Skip to content

Commit

Permalink
cmd/go/internal/auth: use sync.OnceValues
Browse files Browse the repository at this point in the history
Use sync.OnceValues (CL 451356, since Go 1.21) instead of sync.Once for
cleaner code and less global variables, preventing their potential
misuse.

Change-Id: I9d7ccc42847fe77af1757672c31bb39e20007f92
Reviewed-on: https://go-review.googlesource.com/c/go/+/611016
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
  • Loading branch information
kolyshkin authored and gopherbot committed Sep 6, 2024
1 parent e6ae2d8 commit ba2a16c
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 15 deletions.
6 changes: 5 additions & 1 deletion src/cmd/go/internal/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,17 @@ import "net/http"
// AddCredentials fills in the user's credentials for req, if any.
// The return value reports whether any matching credentials were found.
func AddCredentials(req *http.Request) (added bool) {
netrc, _ := readNetrc()
if len(netrc) == 0 {
return false
}

host := req.Host
if host == "" {
host = req.URL.Hostname()
}

// TODO(golang.org/issue/26232): Support arbitrary user-provided credentials.
netrcOnce.Do(readNetrc)
for _, l := range netrc {
if l.machine == host {
req.SetBasicAuth(l.login, l.password)
Expand Down
21 changes: 7 additions & 14 deletions src/cmd/go/internal/auth/netrc.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,6 @@ type netrcLine struct {
password string
}

var (
netrcOnce sync.Once
netrc []netrcLine
netrcErr error
)

func parseNetrc(data string) []netrcLine {
// See https://www.gnu.org/software/inetutils/manual/html_node/The-_002enetrc-file.html
// for documentation on the .netrc format.
Expand Down Expand Up @@ -91,20 +85,19 @@ func netrcPath() (string, error) {
return filepath.Join(dir, base), nil
}

func readNetrc() {
var readNetrc = sync.OnceValues(func() ([]netrcLine, error) {
path, err := netrcPath()
if err != nil {
netrcErr = err
return
return nil, err
}

data, err := os.ReadFile(path)
if err != nil {
if !os.IsNotExist(err) {
netrcErr = err
if os.IsNotExist(err) {
err = nil
}
return
return nil, err
}

netrc = parseNetrc(string(data))
}
return parseNetrc(string(data)), nil
})

0 comments on commit ba2a16c

Please sign in to comment.