0
0
mirror of https://github.com/thegeeklab/wp-git-action.git synced 2024-11-13 22:50:41 +00:00
wp-git-action/git/utils.go

108 lines
1.5 KiB
Go
Raw Normal View History

2022-11-27 13:33:39 +00:00
package git
2019-06-07 10:32:16 +00:00
import (
"fmt"
"os"
"os/user"
"path/filepath"
"strings"
"golang.org/x/sys/execabs"
2019-06-07 10:32:16 +00:00
)
const (
netrcFile = `
2019-06-07 10:32:16 +00:00
machine %s
login %s
password %s
`
configFile = `
2019-06-07 10:32:16 +00:00
Host *
StrictHostKeyChecking no
UserKnownHostsFile=/dev/null
`
)
const (
strictFilePerm = 0o600
strictDirPerm = 0o600
)
2019-06-07 10:32:16 +00:00
2022-11-27 13:33:39 +00:00
// WriteKey writes the SSH private key.
func WriteSSHKey(privateKey string) error {
2019-06-07 10:32:16 +00:00
home := "/root"
if currentUser, err := user.Current(); err == nil {
home = currentUser.HomeDir
}
sshpath := filepath.Join(home, ".ssh")
2019-06-07 10:32:16 +00:00
if err := os.MkdirAll(sshpath, strictDirPerm); err != nil {
2019-06-07 10:32:16 +00:00
return err
}
confpath := filepath.Join(sshpath, "config")
2019-06-07 10:32:16 +00:00
2022-11-27 13:33:39 +00:00
if err := os.WriteFile(
2019-06-07 10:32:16 +00:00
confpath,
[]byte(configFile),
strictFilePerm,
2019-06-07 10:32:16 +00:00
); err != nil {
return err
}
privpath := filepath.Join(sshpath, "id_rsa")
2019-06-07 10:32:16 +00:00
return os.WriteFile(
2019-06-07 10:32:16 +00:00
privpath,
[]byte(privateKey),
strictFilePerm,
)
2019-06-07 10:32:16 +00:00
}
// WriteNetrc writes the netrc file.
func WriteNetrc(machine, login, password string) error {
netrcContent := fmt.Sprintf(
netrcFile,
machine,
login,
password,
)
home := "/root"
if currentUser, err := user.Current(); err == nil {
home = currentUser.HomeDir
}
netpath := filepath.Join(
home,
".netrc",
)
2022-11-27 13:33:39 +00:00
return os.WriteFile(
2019-06-07 10:32:16 +00:00
netpath,
[]byte(netrcContent),
strictFilePerm,
2019-06-07 10:32:16 +00:00
)
}
func trace(cmd *execabs.Cmd) {
fmt.Fprintf(os.Stdout, "+ %s\n", strings.Join(cmd.Args, " "))
}
func runCommand(cmd *execabs.Cmd) error {
if cmd.Stdout == nil {
cmd.Stdout = os.Stdout
}
if cmd.Stderr == nil {
cmd.Stderr = os.Stderr
}
trace(cmd)
return cmd.Run()
}