func pretty_print_flags(prefix string, detail bool) { if detail { max1 := 0 max2 := 0 flag.VisitAll(func(f *flag.Flag) { len1 := len(f.Name) len2 := len(fmt.Sprintf("%v", f.Value)) if max1 < len1 { max1 = len1 } if max2 < len2 { max2 = len2 } }) format := fmt.Sprintf(" --%%-%ds %%%dv %%s\n", max1, max2) format = "%s" + format flag.VisitAll(func(f *flag.Flag) { fmt.Printf(format, prefix, f.Name, f.Value, f.Usage) }) } else { flag.VisitAll(func(f *flag.Flag) { fmt.Printf("%s--%s=%v\n", prefix, f.Name, f.Value) }) } }
// Prints the usage of the Iris command and its options. func usage() { fmt.Printf("Server node of the Iris decentralized messaging framework.\n\n") fmt.Printf("Usage:\n\n") fmt.Printf("\t%s [options]\n\n", os.Args[0]) fmt.Printf("The options are:\n\n") flag.VisitAll(func(f *flag.Flag) { if !strings.HasSuffix(f.Name, "prof") { if f.DefValue != "" { fmt.Printf("\t-%-8s%-12s%s\n", f.Name, "[="+f.DefValue+"]", f.Usage) } else { fmt.Printf("\t-%-20s%s\n", f.Name, f.Usage) } } }) fmt.Printf("\n") fmt.Printf("Profiling options:\n\n") flag.VisitAll(func(f *flag.Flag) { if strings.HasSuffix(f.Name, "prof") { fmt.Printf("\t-%-20s%s\n", f.Name, f.Usage) } }) fmt.Printf("\n") }
func saveConfig(w io.Writer, obsKeys map[string]string) { // find flags pointing to the same variable. We will only write the longest // named flag to the config file, the shorthand version is ignored. deduped := make(map[flag.Value]flag.Flag) flag.VisitAll(func(f *flag.Flag) { if cur, ok := deduped[f.Value]; !ok || utf8.RuneCountInString(f.Name) > utf8.RuneCountInString(cur.Name) { deduped[f.Value] = *f } }) flag.VisitAll(func(f *flag.Flag) { if cur, ok := deduped[f.Value]; ok && cur.Name == f.Name { _, usage := flag.UnquoteUsage(f) usage = strings.Replace(usage, "\n \t", "\n# ", -1) fmt.Fprintf(w, "\n# %s (default %v)\n", usage, f.DefValue) fmt.Fprintf(w, "%s=%v\n", f.Name, f.Value.String()) } }) // if we have obsolete keys left from the old config, preserve them in an // additional section at the end of the file if obsKeys != nil && len(obsKeys) > 0 { fmt.Fprintln(w, "\n\n# The following options are probably deprecated and not used currently!") for key, val := range obsKeys { fmt.Fprintf(w, "%v=%v\n", key, val) } } }
func FlagParse(positional string, desc string) { for _, fl := range commonFlags { if fl.use { fl.set() } } flag.Usage = func() { log.Printf("Usage: %s [flags] %s\n\n", path.Base(os.Args[0]), positional) if len(desc) > 0 { log.Printf("%s\n\n", desc) } flag.VisitAll(func(fl *flag.Flag) { var def string if len(fl.DefValue) > 0 { def = fmt.Sprintf(" (default: %s)", fl.DefValue) } usage := strings.Replace(fl.Usage, "\n", "\n ", -1) log.Printf("-%s%s\n", fl.Name, def) log.Printf(" %s\n", usage) }) os.Exit(1) } flag.Parse() for _, fl := range commonFlags { if fl.use && fl.init != nil { fl.init() } } }
// Usage prints the usage information for the application including all flags // and their values after parsing the configuration file func Usage() { Parse() fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) flag.VisitAll(func(f *flag.Flag) { fmt.Fprintf(os.Stderr, " -%s=%s: %s\n", f.Name, f.Value.String(), f.Usage) }) }
func Parse() { if *configFile == "" { return } config := readConfig() explicit := make([]*flag.Flag, 0) all := make([]*flag.Flag, 0) flag.Visit(func(f *flag.Flag) { explicit = append(explicit, f) }) flag.VisitAll(func(f *flag.Flag) { all = append(all, f) if !contains(explicit, f) { val := config[f.Name] if val != "" { err := f.Value.Set(val) if err != nil { log.Fatalf("Failed to set flag %s with value %s", f.Name, val) } } } }) Outer: for name, val := range config { for _, f := range all { if f.Name == name { continue Outer } } log.Fatalf("Unknown flag %s=%s in config file.", name, val) } }
func parse() (err error) { // Record which flags were set by command line args so that we don't overwrite them. set := make(map[*flag.Flag]bool, 0) flag.Visit(func(f *flag.Flag) { set[f] = true }) flag.VisitAll(func(f *flag.Flag) { if !set[f] && err == nil { r := strings.NewReplacer(".", "_", "-", "_") name := r.Replace(f.Name) if UseUpperCaseFlagNames { name = strings.ToUpper(name) } val := os.Getenv(name) if val != "" { if seterr := f.Value.Set(val); seterr != nil { err = fmt.Errorf("Failed to set flag %s with value %s", f.Name, val) } } } }) return }
func init() { flag.Parse() // Create a map of pointers to all the current flags flags := map[string]*flag.Flag{} flag.VisitAll(func(f *flag.Flag) { flags[f.Name] = f }) // Remove the flags that were set on the command line flag.Visit(func(f *flag.Flag) { delete(flags, f.Name) }) // Now for the flags that weren't set on the cli, // Look at the env for 'PBOX_<uppercase flag name>' // If it exists, use it to set the corresponding flag. for _, f := range flags { var buffer bytes.Buffer buffer.WriteString("PBOX_") buffer.WriteString(strings.ToUpper(f.Name)) if os.Getenv(buffer.String()) != "" { f.Value.Set(os.Getenv(buffer.String())) } } }
func getFlags() []string { flagData := []string{} flag.VisitAll(func(flag *flag.Flag) { flagData = append(flagData, fmt.Sprintf("%s='%v'", flag.Name, flag.Value)) }) return flagData }
// parse() iterates through the flags and populate the // values from environment variables if present func parse(prefix string) (errp error) { cmdline := make(map[string]bool) flag.Visit(func(f *flag.Flag) { cmdline[f.Name] = true }) flag.VisitAll(func(f *flag.Flag) { if _, ok := cmdline[f.Name]; !ok { val := os.Getenv(getEnvName(prefix, f.Name)) if val != "" { err := f.Value.Set(val) if err != nil { if errp != nil { errp = fmt.Errorf(errp.Error()+", value:\"%s\" for flag:\"%s\"", val, f.Name) } else { errp = fmt.Errorf(":envtoflag: error setting value:\"%s\" for flag:\"%s\"", val, f.Name) } } } } }) return }
func main() { flag.Parse() flag.VisitAll(func(f *flag.Flag) { if fmt.Sprintf("%s", f.Value) == f.DefValue { log.Println("Arguments invalid") os.Exit(0) } }) absRoot, err := filepath.Abs(*root) if err != nil { log.Fatal(err) } absKey, err := filepath.Abs(*keyFile) if err != nil { log.Fatal(err) } absCert, err := filepath.Abs(*certFile) if err != nil { log.Fatal(err) } secret := auth.HtdigestFileProvider(*htdigest) authenticator := auth.NewDigestAuthenticator(*realm, secret) log.Printf("Starting server on port %d\n", *port) hostport := fmt.Sprintf(":%d", *port) authHandler := makeAuthHandler(http.FileServer(http.Dir(absRoot))) handler := authenticator.Wrap(authHandler) log.Fatal(http.ListenAndServeTLS(hostport, absCert, absKey, handler)) }
func dumpFlags() { flag.VisitAll(func(f *flag.Flag) { if f.Name != "config" && f.Name != "dumpflags" { fmt.Printf("%s = %s # %s\n", f.Name, quoteValue(f.Value.String()), escapeUsage(f.Usage)) } }) }
func main() { flag.Parse() flag.VisitAll(func(f *flag.Flag) { fmt.Printf("%s=%v\n", f.Name, f.Value) }) runtime.GOMAXPROCS(*goMaxProcs) victimUri, err := url.Parse(*victimUrl) if err != nil { log.Fatalf("Cannot parse victimUrl=[%s]: [%s]\n", victimUrl, err) } victimHostPort := victimUri.Host if !strings.Contains(victimHostPort, ":") { port := "80" if victimUri.Scheme == "https" { port = "443" } victimHostPort = net.JoinHostPort(victimHostPort, port) } requestHeader := []byte(fmt.Sprintf("POST %s HTTP/1.1\nHost: %s\nContent-Type: application/x-www-form-urlencoded\nContent-Length: %d\n\n", victimUri.RequestURI(), victimUri.Host, *contentLength)) dialWorkersLaunchInterval := *rampUpInterval / time.Duration(*dialWorkersCount) activeConnectionsCh := make(chan int, *dialWorkersCount) go activeConnectionsCounter(activeConnectionsCh) for i := 0; i < *dialWorkersCount; i++ { go dialWorker(activeConnectionsCh, victimHostPort, victimUri, requestHeader) time.Sleep(dialWorkersLaunchInterval) } time.Sleep(*testDuration) }
// Returns the number of flags that have been declared. func numFlags() int { n := 0 flag.VisitAll(func(f *flag.Flag) { n++ }) return n }
func (l *Layout) GetUsage(app, desc, ver string) func() { return func() { fmt.Printf("NAME: \t %v - %v\n", l.bash.Blue(app), l.bash.White(desc)) //fmt.Printf("%v", l.bash.Blue(fmt.Sprintf("\n\t\t### %v - %v ###\n\n", app, desc))) fmt.Printf("USAGE:\t %v %v\n", l.bash.Blue(path.Base(os.Args[0])), l.bash.White("[arguments...]")) fmt.Printf("VER: \t %v\n", l.bash.Blue(ver)) fmt.Println("COMMANDS:") flag.VisitAll(func(f *flag.Flag) { extra := (func(extra string) string { if len(extra) == 0 { return "" } return fmt.Sprintf("[default: %v]", l.bash.White(extra)) })(f.DefValue) space := "\t%v: \t %v %v \n" if len(f.Name) < 7 { space = "\t%v: \t\t %v %v \n" } else if len(f.Name) < 3 { space = "\t%v: +\t\t\t %v %v \n" } fmt.Printf(space, l.bash.Green(f.Name), l.bash.Yellow(f.Usage), extra) }) } }
func printFlags() { var s []string flag.VisitAll(func(fl *flag.Flag) { s = append(s, "-"+fl.Name) }) fmt.Printf("%v", strings.Join(s, " ")) }
func getMissingFlags() []string { var ( set, missing []string found = false ) // Visit only the flags that have been set flag.Visit(func(f *flag.Flag) { set = append(set, f.Name) }) // Visit all the flags, even those not set flag.VisitAll(func(f *flag.Flag) { for _, v := range set { if v == f.Name { found = true break } } // If we don't find the flag in the slice of already set flags, we add it to the missing slice if !found { missing = append(missing, f.Name) } found = false }) return missing }
func usageMsg() { fmt.Fprintln(os.Stderr, msg) off := 0 flag.VisitAll(func(f *flag.Flag) { if off < len(f.Name) { off = len(f.Name) } }) flag.VisitAll(func(f *flag.Flag) { sep := make([]byte, off-len(f.Name)) for i := range sep { sep[i] = 0x20 } fmt.Fprintf(os.Stderr, "-%s %s-- %s\n", f.Name, sep, f.Usage) }) }
func generalHelp() { out := tabwriter.NewWriter(os.Stderr, 0, 8, 1, '\t', 0) exe := filepath.Base(os.Args[0]) fmt.Fprintf(out, "USAGE:\n\t%s [global options] <command> [command options] [arguments...]\n\n", exe) fmt.Fprintf(out, "VERSION:\n\t%s\n\n", Version) fmt.Fprintf(out, "COMMANDS:\n") names := sort.StringSlice{} for name, _ := range subcommands { names = append(names, name) } names.Sort() for _, name := range names { cmd := subcommands[name] fmt.Fprintf(out, "\t%s\t%s\n", name, cmd.desc()) } fmt.Fprintln(out) fmt.Fprintf(out, "GLOBAL OPTIONS:\n") flag.VisitAll(func(f *flag.Flag) { prefix := "-" if len(f.Name) > 1 { prefix = "--" } fmt.Fprintf(out, "\t%s%s=%s\t%s\n", prefix, f.Name, f.DefValue, f.Usage) }) fmt.Fprintln(out) fmt.Fprintf(out, "Run \"%s help <command>\" for more details about a command.\n", exe) }
func main() { log.SetFlags(log.Flags() | log.Llongfile) //recv := &chromebus.ChromebusRecordStdinReceiver{} //str, _ := recv.GetRecord() //log.Printf("%s", str) //str, _ = recv.GetRecord() //log.Printf("%s", str) flag.Parse() flag.VisitAll(defFlags) if !serverMode { chromebus.EnvSetup() } var e *chromebus.Engine if pluginsDefined { e = chromebus.CreateEngine(plugins, port) } else { e = chromebus.CreateEngine(nil, port) } go func() { e.Start() }() signalChannel := make(chan os.Signal, 1) signal.Notify(signalChannel, os.Interrupt, os.Kill) <-signalChannel e.CleanUp() //rcv := ChromebusRecordStdinReceiver{} //exec.Command("date") }
// overwriteFlagsWithViperConfig finds and writes values to flags using viper as input. func overwriteFlagsWithViperConfig() { viperFlagSetter := func(f *flag.Flag) { if viper.IsSet(f.Name) { f.Value.Set(viper.GetString(f.Name)) } } flag.VisitAll(viperFlagSetter) }
func usage() { fmt.Fprintf(os.Stderr, "\nUsage: %s [flags]\n", path.Base(os.Args[0])) flag.VisitAll(func(fg *flag.Flag) { fmt.Printf("--%s=\"%s\"\n\t%s\n", fg.Name, fg.DefValue, strings.Replace(fg.Usage, "\n", "\n\t", -1)) }) os.Exit(1) }
func printUsage(fd io.Writer) { fmt.Fprintf(fd, "%s [OPTIONS] -c <path>", path.Base(os.Args[0])) fmt.Fprint(fd, "\n\nOptions:\n") flag.VisitAll(func(f *flag.Flag) { fmt.Fprintf(fd, " -%s %s\n", f.Name, f.Usage) }) }
func usage() string { b := bytes.Buffer{} b.WriteString("usage: polygen [options] idlfile\n") flag.VisitAll(func(f *flag.Flag) { b.WriteString(fmt.Sprintf(" -%s=%s: %s)\n", f.Name, f.DefValue, f.Usage)) }) return b.String() }
func showHelp() { fmt.Println("Usage:") fmt.Printf("%s [options] install | clear\n\nOptions:\n", os.Args[0]) flag.VisitAll(func(f *flag.Flag) { fmt.Printf(" - %s (%s) %s\n", f.Name, f.DefValue, f.Usage) }) fmt.Println("") }
func LogFlags(flagAliases map[string][]string) { flag.VisitAll(func(f *flag.Flag) { if flagAliases[f.Name] != nil { log.Printf(" -%s=%q\n", f.Name, f.Value) } }) log.Printf(" GOMAXPROCS=%d", runtime.GOMAXPROCS(-1)) }
// For settings that are constant throughout server process lifetime. func restGetSettings(w http.ResponseWriter, r *http.Request) { m := map[string]interface{}{} flag.VisitAll(func(f *flag.Flag) { if f.Name != "adminUser" && f.Name != "adminPass" { m[f.Name] = f.Value } }) mustEncode(w, m) }
func main() { var rootDataDirectory, listenAddress, port, mimeTypesFile string var mimeTypesClear bool var replicationTargets ReplicationTargets var replicationWorkers int var healthCheckPath, healthyIfFile, healthyUnlessFile string var quiet bool flag.StringVar(&rootDataDirectory, "data", default_root(), "Sets the root data directory to /foo. Must be fully-qualified (ie. it must start with a /).") flag.StringVar(&listenAddress, "listen", DefaultListenAddress, "Listen on the given IP address. Default: listen on all network interfaces.") flag.StringVar(&port, "port", DefaultPort, "Listen on the given port.") flag.StringVar(&mimeTypesFile, "mime-types-file", DefaultMimeTypesFile, "Load MIME content-types from the given file.") flag.BoolVar(&mimeTypesClear, "no-default-mime-types", false, "Clear the built-in MIME types so the settings in the file given in the mime-types-file option are used exclusively.") flag.Var(&replicationTargets, "replicate-to", "Replicate files to the given Verm server. May be given multiple times.") flag.IntVar(&replicationWorkers, "replication-workers", runtime.NumCPU()*10, "Number of gophers to use to replicate files to each Verm server. Generally should be large; the default scales with the number of CPUs detected.") flag.BoolVar(&quiet, "quiet", false, "Quiet mode. Don't print startup/shutdown/request log messages to stdout.") flag.StringVar(&healthCheckPath, "health-check-path", "", "Treat requests to this path as health checks from your load balancer, and give a 200 response without trying to serve a file.") flag.StringVar(&healthyIfFile, "healthy-if-file", "", "Respond to requests to the health-check-path with a 503 response code if this file doesn't exist.") flag.StringVar(&healthyUnlessFile, "healthy-unless-file", "", "Respond to requests to the health-check-path with a 503 response code if this file exists.") flag.VisitAll(setFlagFromEnvironment) flag.Parse() runtime.GOMAXPROCS(runtime.NumCPU()) mimeext.LoadMimeFile(mimeTypesFile, mimeTypesClear) listener, err := net.Listen("tcp", listenAddress+":"+port) if err != nil { fmt.Fprintf(os.Stderr, "Couldn't listen on %s:%s: %s\n", listenAddress, port, err.Error()) os.Exit(1) } else if !quiet { fmt.Fprintf(os.Stdout, "%s listening on http://%s:%s, data in %s\n", banner(), listenAddress, port, rootDataDirectory) } statistics := &LogStatistics{} server := VermServer(listener, rootDataDirectory, &replicationTargets, statistics, quiet) replicationTargets.Start(rootDataDirectory, statistics, replicationWorkers) replicationTargets.EnqueueResync() go waitForSignals(&server, &replicationTargets) if healthCheckPath != "" { http.Handle(AddRoot(healthCheckPath), HealthCheckServer(healthyIfFile, healthyUnlessFile)) } http.Handle("/", server) server.Serve() if err != nil { fmt.Fprintf(os.Stderr, "Unexpected error: %s\n", err.Error()) os.Exit(1) } server.Tracker.Shutdown(ShutdownResponseTimeout * time.Second) os.Exit(0) }
// ShortUsage only outputs to stderr flags without "." and withholds some // system flags. func ShortUsage() { header() flag.VisitAll(func(f *flag.Flag) { if strings.Contains(f.Name, ".") || isWithheld(f.Name) { return } fmt.Fprint(os.Stderr, formatFlag(f), "\n") }) }
// Printable config func (settings *ScanSettings) String() string { flags := make([]string, 0) flag.VisitAll(func(f *flag.Flag) { flags = append(flags, fmt.Sprintf("-%s=%s", f.Name, f.Value.String())) }) return strings.Join(flags, " ") }