command.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package daemon
  2. import (
  3. "os"
  4. )
  5. // AddCommand is wrapper on AddFlag and SetSigHandler functions.
  6. func AddCommand(f Flag, sig os.Signal, handler SignalHandlerFunc) {
  7. if f != nil {
  8. AddFlag(f, sig)
  9. }
  10. if handler != nil {
  11. SetSigHandler(handler, sig)
  12. }
  13. }
  14. // Flag is the interface implemented by an object that has two state:
  15. // 'set' and 'unset'.
  16. type Flag interface {
  17. IsSet() bool
  18. }
  19. // BoolFlag returns new object that implements interface Flag and
  20. // has state 'set' when var with the given address is true.
  21. func BoolFlag(f *bool) Flag {
  22. return &boolFlag{f}
  23. }
  24. // StringFlag returns new object that implements interface Flag and
  25. // has state 'set' when var with the given address equals given value of v.
  26. func StringFlag(f *string, v string) Flag {
  27. return &stringFlag{f, v}
  28. }
  29. type boolFlag struct {
  30. b *bool
  31. }
  32. func (f *boolFlag) IsSet() bool {
  33. if f == nil {
  34. return false
  35. }
  36. return *f.b
  37. }
  38. type stringFlag struct {
  39. s *string
  40. v string
  41. }
  42. func (f *stringFlag) IsSet() bool {
  43. if f == nil {
  44. return false
  45. }
  46. return *f.s == f.v
  47. }
  48. var flags = make(map[Flag]os.Signal)
  49. // Flags returns flags that was added by the function AddFlag.
  50. func Flags() map[Flag]os.Signal {
  51. return flags
  52. }
  53. // AddFlag adds the flag and signal to the internal map.
  54. func AddFlag(f Flag, sig os.Signal) {
  55. flags[f] = sig
  56. }
  57. // SendCommands sends active signals to the given process.
  58. func SendCommands(p *os.Process) (err error) {
  59. for _, sig := range signals() {
  60. if err = p.Signal(sig); err != nil {
  61. return
  62. }
  63. }
  64. return
  65. }
  66. // ActiveFlags returns flags that has the state 'set'.
  67. func ActiveFlags() (ret []Flag) {
  68. ret = make([]Flag, 0, 1)
  69. for f := range flags {
  70. if f.IsSet() {
  71. ret = append(ret, f)
  72. }
  73. }
  74. return
  75. }
  76. func signals() (ret []os.Signal) {
  77. ret = make([]os.Signal, 0, 1)
  78. for f, sig := range flags {
  79. if f.IsSet() {
  80. ret = append(ret, sig)
  81. }
  82. }
  83. return
  84. }