From: Cherry Zhang Date: Tue, 22 Dec 2020 17:40:32 +0000 (-0500) Subject: cmd/pack: r command create output file if not exist X-Git-Tag: go1.16rc1~152 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=0aa9b4709acd609c1a3e9cb028e7f4c4da3f0357;p=gostls13.git cmd/pack: r command create output file if not exist Go 1.15 pack's r command creates the output file if it does not exist. The system "ar" command does this as well. Do the same. For bazelbuild/rules_go#2762. Change-Id: Icd88396b5c714b735c859a29ab29851e4301f4d2 Reviewed-on: https://go-review.googlesource.com/c/go/+/279516 Trust: Cherry Zhang Run-TryBot: Cherry Zhang Reviewed-by: Than McIntosh TryBot-Result: Go Bot --- diff --git a/src/cmd/pack/pack.go b/src/cmd/pack/pack.go index 3dffabe5ec..412ea36d60 100644 --- a/src/cmd/pack/pack.go +++ b/src/cmd/pack/pack.go @@ -43,7 +43,7 @@ func main() { ar = openArchive(os.Args[2], os.O_RDONLY, os.Args[3:]) ar.scan(ar.printContents) case 'r': - ar = openArchive(os.Args[2], os.O_RDWR, os.Args[3:]) + ar = openArchive(os.Args[2], os.O_RDWR|os.O_CREATE, os.Args[3:]) ar.addFiles() case 'c': ar = openArchive(os.Args[2], os.O_RDWR|os.O_TRUNC|os.O_CREATE, os.Args[3:]) @@ -124,10 +124,13 @@ func openArchive(name string, mode int, files []string) *Archive { log.Fatal(err) } var a *archive.Archive - if mode&os.O_CREATE != 0 { // the c command + if mode&os.O_TRUNC != 0 { // the c command a, err = archive.New(f) } else { a, err = archive.Parse(f, verbose) + if err != nil && mode&os.O_CREATE != 0 { // the r command + a, err = archive.New(f) + } } if err != nil { log.Fatal(err) diff --git a/src/cmd/pack/pack_test.go b/src/cmd/pack/pack_test.go index 16a5135800..118376f9df 100644 --- a/src/cmd/pack/pack_test.go +++ b/src/cmd/pack/pack_test.go @@ -303,7 +303,7 @@ func TestIssue21703(t *testing.T) { } // Test the "c" command can "see through" the archive generated by the compiler. -// This is peculiar. (See issue ) +// This is peculiar. (See issue #43271) func TestCreateWithCompilerObj(t *testing.T) { testenv.MustHaveGoBuild(t) @@ -368,6 +368,29 @@ func TestCreateWithCompilerObj(t *testing.T) { } } +// Test the "r" command creates the output file if it does not exist. +func TestRWithNonexistentFile(t *testing.T) { + testenv.MustHaveGoBuild(t) + + dir := tmpDir(t) + defer os.RemoveAll(dir) + src := filepath.Join(dir, "p.go") + prog := "package p; var X = 42\n" + err := os.WriteFile(src, []byte(prog), 0666) + if err != nil { + t.Fatal(err) + } + + run := func(args ...string) string { + return doRun(t, dir, args...) + } + + goBin := testenv.GoToolPath(t) + run(goBin, "build", "cmd/pack") // writes pack binary to dir + run(goBin, "tool", "compile", "-o", "p.o", "p.go") + run("./pack", "r", "p.a", "p.o") // should succeed +} + // doRun runs a program in a directory and returns the output. func doRun(t *testing.T, dir string, args ...string) string { cmd := exec.Command(args[0], args[1:]...)