/
ish.go
60 lines (55 loc) · 1.29 KB
/
ish.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright 2014 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
package ggit
import (
"bytes"
"crypto/sha1"
"fmt"
"io/ioutil"
)
var readFile = ioutil.ReadFile
func CommitishToHash(committish string) string {
if len(committish) <= sha1.Size*2 {
allHex := true
for _, c := range committish {
if c < '0' && c > '9' && c < 'a' && c > 'f' {
allHex = false
break
}
}
if allHex {
return committish
}
}
if committish == "HEAD" {
h, err := readFile(".git/HEAD")
if err != nil {
panic(err)
}
if bytes.HasPrefix(h, []byte(refPrefix)) {
ref := h[len(refPrefix):]
if bytes.HasPrefix(ref, []byte("refs/heads/")) {
ref = ref[len("refs/heads/"):]
branches, err := ReadBranches()
if err != nil {
panic(err)
}
for _, b := range branches {
if bytes.HasPrefix(ref, []byte(b.Name)) {
return b.Hash
}
}
panic(fmt.Sprintf("unknown ref %s", string(ref)))
} else {
panic(fmt.Sprintf("no idea how to handle ref %s", string(ref)))
}
}
if len(h) < sha1.Size*2 {
panic(fmt.Sprintf(".git/HEAD too short: %d", len(h)))
}
return string(h[:sha1.Size*2])
}
return ""
}