cpg1111/maestro

View on GitHub
util/commit.go

Summary

Maintainability
A
0 mins
Test Coverage
/*
Copyright 2016 Christian Grabowski All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package util

import (
    "strings"

    git "gopkg.in/libgit2/git2go.v24"
)

// GHWorkingCommit is for new branches on Github that have this a previous commit
const GHWorkingCommit = "0000000000000000000000000000000000000000"

// CommitToTree takes a commit hash and fetches its git tree
func CommitToTree(repo *git.Repository, hash string) (*git.Tree, error) {
    var (
        commit    *git.Commit
        lookupErr error
    )
    if strings.Compare(hash, GHWorkingCommit) == 0 {
        ref, err := repo.Head()
        if err != nil {
            return nil, err
        }
        oid := ref.Target()
        commit, lookupErr = repo.LookupCommit(oid)
    } else {
        commitObj, commitErr := repo.RevparseSingle(hash)
        if commitErr != nil {
            return nil, commitErr
        }
        commitID := commitObj.Id()
        commit, lookupErr = repo.LookupCommit(commitID)
    }
    if lookupErr != nil {
        return nil, lookupErr
    }
    return commit.Tree()
}