-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
272 lines (213 loc) · 5.46 KB
/
main.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package main
import (
"bytes"
"crypto/sha1"
"encoding/hex"
"flag"
"fmt"
"log"
"os"
"os/exec"
"regexp"
"runtime"
"strconv"
"sync"
"time"
)
var invalidKey = regexp.MustCompile(`^(commit|tree|parent|author|committer|encoding)\b|[^a-zA-Z0-9]`).MatchString
var validPrefix = regexp.MustCompile("^[0-9a-f]{1,40}$").MatchString
func main() {
log.SetFlags(log.Ltime | log.Lmsgprefix)
log.SetPrefix("| ")
commit := flag.String("commit", "HEAD", "Starting point")
prefix := flag.String("prefix", "", "Desired hash prefix (mandatory)")
key := flag.String("key", "", "Key used in the commit header (defaults to the prefix)")
reset := flag.Bool("reset", false, "If set, reset to the new commit (implies -write)")
write := flag.Bool("write", false, "If set, write the new commit to the repository (hash-object -w)")
startN := flag.Int("start", 0, "Iteration to start from")
flag.Parse()
if *prefix == "" {
fmt.Fprintln(os.Stderr, "missing prefix")
fmt.Fprintln(os.Stderr)
flag.Usage()
os.Exit(1)
}
if !validPrefix(*prefix) {
fmt.Fprintln(os.Stderr, "invalid prefix (must be lowercase hex)")
fmt.Fprintln(os.Stderr)
flag.Usage()
os.Exit(1)
}
if *key == "" {
*key = *prefix
}
if invalidKey(*key) {
fmt.Fprintln(os.Stderr, "invalid key")
fmt.Fprintln(os.Stderr)
flag.Usage()
os.Exit(1)
}
if *startN < 0 {
fmt.Fprintln(os.Stderr, "starting iteration must be positive")
os.Exit(1)
}
log.Printf("Using commit at %s (%s)", *commit, revParseShort(*commit))
log.Printf("Finding hash prefixed %q", *prefix)
commitData := fetchCommit(*commit)
ts := thousandSeparate
log.Printf("Commit size %s bytes", ts(len(commitData)))
if *startN > 0 {
log.Printf("Starting at iteration %d", *startN)
}
start := time.Now()
hash, iteration, newCommit := find(*prefix, *key, *startN, commitData)
duration := time.Since(start)
log.Printf("Tested %s commits at %s commits per second", ts((iteration - *startN + 1)), ts(int(float64(iteration-*startN+1)/duration.Seconds())))
log.Printf("Found %s (iteration %d, %s)", hash, iteration, duration.Round(time.Millisecond))
if *write || *reset {
writtenHash := writeCommit(newCommit)
log.Println("Commit object written")
if hash != writtenHash {
fmt.Printf("hash mismatch: git-vanity-commit %q vs. hash-object output %q\n", hash, writtenHash)
os.Exit(1)
}
}
if *reset {
resetTo(hash)
log.Printf("HEAD is now at %s", hash)
}
}
func revParseShort(rev string) string {
out, err := exec.Command("git", "rev-parse", "--short=12", "--verify", rev).Output()
if err != nil {
log.Fatalf("cannot find commit: %v", err)
}
return string(bytes.TrimSpace(out))
}
func fetchCommit(ref string) []byte {
out, err := exec.Command("git", "cat-file", "-p", ref).Output()
if err != nil {
log.Fatal(err)
}
return out
}
func find(hashPrefix, header string, startN int, commit []byte) (hash string, iteration int, newCommit []byte) {
done := make(chan struct{})
type res struct {
hash string
n int
b []byte
}
found := make(chan res)
var firstN int
var wg sync.WaitGroup
work := func(offset, stepSize int) {
defer wg.Done()
h := sha1.New()
head, tail := headTail(commit)
head = trimHeader(head, header)
dst := make([]byte, sha1.Size*2)
scratch := make([]byte, 0, sha1.Size)
for n := offset; ; n += stepSize {
nStr := strconv.Itoa(n)
commitSize := len(head) + len(tail) + len(header) + 1 + len(nStr) + 1
h.Write([]byte("commit " + strconv.Itoa(commitSize) + "\x00"))
h.Write(head)
h.Write([]byte("\n" + header + " " + nStr))
h.Write(tail)
candidate := h.Sum(scratch[:0])
hex.Encode(dst, candidate)
if bytes.Equal(dst[:len(hashPrefix)], []byte(hashPrefix)) {
buf := new(bytes.Buffer)
buf.Write(head)
buf.Write([]byte("\n" + header + " " + nStr))
buf.Write(tail)
found <- res{string(dst), n, buf.Bytes()}
return
}
h.Reset()
select {
case <-done:
if n > firstN {
return
}
default:
}
}
}
workers := runtime.GOMAXPROCS(0)
if numCPU := runtime.NumCPU(); workers > numCPU {
workers = numCPU
}
wg.Add(workers)
log.Printf("Using %d concurrent workers", workers)
for i := startN; i < startN+workers; i++ {
go work(i, workers)
}
go func() {
wg.Wait()
close(found)
}()
minRes := <-found
firstN = minRes.n
close(done)
for r := range found {
if r.n < minRes.n {
minRes = r
}
}
return minRes.hash, minRes.n, minRes.b
}
func headTail(commit []byte) (head, tail []byte) {
idx := bytes.Index(commit, []byte("\n\n"))
if idx == -1 {
log.Fatal("cannot parse commit")
}
return commit[:idx], commit[idx:]
}
func trimHeader(head []byte, header string) []byte {
idx := bytes.LastIndex(head, []byte("\n"))
if idx == -1 {
return head
}
if bytes.HasPrefix(head[idx+1:], []byte(header)) {
return head[:idx]
}
return head
}
func writeCommit(commit []byte) (hash string) {
cmd := exec.Command("git", "hash-object", "--stdin", "-t", "commit", "-w")
stdin, err := cmd.StdinPipe()
if err != nil {
log.Fatal(err)
}
go func() {
stdin.Write(commit)
stdin.Close()
}()
out, err := cmd.Output()
if err != nil {
log.Fatal(err)
}
return string(bytes.TrimSpace(out))
}
func resetTo(hash string) {
if err := exec.Command("git", "reset", hash).Run(); err != nil {
log.Fatal(err)
}
}
func thousandSeparate(n int) string {
var newS string
if n < 0 {
n = -n
newS = "-"
}
s := strconv.Itoa(n)
for n := range s {
if n != 0 && n%3 == len(s)%3 {
newS += ","
}
newS += string(s[n])
}
return newS
}