Add working directory

This commit is contained in:
Justin Hawkins 2022-11-24 19:29:20 +10:30
parent 2950e72101
commit 35d8969953
2 changed files with 16 additions and 9 deletions

View File

@ -4,6 +4,7 @@
Description={{ .description }} Description={{ .description }}
[Service] [Service]
WorkingDirectory={{ .workingDirectory }}
ExecStart={{ .execStart }} ExecStart={{ .execStart }}
[Install] [Install]

View File

@ -8,6 +8,7 @@ import (
"io" "io"
"os" "os"
"os/exec" "os/exec"
"path"
"regexp" "regexp"
"strings" "strings"
"text/template" "text/template"
@ -17,8 +18,9 @@ import (
var fs embed.FS var fs embed.FS
type Unit struct { type Unit struct {
name string name string
binary string binary string
binaryPath string
systemCtlPath string // path to systemctl command systemCtlPath string // path to systemctl command
unitFilePath string unitFilePath string
@ -37,9 +39,11 @@ func NewUnit(unitName string, unitOpts ...UnitOpts) (Unit, error) {
if !ok { if !ok {
return Unit{}, fmt.Errorf("sorry, name '%s' is not valid", unitName) return Unit{}, fmt.Errorf("sorry, name '%s' is not valid", unitName)
} }
path, binPath := binaryInfo()
u := Unit{ u := Unit{
name: unitName, name: unitName,
binary: binaryName(), binary: binPath,
binaryPath: path,
} }
if len(unitOpts) > 0 { if len(unitOpts) > 0 {
@ -91,8 +95,9 @@ func (u Unit) writeTemplate(f io.Writer) error {
} }
data := map[string]string{ data := map[string]string{
"description": u.name, "description": u.name,
"execStart": u.binary, "execStart": u.binary,
"workingDirectory": u.binaryPath,
} }
err = t.ExecuteTemplate(f, "basic.service", data) err = t.ExecuteTemplate(f, "basic.service", data)
return err return err
@ -163,14 +168,15 @@ func (u Unit) runExpectZero(command string, args ...string) error {
return nil return nil
} }
// binaryName returns the fully-qualified path to the binary on disk // binaryName returns the fully-qualified path to the binary and the qualified path of the binary
func binaryName() string { func binaryInfo() (string, string) {
binary, err := os.Executable() binary, err := os.Executable()
if err != nil { if err != nil {
panic(err) panic(err)
} }
dir, file := path.Split(binary)
return binary return dir, dir + file
} }
func checkName(name string) bool { func checkName(name string) bool {