0
0
mirror of https://github.com/thegeeklab/wp-git-action.git synced 2024-11-25 09:00:40 +00:00
wp-git-action/git/utils.go

104 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/exec"
2019-06-07 10:32:16 +00:00
"os/user"
"path/filepath"
"strings"
2019-06-07 10:32:16 +00:00
)
const netrcFile = `
machine %s
login %s
password %s
`
const configFile = `
Host *
StrictHostKeyChecking no
UserKnownHostsFile=/dev/null
`
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
2022-11-27 13:33:39 +00:00
if err := os.MkdirAll(sshpath, 0o700); 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),
2022-11-27 13:33:39 +00:00
0o700,
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
2022-11-27 13:33:39 +00:00
if err := os.WriteFile(
2019-06-07 10:32:16 +00:00
privpath,
[]byte(privateKey),
2022-11-27 13:33:39 +00:00
0o600,
2019-06-07 10:32:16 +00:00
); err != nil {
return err
}
return nil
}
// 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),
2022-11-27 13:33:39 +00:00
0o600,
2019-06-07 10:32:16 +00:00
)
}
func trace(cmd *exec.Cmd) {
fmt.Fprintf(os.Stdout, "+ %s\n", strings.Join(cmd.Args, " "))
}
func runCommand(cmd *exec.Cmd) error {
if cmd.Stdout == nil {
cmd.Stdout = os.Stdout
}
if cmd.Stderr == nil {
cmd.Stderr = os.Stderr
}
trace(cmd)
return cmd.Run()
}