Skip to content

Commit

Permalink
add daemon; hooks before/after xref-building; bugs;
Browse files Browse the repository at this point in the history
  • Loading branch information
hedzr committed May 25, 2019
1 parent e34052a commit e898428
Show file tree
Hide file tree
Showing 18 changed files with 646 additions and 110 deletions.
37 changes: 36 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,37 @@ A getopt-like parser of command-line options, compatible with the [getopt_long](

- Uses `WalkAllCommands(walker)` to loop commands.

- Daemon

> Uses daemon feature with `go-daemon`

```golang
import "github.com/hedzr/cmdr/plugin/daemon"
func main() {
daemon.Enable(NewDaemon())
if err := cmdr.Exec(rootCmd); err != nil {
log.Fatal("Error:", err)
}
}
func NewDaemon() daemon.Daemon {
return &DaemonImpl{}
}
```
See full codes in [demo](./examples/demo/) app.
```bash
bin/demo server [start|stop|status|restart|install|uninstall]
```
`install`/`uninstall` sub-commands could install `demo` app as a systemd service.
- `ExecWith(rootCmd *RootCommand, beforeXrefBuilding_, afterXrefBuilt_ HookXrefFunc) (err error)`
`AddOnBeforeXrefBuilding(cb)`
`AddOnAfterXrefBuilt(cb)`
- More...
Expand Down Expand Up @@ -142,9 +173,13 @@ A getopt-like parser of command-line options, compatible with the [getopt_long](
## Contrib
*Feel free to issue me bug reports and fixes. Many thanks to all contributors.*
## LICENSE
## License
MIT.
Expand Down
5 changes: 5 additions & 0 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ func (c *Command) IsRoot() bool {
return c == &c.root.Command
}

// GetHitStr returns the matched command string
func (c *Command) GetHitStr() string {
return c.strHit
}

// // HasParent detects whether owner is available or not
// func (c *BaseOpt) HasParent() bool {
// return c.owner != nil
Expand Down
4 changes: 2 additions & 2 deletions def.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,8 @@ var (
globalShowVersion func()
globalShowBuildInfo func()

beforeXrefBuilding HookXrefFunc
afterXrefBuilt HookXrefFunc
beforeXrefBuilding []HookXrefFunc
afterXrefBuilt []HookXrefFunc

// ErrShouldBeStopException tips `Exec()` cancelled the following actions after `PreAction()`
ErrShouldBeStopException = errors.New("should be stop right now")
Expand Down
4 changes: 4 additions & 0 deletions examples/demo/demo/entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ package demo

import (
"github.com/hedzr/cmdr"
"github.com/hedzr/cmdr/examples/demo/svr"
"github.com/hedzr/cmdr/plugin/daemon"
"github.com/sirupsen/logrus"
)

Expand All @@ -21,6 +23,8 @@ func Entry() {
// cmdr.EnableHelpCommands = false
// cmdr.EnableGenerateCommands = false

daemon.Enable(svr.NewDaemon())

if err := cmdr.Exec(rootCmd); err != nil {
logrus.Errorf("Error: %v", err)
}
Expand Down
61 changes: 1 addition & 60 deletions examples/demo/demo/root_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ var (
},
SubCommands: []*cmdr.Command{
// generatorCommands,
serverCommands,
// serverCommands,
msCommands,
},
},
Expand All @@ -48,65 +48,6 @@ var (
Author: "Hedzr Yeh <[email protected]>",
}

serverCommands = &cmdr.Command{
BaseOpt: cmdr.BaseOpt{
// Name: "server",
Short: "s",
Full: "server",
Aliases: []string{"serve", "svr"},
Description: "server ops: for linux service/daemon.",
},
SubCommands: []*cmdr.Command{
{
BaseOpt: cmdr.BaseOpt{
Short: "s",
Full: "start",
Aliases: []string{"run", "startup"},
Description: "startup this system service/daemon.",
},
},
{
BaseOpt: cmdr.BaseOpt{
Short: "t",
Full: "stop",
Aliases: []string{"stp", "halt", "pause"},
Description: "stop this system service/daemon.",
},
},
{
BaseOpt: cmdr.BaseOpt{
Short: "r",
Full: "restart",
Aliases: []string{"reload"},
Description: "restart this system service/daemon.",
},
},
{
BaseOpt: cmdr.BaseOpt{
Full: "status",
Aliases: []string{"st"},
Description: "display its running status as a system service/daemon.",
},
},
{
BaseOpt: cmdr.BaseOpt{
Short: "i",
Full: "install",
Aliases: []string{"setup"},
Description: "install as a system service/daemon.",
},
},
{
BaseOpt: cmdr.BaseOpt{
Short: "u",
Full: "uninstall",
Aliases: []string{"remove"},
Description: "remove from a system service/daemon.",
},
},
},
}

msCommands = &cmdr.Command{
BaseOpt: cmdr.BaseOpt{
Name: "microservices",
Expand Down
65 changes: 65 additions & 0 deletions examples/demo/svr/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Copyright © 2019 Hedzr Yeh.
*/

package svr

import (
"fmt"
"github.com/hedzr/cmdr"
"github.com/hedzr/cmdr/plugin/daemon"
"github.com/sirupsen/logrus"
"os"
"time"
)

func NewDaemon() daemon.Daemon {
return &DaemonImpl{}
}

type DaemonImpl struct {
}

func (*DaemonImpl) OnRun(cmd *cmdr.Command, args []string, stopCh, doneCh chan struct{}) (err error) {
logrus.Debugf("demo daemon OnRun, pid = %v, ppid = %v", os.Getpid(), os.Getppid())
go worker(stopCh, doneCh)
return
}

func worker(stopCh, doneCh chan struct{}) {
LOOP:
for {
time.Sleep(time.Second) // this is work to be done by worker.
select {
case <-stopCh:
break LOOP
default:
}
}
doneCh <- struct{}{}
}

func (*DaemonImpl) OnStop(cmd *cmdr.Command, args []string) (err error) {
logrus.Debugf("demo daemon OnStop")
return
}

func (*DaemonImpl) OnReload() {
logrus.Debugf("demo daemon OnReload")
}

func (*DaemonImpl) OnStatus(cxt *daemon.Context, cmd *cmdr.Command, p *os.Process) (err error) {
fmt.Printf("%v v%v\n", cmd.GetRoot().AppName, cmd.GetRoot().Version)
fmt.Printf("PID=%v\nLOG=%v\n", cxt.PidFileName, cxt.LogFileName)
return
}

func (*DaemonImpl) OnInstall(cxt *daemon.Context, cmd *cmdr.Command, args []string) (err error) {
logrus.Debugf("demo daemon OnInstall")
panic("implement me")
}

func (*DaemonImpl) OnUninstall(cxt *daemon.Context, cmd *cmdr.Command, args []string) (err error) {
logrus.Debugf("demo daemon OnUninstall")
panic("implement me")
}
22 changes: 16 additions & 6 deletions exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ func Exec(rootCmd *RootCommand) (err error) {

// ExecWith is main entry of `cmdr`.
func ExecWith(rootCmd *RootCommand, beforeXrefBuilding_, afterXrefBuilt_ HookXrefFunc) (err error) {
beforeXrefBuilding = beforeXrefBuilding_
afterXrefBuilt = afterXrefBuilt_
beforeXrefBuilding = append(beforeXrefBuilding, beforeXrefBuilding_)
afterXrefBuilt = append(afterXrefBuilt, afterXrefBuilt_)
err = InternalExecFor(rootCmd, os.Args)
return
}
Expand All @@ -52,6 +52,16 @@ func buildRefs(rootCmd *RootCommand) (err error) {
return
}

// AddOnBeforeXrefBuilding add hook func
func AddOnBeforeXrefBuilding(cb HookXrefFunc) {
beforeXrefBuilding = append(beforeXrefBuilding, cb)
}

// AddOnAfterXrefBuilt add hook func
func AddOnAfterXrefBuilt(cb HookXrefFunc) {
afterXrefBuilt = append(afterXrefBuilt, cb)
}

// InternalExecFor is an internal helper, esp for debugging
func InternalExecFor(rootCmd *RootCommand, args []string) (err error) {
var (
Expand All @@ -70,17 +80,17 @@ func InternalExecFor(rootCmd *RootCommand, args []string) (err error) {
_ = rootCmd.oerr.Flush()
}()

if beforeXrefBuilding != nil {
beforeXrefBuilding(rootCmd, args)
for _, x := range beforeXrefBuilding {
x(rootCmd, args)
}

err = buildRefs(rootCmd)
if err != nil {
return
}

if afterXrefBuilt != nil {
afterXrefBuilt(rootCmd, args)
for _, x := range afterXrefBuilt {
x(rootCmd, args)
}

for pkg.i = 1; pkg.i < len(args); pkg.i++ {
Expand Down
9 changes: 6 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ module github.com/hedzr/cmdr
go 1.12

require (
github.com/BurntSushi/toml v0.3.1 // indirect
github.com/fsnotify/fsnotify v1.4.7
github.com/sirupsen/logrus v1.4.1
github.com/spf13/viper v1.3.2
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 // indirect
github.com/sevlyar/go-daemon v0.1.5
github.com/sirupsen/logrus v1.4.2
golang.org/x/sys v0.0.0-20190523142557-0e01d883c5c5 // indirect
gopkg.in/yaml.v2 v2.2.2
)

exclude github.com/sirupsen/logrus v1.4.1
44 changes: 9 additions & 35 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,49 +1,23 @@
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk=
github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 h1:iQTw/8FWTuc7uiaSepXwyf3o52HaUYcV+Tu66S3F5GA=
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0/go.mod h1:1NbS8ALrpOvjt0rHPNLyCIeMtbizbir8U//inJ+zuB8=
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY=
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.4.1 h1:GL2rEmy6nsikmW0r8opw9JIRScdMF5hA8cOYLH7In1k=
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI=
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8=
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/viper v1.3.2 h1:VUFqw5KcqRf7i70GOzW7N+Q7+gxVBkSSqiXB12+JQ4M=
github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s=
github.com/sevlyar/go-daemon v0.1.5 h1:Zy/6jLbM8CfqJ4x4RPr7MJlSKt90f00kNM1D401C+Qk=
github.com/sevlyar/go-daemon v0.1.5/go.mod h1:6dJpPatBT9eUwM5VCw9Bt6CdX9Tk6UWvhW3MebLDRKE=
github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=
github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33 h1:I6FyU15t786LL7oL/hn43zqTuEGr4PN7F4XJ1p4E3Y8=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a h1:1n5lsVfiQW3yfsRGu98756EH1YthsFqr/5mxHduZW2A=
golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190523142557-0e01d883c5c5 h1:sM3evRHxE/1RuMe1FYAL3j7C7fUfIjkbE+NiDAYUF8U=
golang.org/x/sys v0.0.0-20190523142557-0e01d883c5c5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
Expand Down
4 changes: 1 addition & 3 deletions options.watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ import (
"log"
"path"

// log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"gopkg.in/yaml.v2"
"io"
"io/ioutil"
Expand Down Expand Up @@ -203,7 +201,7 @@ func (s *Options) watchConfigDir(configDir string) {
if err != nil {
log.Printf("ERROR: os.Open() returned %v\n", err)
} else {
err = viper.MergeConfig(bufio.NewReader(file))
err = s.mergeConfigFile(bufio.NewReader(file))
if err != nil {
log.Printf("ERROR: os.Open() returned %v\n", err)
}
Expand Down
Loading

0 comments on commit e898428

Please sign in to comment.