-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
370 lines (297 loc) · 7.88 KB
/
main.go
File metadata and controls
370 lines (297 loc) · 7.88 KB
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package main
import (
"bytes"
"crypto/sha1"
"encoding/hex"
"flag"
"fmt"
"hash"
"io"
"log"
"os"
"os/exec"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"time"
"unsafe"
)
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)")
printHash := flag.Bool("print", false, "Print the commit hash found to stdout")
quiet := flag.Bool("quiet", false, "Suppress log output")
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)
}
if *quiet {
log.SetOutput(io.Discard)
}
commitData := fetchCommit(*commit)
log.Printf("Using commit at %s (%s)", *commit, revParseShort(*commit))
log.Printf("Finding hash prefixed %q", *prefix)
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, ok := find(*prefix, *key, *startN, commitData)
if !ok {
log.Println("No hash found")
os.Exit(1)
}
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 *printHash {
fmt.Println(hash)
}
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 {
if eErr, ok := err.(*exec.ExitError); ok {
log.Fatalf("error parsing revision; git says %v", string(eErr.Stderr))
} else {
log.Fatalf("error parsing revision: %v", err)
}
}
return string(bytes.TrimSpace(out))
}
func fetchCommit(ref string) []byte {
shortRef := revParseShort(ref)
out, err := exec.Command("git", "cat-file", "-t", ref).Output()
if err != nil {
if eErr, ok := err.(*exec.ExitError); ok {
log.Fatalf("error reading object type; git says %v", string(eErr.Stderr))
} else {
log.Fatalf("error reading object type: %v", err)
}
}
if got, want := strings.TrimSpace(string(out)), "commit"; got != want {
log.Fatalf("%s is a %s object; expected a commit", shortRef, got)
}
out, err = exec.Command("git", "cat-file", "commit", ref).Output()
if err != nil {
if eErr, ok := err.(*exec.ExitError); ok {
log.Fatalf("error reading commit; git says %v", string(eErr.Stderr))
} else {
log.Fatalf("error reading commit: %v", err)
}
}
return out
}
func find(hashPrefix, header string, startN int, commit []byte) (hash string, iteration int, newCommit []byte, ok bool) {
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)
scratch := make([]byte, 0, sha1.Size)
commitHeaderBytes := []byte("commit ")
headerBytes := []byte("\n" + header + " ")
nullByte := []byte{0x00}
hashMask := byte(0xff)
var suffix string
if len(hashPrefix)%2 != 0 {
hashMask = 0xf0
suffix = "0"
}
hashPrefixBytes, _ := hex.DecodeString(hashPrefix + suffix)
var nBytes []byte
var commitSizeBytes []byte
var lastCommitSize int
lastH := sha1.New()
for n := offset; n >= 0; n += stepSize {
nBytes = strconv.AppendInt(nBytes[:0], int64(n), 10)
commitSize := len(head) + len(tail) + len(header) + 1 + len(nBytes) + 1
if lastCommitSize != commitSize {
h.Reset()
commitSizeBytes = strconv.AppendInt(commitSizeBytes[:0], int64(commitSize), 10)
h.Write(commitHeaderBytes)
h.Write(commitSizeBytes)
h.Write(nullByte)
h.Write(head)
h.Write(headerBytes)
copySHA1Hash(lastH, h)
lastCommitSize = commitSize
}
copySHA1Hash(h, lastH)
h.Write(nBytes)
h.Write(tail)
candidate := h.Sum(scratch[:0])
if bytes.HasPrefix(candidate, hashPrefixBytes[:len(hashPrefixBytes)-1]) &&
candidate[len(hashPrefixBytes)-1]&hashMask == hashPrefixBytes[len(hashPrefixBytes)-1]&hashMask {
buf := new(bytes.Buffer)
buf.Write(head)
buf.Write(headerBytes)
buf.Write(nBytes)
buf.Write(tail)
found <- res{hex.EncodeToString(candidate), n, buf.Bytes()}
return
}
select {
case <-done:
if n > firstN {
return
}
default:
}
}
}
workers := runtime.GOMAXPROCS(0)
if numCPU := runtime.NumCPU(); workers > numCPU {
workers = numCPU
}
log.Printf("Using %d concurrent workers", workers)
for i := range workers {
offset := startN + i
if offset < 0 {
break
}
wg.Add(1)
go work(offset, workers)
}
go func() {
wg.Wait()
close(found)
}()
minRes, ok := <-found
firstN = minRes.n
close(done)
for r := range found {
if r.n < minRes.n {
minRes = r
}
}
return minRes.hash, minRes.n, minRes.b, ok
}
func copySHA1Hash(dst, src hash.Hash) {
type eface struct {
_type uintptr
data unsafe.Pointer
}
type digest struct {
h [5]uint32
x [64]byte
nx int
len uint64
}
*(*digest)((*eface)(unsafe.Pointer(&dst)).data) = *(*digest)((*eface)(unsafe.Pointer(&src)).data)
}
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 {
if eErr, ok := err.(*exec.ExitError); ok {
log.Fatalf("error writing object; git says %v", string(eErr.Stderr))
} else {
log.Fatalf("error writing object: %v", err)
}
}
return string(bytes.TrimSpace(out))
}
func resetTo(hash string) {
if err := exec.Command("git", "reset", hash).Run(); err != nil {
if eErr, ok := err.(*exec.ExitError); ok {
log.Fatalf("error resetting to commit; git says %v", string(eErr.Stderr))
} else {
log.Fatalf("error resettting to commit: %v", 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
}