1 // netrc -- parse .netrc file
2 // Copyright 2018 The Go Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
6 // netrc library parses .netrc file. It is copy-paste of
7 // golang.org/x/tools/cmd/auth/netrcauth.
9 // See https://www.gnu.org/software/inetutils/manual/html_node/The-_002enetrc-file.html
10 // for documentation on the .netrc format.
25 func Parse(data string) []Line {
29 for _, line := range strings.Split(data, "\n") {
36 f := strings.Fields(line)
38 for ; i < len(f)-1; i += 2 {
39 // Reset at each "machine" token.
40 // "The auto-login process searches the .netrc file for a machine token
41 // that matches […]. Once a match is made, the subsequent .netrc tokens
42 // are processed, stopping when the end of file is reached or another
43 // machine or a default token is encountered."
46 l = Line{Machine: f[i+1]}
54 // "A macro is defined with the specified name; its contents begin with
55 // the next .netrc line and continue until a null line (consecutive
56 // new-line characters) is encountered."
59 if l.Machine != "" && l.Login != "" && l.Password != "" {
64 if i < len(f) && f[i] == "default" {
65 // "There can be only one default token, and it must be after all machine tokens."
72 func Path() (netrc string) {
73 p, ok := os.LookupEnv("NETRC")
77 homeDir, _ := os.UserHomeDir()
78 return path.Join(homeDir, ".netrc")
81 func Find(host string) (login string, password string) {
82 data, err := os.ReadFile(Path())
86 for _, l := range Parse(string(data)) {
87 if l.Machine == host {
88 return l.Login, l.Password