Added create command's skeleton

This commit is contained in:
Christian Muehlhaeuser 2018-03-10 22:29:11 +01:00
parent 3307087412
commit e5faf1ffa5
2 changed files with 60 additions and 3 deletions

View File

@ -2,25 +2,65 @@ package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
type CreateOptions struct {
Executable string
Description string
WorkingDirectory string
User string
Group string
RestartSec uint
Restart string
After string
WantedBy string
}
var (
createOpts = CreateOptions{}
createCmd = &cobra.Command{
Use: "create <executable>",
Use: "create <executable> <description>",
Short: "creates a new Unit file",
Long: `The create command creates a new systemd Unit file`,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return fmt.Errorf("create needs an executable to create a Unit file for")
var err error
if len(args) >= 1 {
createOpts.Executable = args[0]
} else {
createOpts.Executable, err = readString("Which executable do you want to create a service for", true)
if err != nil {
return fmt.Errorf("create needs an executable to create a service for")
}
}
stat, err := os.Stat(createOpts.Executable)
if os.IsNotExist(err) {
return fmt.Errorf("Can't create service: no such file")
}
if stat.IsDir() {
return fmt.Errorf("Can't create service: target is a directory")
}
if stat.Mode()&0111 == 0 {
return fmt.Errorf("Can't create service: target is not executable")
}
if len(args) >= 2 {
createOpts.Description = args[1]
} else {
createOpts.Description, _ = readString("Description", true)
}
if len(createOpts.Description) == 0 {
return fmt.Errorf("create needs a description for this service")
}
return executeCreate()
},
}

17
main.go
View File

@ -1,7 +1,11 @@
package main
import (
"bufio"
"errors"
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
)
@ -16,6 +20,19 @@ var (
}
)
func readString(prompt string, required bool) (string, error) {
reader := bufio.NewReader(os.Stdin)
fmt.Printf("%s: ", prompt)
text, err := reader.ReadString('\n')
text = strings.TrimSpace(text)
if required && len(text) == 0 {
return "", errors.New("Required string is empty")
}
return text, err
}
func main() {
if err := RootCmd.Execute(); err != nil {
os.Exit(-1)