src-d / go-git

Project has been moved to: https://github.com/go-git/go-git
https://github.com/go-git/go-git
Apache License 2.0
4.9k stars 541 forks source link

ResolveRevision doesn't resolve on abbreviated unique hashes #1148

Open mroth opened 5 years ago

mroth commented 5 years ago

As per the gitrevisions documentation (https://mirrors.edge.kernel.org/pub/software/scm/git/docs/gitrevisions.html), abbreviated SHA "leading substring that is unique within the repository" should be resolved:

<sha1>, e.g. dae86e1950b1277e545cee180551750029cfe735, dae86e The full SHA-1 object name (40-byte hexadecimal string), or a leading substring that is unique within the repository. E.g. dae86e1950b1277e545cee180551750029cfe735 and dae86e both name the same commit object if there is no other object in your repository whose object name starts with dae86e.

However, ResolveRevision() in go-git will error if given a rev string which is not the full 40 characters.

Quick sample code to run within a repo:

package main

import (
    "fmt"

    "gopkg.in/src-d/go-git.v4"
    "gopkg.in/src-d/go-git.v4/plumbing"
)

func main() {
    r, _ := git.PlainOpen(".")
    head, _ := r.Head()
    hashString := head.Hash().String()
    shortHash := hashString[:8]

    logAttemptedResolve(r, plumbing.Revision(hashString))
    logAttemptedResolve(r, plumbing.Revision(shortHash))
}

func logAttemptedResolve(r *git.Repository, rev plumbing.Revision) {
    hash, err := r.ResolveRevision(rev)
    fmt.Printf(`
attempted to resolve %v
    got: %v
    error: %v
`, rev, hash, err)
}

Produces:

attempted to resolve 2c46957dd2fdd7daf8502a27b4e7c0bfbfb15e51
    got: 2c46957dd2fdd7daf8502a27b4e7c0bfbfb15e51
    error: <nil>

attempted to resolve 2c46957d
    got: 0000000000000000000000000000000000000000
    error: reference not found
jacobcase commented 5 years ago

I'm also affected by this issue. I'm working on an application has a workflow that allows people to plugin short hashes that are expected to resolve to a commit.