-
Notifications
You must be signed in to change notification settings - Fork 235
/
netrc.go
71 lines (60 loc) · 1.54 KB
/
netrc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package getter
import (
"fmt"
"net/url"
"os"
"runtime"
"syscall"
"github.com/bgentry/go-netrc/netrc"
"github.com/mitchellh/go-homedir"
)
// addAuthFromNetrc adds auth information to the URL from the user's
// netrc file if it can be found. This will only add the auth info
// if the URL doesn't already have auth info specified and the
// the username is blank.
func addAuthFromNetrc(u *url.URL) error {
// If the URL already has auth information, do nothing
if u.User != nil && u.User.Username() != "" {
return nil
}
// Get the netrc file path
path := os.Getenv("NETRC")
if path == "" {
filename := ".netrc"
if runtime.GOOS == "windows" {
filename = "_netrc"
}
var err error
path, err = homedir.Expand("~/" + filename)
if err != nil {
return err
}
}
// If the file is not a file, then do nothing
if fi, err := os.Stat(path); err != nil {
// File doesn't exist, do nothing
if serr, ok := err.(*os.PathError); ok && (os.IsNotExist(serr.Err) || serr.Err == syscall.ENOTDIR) {
return nil
}
// Some other error!
return err
} else if fi.IsDir() {
// File is directory, ignore
return nil
}
// Load up the netrc file
net, err := netrc.ParseFile(path)
if err != nil {
return fmt.Errorf("Error parsing netrc file at %q: %s", path, err)
}
machine := net.FindMachine(u.Host)
if machine == nil {
// Machine not found, no problem
return nil
}
// Set the user info
u.User = url.UserPassword(machine.Login, machine.Password)
return nil
}