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