Created
September 2, 2020 16:19
-
-
Save artyom/0ca2b5d8967abbaedb00f932ab05a97d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Flags parsing illustration for https://www.reddit.com/r/golang/comments/il5h9g/looking_for_cli_parsing/ | |
package main | |
import ( | |
"flag" | |
"log" | |
"os" | |
"strings" | |
) | |
func main() { | |
log.SetFlags(0) | |
jobs, err := parseFlags(os.Args[1:]) | |
if err != nil { | |
log.Fatal(err) | |
} | |
if err := run(jobs); err != nil { | |
log.Fatal(err) | |
} | |
} | |
func run(jobs []job) error { | |
log.Printf("%+v", jobs) | |
return nil | |
} | |
type job struct { | |
N, P int | |
Items []string | |
} | |
func parseFlags(rawArgs []string) ([]job, error) { | |
var out []job | |
args := rawArgs | |
for len(args) != 0 { | |
j := job{} | |
fs := flag.NewFlagSet("", flag.ExitOnError) | |
fs.IntVar(&j.N, "n", j.N, "number of times to process an item") | |
fs.IntVar(&j.P, "p", j.P, "max number of cores to use for processing") | |
if err := fs.Parse(args); err != nil { | |
return nil, err | |
} | |
args = args[:0] | |
for i, s := range fs.Args() { | |
if strings.HasPrefix(s, "-") { | |
args = append(args, fs.Args()[i:]...) | |
break | |
} | |
j.Items = append(j.Items, s) | |
} | |
if len(j.Items) != 0 { | |
out = append(out, j) | |
} | |
} | |
return out, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment