Source file src/cmd/buildid/buildid.go

     1  // Copyright 2017 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     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  	// Keep in sync with src/cmd/go/internal/work/buildid.go:updateBuildID
    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  	newID := id[:strings.LastIndex(id, "/")] + "/" + buildid.HashToString(hash)
    57  	if len(newID) != len(id) {
    58  		log.Fatalf("%s: build ID length mismatch %q vs %q", file, id, newID)
    59  	}
    60  
    61  	if len(matches) == 0 {
    62  		return
    63  	}
    64  
    65  	f, err = os.OpenFile(file, os.O_RDWR, 0)
    66  	if err != nil {
    67  		log.Fatal(err)
    68  	}
    69  	if err := buildid.Rewrite(f, matches, newID); err != nil {
    70  		log.Fatal(err)
    71  	}
    72  	if err := f.Close(); err != nil {
    73  		log.Fatal(err)
    74  	}
    75  }
    76  

View as plain text