Source file src/cmd/go/help_test.go

     1  // Copyright 2018 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_test
     6  
     7  import (
     8  	"flag"
     9  	"go/format"
    10  	"internal/diff"
    11  	"internal/testenv"
    12  	"os"
    13  	"strings"
    14  	"testing"
    15  )
    16  
    17  var fixDocs = flag.Bool("fixdocs", false, "if true, update alldocs.go")
    18  
    19  func TestDocsUpToDate(t *testing.T) {
    20  	testenv.MustHaveGoBuild(t)
    21  	if !*fixDocs {
    22  		t.Parallel()
    23  	}
    24  
    25  	// We run 'go help documentation' as a subprocess instead of
    26  	// calling help.Help directly because it may be sensitive to
    27  	// init-time configuration
    28  	cmd := testenv.Command(t, testGo, "help", "documentation")
    29  	// Unset GO111MODULE so that the 'go get' section matches
    30  	// the default 'go get' implementation.
    31  	cmd.Env = append(cmd.Environ(), "GO111MODULE=")
    32  	cmd.Stderr = new(strings.Builder)
    33  	out, err := cmd.Output()
    34  	if err != nil {
    35  		t.Fatalf("%v: %v\n%s", cmd, err, cmd.Stderr)
    36  	}
    37  
    38  	alldocs, err := format.Source(out)
    39  	if err != nil {
    40  		t.Fatalf("format.Source($(%v)): %v", cmd, err)
    41  	}
    42  
    43  	const srcPath = `alldocs.go`
    44  	old, err := os.ReadFile(srcPath)
    45  	if err != nil {
    46  		t.Fatalf("error reading %s: %v", srcPath, err)
    47  	}
    48  	diff := diff.Diff(srcPath, old, "go help documentation | gofmt", alldocs)
    49  	if diff == nil {
    50  		t.Logf("%s is up to date.", srcPath)
    51  		return
    52  	}
    53  
    54  	if *fixDocs {
    55  		if err := os.WriteFile(srcPath, alldocs, 0666); err != nil {
    56  			t.Fatal(err)
    57  		}
    58  		t.Logf("wrote %d bytes to %s", len(alldocs), srcPath)
    59  	} else {
    60  		t.Logf("\n%s", diff)
    61  		t.Errorf("%s is stale. To update, run 'go generate cmd/go'.", srcPath)
    62  	}
    63  }
    64  

View as plain text