...
1
2
3
4
5 package main
6
7 import (
8 "flag"
9 "fmt"
10 "log"
11 "os"
12 "strings"
13
14 "cmd/internal/buildid"
15 )
16
17 func usage() {
18 fmt.Fprintf(os.Stderr, "usage: go tool buildid [-w] file\n")
19 flag.PrintDefaults()
20 os.Exit(2)
21 }
22
23 var wflag = flag.Bool("w", false, "write build ID")
24
25 func main() {
26 log.SetPrefix("buildid: ")
27 log.SetFlags(0)
28 flag.Usage = usage
29 flag.Parse()
30 if flag.NArg() != 1 {
31 usage()
32 }
33
34 file := flag.Arg(0)
35 id, err := buildid.ReadFile(file)
36 if err != nil {
37 log.Fatal(err)
38 }
39 if !*wflag {
40 fmt.Printf("%s\n", id)
41 return
42 }
43
44
45
46 f, err := os.Open(file)
47 if err != nil {
48 log.Fatal(err)
49 }
50 matches, hash, err := buildid.FindAndHash(f, id, 0)
51 f.Close()
52 if err != nil {
53 log.Fatal(err)
54 }
55
56
57 if !strings.Contains(id, "/") {
58 log.Fatalf("%s: build ID is a legacy format...binary too old for this tool", file)
59 }
60
61 newID := id[:strings.LastIndex(id, "/")] + "/" + buildid.HashToString(hash)
62 if len(newID) != len(id) {
63 log.Fatalf("%s: build ID length mismatch %q vs %q", file, id, newID)
64 }
65
66 if len(matches) == 0 {
67 return
68 }
69
70 f, err = os.OpenFile(file, os.O_RDWR, 0)
71 if err != nil {
72 log.Fatal(err)
73 }
74 if err := buildid.Rewrite(f, matches, newID); err != nil {
75 log.Fatal(err)
76 }
77 if err := f.Close(); err != nil {
78 log.Fatal(err)
79 }
80 }
81
View as plain text