@@ -3,13 +3,15 @@ package cmd
33import (
44 "fmt"
55 "os"
6- "runtime"
76
7+ fakeruntime "github.com/linuxsuren/go-fake-runtime"
88 "github.com/spf13/cobra"
99)
1010
11- func createServiceCommand () (c * cobra.Command ) {
12- opt := & serviceOption {}
11+ func createServiceCommand (execer fakeruntime.Execer ) (c * cobra.Command ) {
12+ opt := & serviceOption {
13+ Execer : execer ,
14+ }
1315 c = & cobra.Command {
1416 Use : "service" ,
1517 Aliases : []string {"s" },
@@ -18,28 +20,47 @@ func createServiceCommand() (c *cobra.Command) {
1820 RunE : opt .runE ,
1921 }
2022 flags := c .Flags ()
21- flags .StringVarP (& opt .action , "action" , "a" , "" , "The action of service, support actions: install" )
23+ flags .StringVarP (& opt .action , "action" , "a" , "" , "The action of service, support actions: install, start, stop, restart, status" )
24+ flags .StringVarP (& opt .scriptPath , "script-path" , "" , "/lib/systemd/system/atest.service" , "The service script file path" )
2225 return
2326}
2427
2528type serviceOption struct {
26- action string
29+ action string
30+ scriptPath string
31+ fakeruntime.Execer
2732}
2833
2934func (o * serviceOption ) preRunE (c * cobra.Command , args []string ) (err error ) {
30- if runtime . GOOS != "linux" {
35+ if o . Execer . OS () != "linux" {
3136 err = fmt .Errorf ("only support on Linux" )
3237 }
38+ if o .action == "" && len (args ) > 0 {
39+ o .action = args [0 ]
40+ }
3341 return
3442}
3543
3644func (o * serviceOption ) runE (c * cobra.Command , args []string ) (err error ) {
45+ var output string
3746 switch o .action {
3847 case "install" , "i" :
39- err = os .WriteFile ("/lib/systemd/system/atest.service" , []byte (script ), os .ModeAppend )
48+ err = os .WriteFile (o .scriptPath , []byte (script ), os .ModeAppend )
49+ case "start" :
50+ output , err = o .Execer .RunCommandAndReturn ("systemctl" , "" , "start" , "atest" )
51+ case "stop" :
52+ output , err = o .Execer .RunCommandAndReturn ("systemctl" , "" , "stop" , "atest" )
53+ case "restart" :
54+ output , err = o .Execer .RunCommandAndReturn ("systemctl" , "" , "restart" , "atest" )
55+ case "status" :
56+ output , err = o .Execer .RunCommandAndReturn ("systemctl" , "" , "status" , "atest" )
4057 default :
4158 err = fmt .Errorf ("not support action: '%s'" , o .action )
4259 }
60+
61+ if output != "" {
62+ c .Println (output )
63+ }
4364 return
4465}
4566
0 commit comments