push-to-dokku/services.go

99 lines
1.9 KiB
Go
Raw Normal View History

package main
import (
"bytes"
"fmt"
"github.com/bitfield/script"
"log"
"os"
"text/template"
)
type Services struct {
cfg config
}
func NewServices(cfg config) *Services {
return &Services{cfg: cfg}
}
func (s *Services) AddPrivateKey() error {
log.Println("Adding private key")
if err := script.Exec(`mkdir -p $HOME/.ssh`).Error(); err != nil {
return err
}
if err := script.Exec(`chmod 700 $HOME/.ssh`).Error(); err != nil {
return err
}
_, err := script.Echo(s.cfg.PrivateKey).WriteFile(os.ExpandEnv(`${HOME}/.ssh/id_rsa`))
if err != nil {
return err
}
if err := script.Exec(`chmod -R 400 $HOME/.ssh/.`).Error(); err != nil {
return err
}
return nil
}
func (s *Services) ConfigureSSH() error {
log.Println("Configuring SSH")
var bfr bytes.Buffer
if err := sshConfigTemplate.Execute(&bfr, struct {
Cfg config
Home string
}{
Cfg: s.cfg,
Home: os.Getenv("HOME"),
}); err != nil {
return err
}
if _, err := script.Echo(bfr.String()).WriteFile(os.ExpandEnv(`${HOME}/.ssh/config`)); err != nil {
return err
}
if err := script.Exec(`chmod 400 $HOME/.ssh/config`).Error(); err != nil {
return err
}
return nil
}
func (s *Services) PushRepository() error {
sshUrl := fmt.Sprintf(`dokku@%v`, s.cfg.HostName)
remoteUrl := fmt.Sprintf(`ssh://%v:22/%v`, sshUrl, s.cfg.AppName)
log.Println("Testing Dokku SSH connection")
if err := script.Exec(fmt.Sprintf(`ssh %v version`, sshUrl)).Error(); err != nil {
return err
}
log.Println("SSH connection good. Pushing repository")
if err := script.Exec(fmt.Sprintf(`git remote add dokku '%v'`, remoteUrl)).Error(); err != nil {
return err
}
if err := script.Exec(`git push dokku main`).Error(); err != nil {
return err
}
return nil
}
var (
sshConfigTemplate = template.Must(template.New("ssh-config").Parse(`
Host *
StrictHostKeyChecking no
Host {{.Cfg.Host}}
HostName {{.Cfg.Host}}
User dokku
IdentityFile {{.Home}}/.ssh/id_rsa
`))
)