0
0
mirror of https://github.com/thegeeklab/wp-git-action.git synced 2024-09-20 01:12:47 +02:00
wp-git-action/git/utils.go

112 lines
1.6 KiB
Go
Raw Normal View History

2022-11-27 14:33:39 +01:00
package git
2019-06-07 12:32:16 +02:00
import (
"fmt"
"os"
"os/user"
"path/filepath"
"strings"
"golang.org/x/sys/execabs"
2019-06-07 12:32:16 +02:00
)
const (
netrcFile = `
2019-06-07 12:32:16 +02:00
machine %s
login %s
password %s
`
configFile = `
2019-06-07 12:32:16 +02:00
Host *
StrictHostKeyChecking no
UserKnownHostsFile=/dev/null
`
)
const (
strictFilePerm = 0o600
strictDirPerm = 0o600
)
2019-06-07 12:32:16 +02:00
2022-11-27 14:33:39 +01:00
// WriteKey writes the SSH private key.
func WriteSSHKey(privateKey string) error {
2019-06-07 12:32:16 +02:00
home := "/root"
if currentUser, err := user.Current(); err == nil {
home = currentUser.HomeDir
}
sshpath := filepath.Join(home, ".ssh")
2019-06-07 12:32:16 +02:00
if err := os.MkdirAll(sshpath, strictDirPerm); err != nil {
2019-06-07 12:32:16 +02:00
return err
}
confpath := filepath.Join(sshpath, "config")
2019-06-07 12:32:16 +02:00
2022-11-27 14:33:39 +01:00
if err := os.WriteFile(
2019-06-07 12:32:16 +02:00
confpath,
[]byte(configFile),
strictFilePerm,
2019-06-07 12:32:16 +02:00
); err != nil {
return err
}
privpath := filepath.Join(sshpath, "id_rsa")
2019-06-07 12:32:16 +02:00
2022-11-27 14:33:39 +01:00
if err := os.WriteFile(
2019-06-07 12:32:16 +02:00
privpath,
[]byte(privateKey),
strictFilePerm,
2019-06-07 12:32:16 +02: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 14:33:39 +01:00
return os.WriteFile(
2019-06-07 12:32:16 +02:00
netpath,
[]byte(netrcContent),
strictFilePerm,
2019-06-07 12:32:16 +02: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()
}