63 lines
1.8 KiB
Go
63 lines
1.8 KiB
Go
|
package netrc
|
||
|
|
||
|
import (
|
||
|
"bufio"
|
||
|
"encoding/base64"
|
||
|
"fmt"
|
||
|
"os"
|
||
|
"path"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
type NetrcCredential struct {
|
||
|
Machine string
|
||
|
Login string
|
||
|
Password string
|
||
|
}
|
||
|
|
||
|
func (credential *NetrcCredential) HttpHost() string {
|
||
|
return credential.HttpHostWithPath("")
|
||
|
}
|
||
|
|
||
|
func (credential *NetrcCredential) HttpHostWithPath(path string) string {
|
||
|
return fmt.Sprintf("http://%s%s", credential.Machine, path)
|
||
|
}
|
||
|
|
||
|
func (credential *NetrcCredential) Base64() string {
|
||
|
formattedCredentials := fmt.Sprintf("%s:%s", credential.Login, credential.Password)
|
||
|
credentialBytes := []byte(formattedCredentials)
|
||
|
return base64.StdEncoding.EncodeToString(credentialBytes)
|
||
|
}
|
||
|
|
||
|
func ReadCredentials(host string) (NetrcCredential, error) {
|
||
|
credentials := NetrcCredential{Machine: host}
|
||
|
netrcPath := path.Join(os.Getenv("HOME"), ".netrc")
|
||
|
netrcFile, err := os.Open(netrcPath)
|
||
|
if err != nil {
|
||
|
return credentials, fmt.Errorf("failed to read ~/.netrc: %v", err)
|
||
|
}
|
||
|
defer netrcFile.Close()
|
||
|
scanner := bufio.NewScanner(netrcFile)
|
||
|
extractCredentials := false
|
||
|
for {
|
||
|
if !scanner.Scan() {
|
||
|
break
|
||
|
}
|
||
|
line := scanner.Text()
|
||
|
if strings.HasPrefix(line, "machine ") {
|
||
|
extractCredentials = strings.HasSuffix(line, credentials.Machine)
|
||
|
} else if strings.HasPrefix(line, "login ") && extractCredentials {
|
||
|
credentials.Login = strings.TrimPrefix(line, "login ")
|
||
|
} else if strings.HasPrefix(line, "password ") && extractCredentials {
|
||
|
credentials.Password = strings.TrimPrefix(line, "password ")
|
||
|
}
|
||
|
}
|
||
|
if credentials.Login == "" {
|
||
|
return credentials, fmt.Errorf("error: no login found for host \"%s\" in ~/.netrc", credentials.Machine)
|
||
|
}
|
||
|
if credentials.Password == "" {
|
||
|
return credentials, fmt.Errorf("error: no password found for host \"%s\" in ~/.netrc", credentials.Machine)
|
||
|
}
|
||
|
return credentials, scanner.Err()
|
||
|
}
|