@@ -17,6 +17,7 @@ package pluginrpc
1717import (
1818 "fmt"
1919 "io"
20+ "sort"
2021 "strconv"
2122 "strings"
2223
@@ -32,6 +33,7 @@ const (
3233 FormatFlagName = "format"
3334
3435 protocolVersion = 1
36+ flagWrapping = 140
3537)
3638
3739type flags struct {
@@ -40,10 +42,13 @@ type flags struct {
4042 format Format
4143}
4244
43- func parseFlags (output io.Writer , args []string ) (* flags , []string , error ) {
45+ func parseFlags (output io.Writer , args []string , spec Spec , doc string ) (* flags , []string , error ) {
4446 flags := & flags {}
4547 var formatString string
4648 flagSet := pflag .NewFlagSet ("plugin" , pflag .ContinueOnError )
49+ flagSet .Usage = func () {
50+ _ , _ = fmt .Fprint (output , getFlagUsage (flagSet , spec , doc ))
51+ }
4752 flagSet .SetOutput (output )
4853 flagSet .BoolVar (& flags .printProtocol , ProtocolFlagName , false , "Print the protocol to stdout and exit." )
4954 flagSet .BoolVar (& flags .printSpec , SpecFlagName , false , "Print the spec to stdout in the specified format and exit." )
@@ -68,6 +73,35 @@ func parseFlags(output io.Writer, args []string) (*flags, []string, error) {
6873 return flags , flagSet .Args (), nil
6974}
7075
76+ func getFlagUsage (flagSet * pflag.FlagSet , spec Spec , doc string ) string {
77+ var sb strings.Builder
78+ if doc != "" {
79+ _ , _ = sb .WriteString (doc )
80+ _ , _ = sb .WriteString ("\n \n " )
81+ }
82+ _ , _ = sb .WriteString ("Commands:\n \n " )
83+ var argBasedProcedureStrings []string
84+ var pathBasedProcedureStrings []string
85+ for _ , procedure := range spec .Procedures () {
86+ if args := procedure .Args (); len (args ) > 0 {
87+ argBasedProcedureStrings = append (argBasedProcedureStrings , strings .Join (args , " " ))
88+ } else {
89+ pathBasedProcedureStrings = append (pathBasedProcedureStrings , procedure .Path ())
90+ }
91+ }
92+ sort .Strings (argBasedProcedureStrings )
93+ sort .Strings (pathBasedProcedureStrings )
94+ for _ , procedureString := range append (argBasedProcedureStrings , pathBasedProcedureStrings ... ) {
95+ _ , _ = sb .WriteString (" " )
96+ _ , _ = sb .WriteString (procedureString )
97+ _ , _ = sb .WriteString ("\n " )
98+ }
99+ _ , _ = sb .WriteString ("\n Flags:\n \n " )
100+ _ , _ = sb .WriteString (flagSet .FlagUsagesWrapped (flagWrapping ))
101+ _ , _ = sb .WriteString (" -h, --help Show this help.\n " )
102+ return sb .String ()
103+ }
104+
71105func marshalProtocol (value int ) []byte {
72106 return []byte (strconv .Itoa (value ) + "\n " )
73107}
0 commit comments