From d1da0661208319071b89aedd92505afae0c81855 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Mart=C3=AD?= Date: Sun, 9 Apr 2023 20:51:49 +0100 Subject: [PATCH] print chosen seed when building with -seed=random The seedFlag.random field had never worked, as my refactor in December 2021 never set it to true. Even if the boolean was working, we only printed the random seed when we failed. It's still useful to see it when a build succeeds, for example when wanting to reproduce the same binary or when wanting to reverse a panic from the produced binary. Add a test this time. Fixes #696. --- main.go | 18 +++++++++++------- testdata/script/seed.txtar | 1 + 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/main.go b/main.go index 95bce4a..74b464e 100644 --- a/main.go +++ b/main.go @@ -78,6 +78,8 @@ func (f seedFlag) String() string { func (f *seedFlag) Set(s string) error { if s == "random" { + f.random = true // to show the random seed we chose + f.bytes = make([]byte, 16) // random 128 bit seed if _, err := cryptorand.Read(f.bytes); err != nil { return fmt.Errorf("error generating random seed: %v", err) @@ -234,18 +236,20 @@ func main1() int { usage() return 2 } + + // If a random seed was used, the user won't be able to reproduce the + // same output or failure unless we print the random seed we chose. + // If the build failed and a random seed was used, + // the failure might not reproduce with a different seed. + // Print it before we exit. + if flagSeed.random { + fmt.Fprintf(os.Stderr, "-seed chosen at random: %s\n", base64.RawStdEncoding.EncodeToString(flagSeed.bytes)) + } if err := mainErr(args); err != nil { if code, ok := err.(errJustExit); ok { return int(code) } fmt.Fprintln(os.Stderr, err) - - // If the build failed and a random seed was used, - // the failure might not reproduce with a different seed. - // Print it before we exit. - if flagSeed.random { - fmt.Fprintf(os.Stderr, "random seed: %s\n", base64.RawStdEncoding.EncodeToString(flagSeed.bytes)) - } return 1 } return 0 diff --git a/testdata/script/seed.txtar b/testdata/script/seed.txtar index d21ba60..0fd4b38 100644 --- a/testdata/script/seed.txtar +++ b/testdata/script/seed.txtar @@ -63,6 +63,7 @@ cp stderr importedpkg-seed-static-2 # Use a random seed, which should always trigger a full build. garble -seed=random build -v +stderr -count=1 '^-seed chosen at random: .+' stderr -count=1 '^runtime$' stderr -count=1 '^test/main$' exec ./main$exe