// Print usage information about the frosty backup tool. func printHelp() { fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) fmt.Fprintf(os.Stderr, "\n\tfrosty <path-to-frosty-config-file> [flags...]\n\n") fmt.Fprintf(os.Stderr, "Flags:\n") flag.PrintDefaults() fmt.Fprintf(os.Stderr, "\n%s\n", frostyVersion) }
func init() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s [configFile]\n", os.Args[0]) flag.PrintDefaults() fmt.Fprintf(os.Stderr, "\n%s", copyright()) } }
func main() { var config Config flag.BoolVar(&DEBUG, "debug", false, "enable debug logging") flag.BoolVar(&QUIET, "quiet", false, "disable output") flag.StringVar(&config.FieldSep, "csv-fields-terminated-by", "\t", "field separator") flag.StringVar(&config.RowSep, "csv-records-terminated-by", "\n", "row separator") flag.StringVar(&config.NullString, "csv-null-string", "\\N", "output string for NULL values") flag.BoolVar(&config.DateEpoch, "epoch", true, "output datetime as epoch instead of RFC3339") defaults_file := flag.String("defaults-file", "my.cnf", "defaults file") defaults_group_suffix := flag.String("defaults-group-suffix", "", "defaults group suffix") format := flag.String("format", "json", "output format 'json' or 'csv'") flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage: mysqlcsvdump [options] database table > output.json\n\n") fmt.Fprintf(os.Stderr, "Reads connection info from ./my.cnf. Use '-' for table to send query in stdin\n\n") flag.PrintDefaults() } flag.Parse() args := flag.Args() if len(args) < 2 { flag.Usage() os.Exit(1) } dsn := getDSN(*defaults_file, "client"+*defaults_group_suffix, args[0]) rows := getRows(dsn, args[1]) if *format == "json" { NewJsonWriter(&config).WriteRows(rows) } else { NewCsvWriter(&config).WriteRows(rows) } }
func usageLong() { // NOTE: the help message uses spaces, not tabs for indentation! errf(`boot2docker management utility. Usage: %s [<options>] <command> [<args>] Commands: init [<vm>] Create a new boot2docker VM. up|start|boot [<vm>] Start VM from any states. ssh Login to VM via SSH. save|suspend [<vm>] Suspend VM and save state to disk. down|stop|halt [<vm>] Gracefully shutdown the VM. restart [<vm>] Gracefully reboot the VM. poweroff [<vm>] Forcefully power off the VM (might corrupt disk image). reset [<vm>] Forcefully power cycle the VM (might corrupt disk image). delete [<vm>] Delete boot2docker VM and its disk image. info [<vm>] Display detailed information of VM. status [<vm>] Display current state of VM. download Download boot2docker ISO image. version Display version information. Options: `, os.Args[0]) flag.PrintDefaults() }
func main() { pflag.Usage = func() { fmt.Printf(`usage: tuplespaced [flags] Run tuplespace server. Flags: `) pflag.PrintDefaults() } pflag.Parse() runtime.GOMAXPROCS(*ncpuFlag) log.AddFilter("stdout", logLevels[*logLevelFlag], log.NewConsoleLogWriter()) debug := logLevels[*logLevelFlag] <= log.DEBUG log.Info("Starting server on http://%s/tuplespace/", *bindFlag) ts := tuplespace.NewTupleSpace(store.NewMemoryStore()) srv := &http.Server{ Addr: *bindFlag, Handler: makeService(ts, debug), ReadTimeout: *readTimeoutFlag, WriteTimeout: *writeTimeoutFlag, } err := srv.ListenAndServe() if err != nil { fatalf("error: %s\n", err) } }
func init() { flag.BoolVarP(&flagVerbose, "verbose", "v", false, "be verbose") flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage: binscope [options] <file1>...\n") flag.PrintDefaults() } }
func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "fsping: check responsiveness of mounted filesystems\n\n") flag.PrintDefaults() } flag.Parse() fsnum := 0 fsch := make(chan fs_t) fsmap := readmounts() args := flag.Args() // if extra args were specified keep only filesystems listed if len(args) > 0 { L: for fs, _ := range fsmap { for _, a := range args { if fs == a { continue L } } delete(fsmap, fs) } } // fire them up for _, fs := range fsmap { fsnum += 1 // fire off a goroutine for each mounted nfs // filesystem. fsch is used for completion // notifications go statit(fs, fsch) } // timeout ticker tick := time.Tick(*timeout) // collect results for fsnum > 0 { select { case fs := <-fsch: if *verbose || fs.err != nil { fmt.Println(fs) } fsmap[fs.path] = fs fsnum -= 1 case <-tick: // ticker has kicked in, print timeout // messages for filesystems that haven't // finished for _, fs := range fsmap { if !*quiet && !fs.done { fmt.Println(fs) } } os.Exit(1) } } }
func main() { pflag.Parse() if helpFlag { pflag.PrintDefaults() return } if versionFlag { log.Printf("This is version %d.%d-%d.", MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION) return } log.Printf("Starting up version %d.%d-%d...\n", MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION) // Read configuration _, err := os.Open(workerDirFlag) if err != nil { if err == os.ErrNotExist || err == os.ErrInvalid { err = os.Mkdir(workerDirFlag, os.ModeDir) if err != nil { log.Panicf("Could not create worker dir: %s", err) } } else { log.Panicf("Error accessing worker directory: %s", err) } } log.Printf("Reading worker configuration:\n") fileWalkErr := filepath.Walk(workerDirFlag, visit) if fileWalkErr != nil { log.Panicf("There seems to have been a problem reading configuration: %s\n", fileWalkErr) } log.Printf("Starting up scheduler...\n") r.Scheduler_Run() if r.SchedulerStatus == 0 { log.Panicf("Scheduler failed to start!\n") } log.Printf("Ping and Queue up Workers...\n") // Establish Ping GoRoutine and add them to Scheduler // (Should this just be connecting the workers? This way we set them as // connected and have reservoir ping constantly until we disconnect.) log.Printf("Start the API interface...\n") // Start the API web interface here (goweb)? log.Printf("Now active.\n") mainBlock := make(chan bool) <-mainBlock // Won't happen, just used to wait the main thread b/c we need to keep the prog active. }
func main() { var pathStrings pathSlice filePtr := flag.StringP("file", "f", "", "Path to json file") jsonPtr := flag.StringP("json", "j", "", "JSON text") flag.VarP(&pathStrings, "path", "p", "One or more paths to target in JSON") showKeysPtr := flag.BoolP("keys", "k", false, "Print keys & indexes that lead to value") flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) flag.PrintDefaults() fmt.Fprintln(os.Stderr, "Pipe JSON to StdIn by not specifying --file or --json ") } flag.Parse() if len(pathStrings) == 0 { fmt.Println("Must specify one or more paths with the --path flag") os.Exit(1) } paths, err := jsonpath.ParsePaths(pathStrings...) if err != nil { fmt.Println(fmt.Errorf("Failed to parse paths: %q", err.Error())) os.Exit(1) } if filePtr != nil && *filePtr != "" { f, err := os.Open(*filePtr) if err != nil { fmt.Println(fmt.Errorf("Failed to open file: %q", err.Error())) os.Exit(1) } eval, err := jsonpath.EvalPathsInReader(f, paths) checkAndHandleError(err) run(eval, *showKeysPtr) checkAndHandleError(eval.Error) f.Close() } else if jsonPtr != nil && *jsonPtr != "" { eval, err := jsonpath.EvalPathsInBytes([]byte(*jsonPtr), paths) checkAndHandleError(err) run(eval, *showKeysPtr) checkAndHandleError(eval.Error) } else { reader := bufio.NewReader(os.Stdin) eval, err := jsonpath.EvalPathsInReader(reader, paths) checkAndHandleError(err) run(eval, *showKeysPtr) checkAndHandleError(eval.Error) } }
func helpCmd() { usage := `Usage: remotectl <flags> <query> [--] <cmd> Available Providers: %s Environment Vars: ` fmt.Printf(usage, providers.Providers()) env.PrintDefaults(os.Stderr) fmt.Println("\nFlags:") flag.PrintDefaults() }
func init() { flag.Usage = func() { fmt.Fprintf( os.Stderr, `Usage: %s log_directory [options] or %s log_directory domains_file --generate [options] with options: `, os.Args[0], os.Args[0], ) flag.PrintDefaults() } }
func (mmsd *mmsdService) Run() { flag.BoolVarP(&mmsd.Verbose, "verbose", "v", mmsd.Verbose, "Set verbosity level") flag.IPVar(&mmsd.MarathonIP, "marathon-ip", mmsd.MarathonIP, "Marathon endpoint TCP IP address") flag.UintVar(&mmsd.MarathonPort, "marathon-port", mmsd.MarathonPort, "Marathon endpoint TCP port number") flag.DurationVar(&mmsd.ReconnectDelay, "reconnect-delay", mmsd.ReconnectDelay, "Marathon reconnect delay") flag.StringVar(&mmsd.RunStateDir, "run-state-dir", mmsd.RunStateDir, "Path to directory to keep run-state") flag.StringVar(&mmsd.FilterGroups, "filter-groups", mmsd.FilterGroups, "Application group filter") flag.IPVar(&mmsd.ManagedIP, "managed-ip", mmsd.ManagedIP, "IP-address to manage for mmsd") flag.BoolVar(&mmsd.GatewayEnabled, "enable-gateway", mmsd.GatewayEnabled, "Enables gateway support") flag.IPVar(&mmsd.GatewayAddr, "gateway-bind", mmsd.GatewayAddr, "gateway bind address") flag.UintVar(&mmsd.GatewayPortHTTP, "gateway-port-http", mmsd.GatewayPortHTTP, "gateway port for HTTP") flag.UintVar(&mmsd.GatewayPortHTTPS, "gateway-port-https", mmsd.GatewayPortHTTPS, "gateway port for HTTPS") flag.BoolVar(&mmsd.FilesEnabled, "enable-files", mmsd.FilesEnabled, "enables file based service discovery") flag.BoolVar(&mmsd.UDPEnabled, "enable-udp", mmsd.UDPEnabled, "enables UDP load balancing") flag.BoolVar(&mmsd.TCPEnabled, "enable-tcp", mmsd.TCPEnabled, "enables haproxy TCP load balancing") flag.BoolVar(&mmsd.LocalHealthChecks, "enable-health-checks", mmsd.LocalHealthChecks, "Enable local health checks (if available) instead of relying on Marathon health checks alone.") flag.StringVar(&mmsd.HaproxyBin, "haproxy-bin", mmsd.HaproxyBin, "path to haproxy binary") flag.StringVar(&mmsd.HaproxyTailCfg, "haproxy-cfgtail", mmsd.HaproxyTailCfg, "path to haproxy tail config file") flag.IPVar(&mmsd.ServiceAddr, "haproxy-bind", mmsd.ServiceAddr, "haproxy management port") flag.UintVar(&mmsd.HaproxyPort, "haproxy-port", mmsd.HaproxyPort, "haproxy management port") flag.BoolVar(&mmsd.DnsEnabled, "enable-dns", mmsd.DnsEnabled, "Enables DNS-based service discovery") flag.UintVar(&mmsd.DnsPort, "dns-port", mmsd.DnsPort, "DNS service discovery port") flag.BoolVar(&mmsd.DnsPushSRV, "dns-push-srv", mmsd.DnsPushSRV, "DNS service discovery to also push SRV on A") flag.StringVar(&mmsd.DnsBaseName, "dns-basename", mmsd.DnsBaseName, "DNS service discovery's base name") flag.DurationVar(&mmsd.DnsTTL, "dns-ttl", mmsd.DnsTTL, "DNS service discovery's reply message TTL") showVersionAndExit := flag.BoolP("version", "V", false, "Shows version and exits") flag.Usage = func() { showVersion() fmt.Fprintf(os.Stderr, "\nUsage: mmsd [flags ...]\n\n") flag.PrintDefaults() fmt.Fprintf(os.Stderr, "\n") } flag.Parse() if *showVersionAndExit { showVersion() os.Exit(0) } mmsd.setupHandlers() mmsd.setupEventBusListener() mmsd.setupHttpService() <-mmsd.quitChannel }
func init() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage: dockdash [options]\n\n") flag.PrintDefaults() } flag.Parse() if *helpFlag { flag.Usage() os.Exit(1) } if *versionFlag { fmt.Println(VERSION) os.Exit(0) } }
func printUsage() { _, file := path.Split(os.Args[0]) fmt.Printf("Usage: %s [options] command [params...]\n\n", file) fmt.Printf("Options:\n") flag.PrintDefaults() fmt.Printf(` Available JSON-RPC commands: getstatus, stop listwallets, createwallet, deletewallet listbalances, listtransactions listaddresses, createaddresses, setaddresslabel addasset, setassetvisible, refreshasset, deleteasset sendbitcoin, sendasset, sendbitcoinasset sendbitcoinmessage, sendassetmessage, sendbitcoinassetmessage listunspent, sendbitcoinusing, sendassetusing `) }
func Tool(desc string, outputter func(s *Stats)) { flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage: %s [OPTION]... [FILE]...\n", os.Args[0]) fmt.Fprintf(os.Stderr, "%s\n\n", desc) flag.PrintDefaults() fmt.Fprintln(os.Stderr, "\nWith no FILE, or when FILE is -, read standard input.") } flag.Parse() if *version { fmt.Printf("%s %s\n", os.Args[0], programVersion) return } s := NewStats() calculate(s) outputter(s) }
func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "usage: jp [file]\n") flag.PrintDefaults() } isTerminal := terminal.IsTerminal(int(os.Stdout.Fd())) compact := flag.Bool("compact", false, "compact format") colors := flag.Bool("color", isTerminal, "colored format") flag.Parse() args := flag.Args() if len(args) < 1 { flag.Usage() os.Exit(2) } format := "pretty" if *compact { format = "compact" } if *colors { format += "16" } var fd *os.File var e error if args[0] == "-" { fd = os.Stdin } else { fd, e = os.Open(args[0]) if e != nil { fmt.Fprintln(os.Stderr, "Error:", e) os.Exit(1) } } e = jp.Expand(fd, os.Stdout, format) if e != nil { fmt.Fprintln(os.Stderr, "Error:", e) os.Exit(1) } }
// syntaxError prints the syntax func syntaxError() { fmt.Fprintf(os.Stderr, `Sync files and directories to and from local and remote object stores - %s. Syntax: [options] subcommand <parameters> <parameters...> Subcommands: `, fs.Version) for i := range Commands { cmd := &Commands[i] fmt.Fprintf(os.Stderr, " %s %s\n", cmd.Name, cmd.ArgsHelp) fmt.Fprintf(os.Stderr, "%s\n\n", cmd.Help) } fmt.Fprintf(os.Stderr, "Options:\n") pflag.PrintDefaults() fmt.Fprintf(os.Stderr, ` It is only necessary to use a unique prefix of the subcommand, eg 'up' for 'upload'. `) }
func init() { flag.Usage = func() { fmt.Fprintln(os.Stderr, "Usage: chanloader [options] /b/res/123456\nOptions:") flag.PrintDefaults() } flag.Parse() if *refresh < time.Second*30 { *refresh = time.Second * 30 } if *showVersion { fmt.Println(version) os.Exit(0) } if flag.NArg() < 1 { flag.Usage() os.Exit(1) } runtime.GOMAXPROCS(runtime.NumCPU()) }
func usage() { PrintErr("usage: gutenberg [flags]", "") flag.PrintDefaults() os.Exit(0) }
func main() { d := deferer.NewDeferer(nil) defer d.Run() rand.Seed(time.Now().UnixNano()) id := rand.Int() if ID := os.Getenv("ID"); ID != "" { fmt.Sscanf(ID, "%d", &id) } params := params{ID: id} flag.Uint64VarP(¶ms.Interval, "interval", "i", 30, "Interval in seconds to refresh lock") flag.Uint64VarP(¶ms.TTL, "ttl", "t", 0, "TTL for key in seconds, leave 0 for (2 * interval)") flag.StringVarP(¶ms.Key, "key", "k", "/lock", "Key to use as lock") flag.BoolVarP(¶ms.Blocking, "block", "b", false, "Block if we failed to acquire the lock") flag.StringVarP(¶ms.Addr, "etcd", "e", defaultAddr, "address of etcd machine") flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage of %s: [options] -- command args\n", os.Args[0]) flag.PrintDefaults() fmt.Fprintf(os.Stderr, "\ncommand will be run with args via fork/exec not a shell\n") } flag.Parse() if params.TTL == 0 { params.TTL = params.Interval * 2 } params.Args = flag.Args() if len(params.Args) < 1 { d.Fatal("command is required") } cmd := resolveCommand(params.Args[0]) if cmd == "" { d.Fatal("") } params.Args[0] = cmd hostname, err := os.Hostname() if err != nil { d.FatalWithFields(log.Fields{ "error": err, "func": "os.Hostname", }, "failed to get hostname") } c := etcd.NewClient([]string{params.Addr}) l, err := lock.Acquire(c, params.Key, hostname, params.TTL, params.Blocking) if err != nil { d.FatalWithFields(log.Fields{ "error": err, "func": "lock.Acquire", "lock": params.Key, "ttl": params.TTL, "blocking": params.Blocking, }, "failed to get lock") } d.Defer(func() { if err := l.Release(); err != nil { d.FatalWithFields(log.Fields{ "error": err, "func": "l.Release", }, "failed to release lock") } }) params.Lock = l args, err := json.Marshal(¶ms) if err != nil { d.FatalWithFields(log.Fields{ "error": err, "func": "json.Marshal", }, "failed to serialize params") } serviceDone := make(chan struct{}) base := filepath.Base(params.Args[0]) target := fmt.Sprintf("locker-%s-%d.service", base, id) locker := resolveCommand("locker") if locker == "" { d.Fatal("") } go runService(d, serviceDone, params.ID, params.TTL, target, locker, base, string(args)) sigs := make(chan os.Signal) signal.Notify(sigs, os.Interrupt, syscall.SIGTERM) select { case <-serviceDone: log.WithField("service_state", "done").Info("service is done") case s := <-sigs: log.WithField("signal", s).Info("signal received") if err := killService(target, int32(s.(syscall.Signal))); err != nil { log.WithField("error", err).Info("failed to kill service") } } }
func main() { conf := &Conf{} flag.StringVarP(&conf.ClientID, "client-id", "i", "", "OAuth client ID") flag.StringVarP(&conf.ClientSecret, "client-secret", "s", "", "OAuth client secret") flag.StringVarP(&conf.Port, "port", "p", "8080", "Port to listen on") flag.Parse() if conf.ClientID == "" || conf.ClientSecret == "" { fmt.Printf("usage: procure --client-id <id> --client-secret <id>\n") flag.PrintDefaults() os.Exit(1) } respChan := make(chan *CallbackResponse) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("See console.\n")) err := r.ParseForm() if err != nil { fmt.Fprintf(os.Stderr, "Could not parse incoming form\n") return } response := &CallbackResponse{ code: r.Form.Get("code"), state: r.Form.Get("state"), } if response.code == "" { fmt.Fprintf(os.Stderr, "Server did not provide 'code' parameter\n") return } if response.state == "" { fmt.Fprintf(os.Stderr, "Server did not provide 'state' parameter\n") return } respChan <- response }) go func() { fmt.Printf("Listening for callback on :%v\n", conf.Port) err := http.ListenAndServe("localhost:"+conf.Port, nil) if err != nil { panic(err) } }() spotifyEndpoint := oauth2.Endpoint{ AuthURL: "https://accounts.spotify.com/authorize", TokenURL: "https://accounts.spotify.com/api/token", } oauthConf := &oauth2.Config{ ClientID: conf.ClientID, ClientSecret: conf.ClientSecret, RedirectURL: "http://localhost:" + conf.Port, Scopes: []string{"playlist-modify-public", "user-read-email"}, Endpoint: spotifyEndpoint, } // should use a real state here url := oauthConf.AuthCodeURL("state") fmt.Printf("Visit the URL for the auth dialog: %v\n", url) response := <-respChan // should validate state here token, err := oauthConf.Exchange(oauth2.NoContext, response.code) if err != nil { exitWithError(err.Error()) } fmt.Printf("\n") fmt.Printf("Success!\n") fmt.Printf("Access token: %v\n", token.AccessToken) fmt.Printf("Refresh token: %v\n", token.RefreshToken) fmt.Printf("Access token expires in: %v\n", token.Expiry.Sub(time.Now())) }
func usage() { fmt.Fprintf(os.Stderr, "Usage: %s [-w (num | num%% | .num) ] file [file...]\n", os.Args[0]) flag.PrintDefaults() }
func main() { output := "" mimetype := "" filetype := "" match := "" siteurl := "" htmlMinifier := &html.Minifier{} xmlMinifier := &xml.Minifier{} flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage: %s [options] [input]\n\nOptions:\n", os.Args[0]) flag.PrintDefaults() fmt.Fprintf(os.Stderr, "\nInput:\n Files or directories, leave blank to use stdin\n") } flag.StringVarP(&output, "output", "o", "", "Output file or directory, leave blank to use stdout") flag.StringVar(&mimetype, "mime", "", "Mimetype (text/css, application/javascript, ...), optional for input filenames, has precendence over -type") flag.StringVar(&filetype, "type", "", "Filetype (css, html, js, ...), optional for input filenames") flag.StringVar(&match, "match", "", "Filename pattern matching using regular expressions, see https://github.com/google/re2/wiki/Syntax") flag.BoolVarP(&recursive, "recursive", "r", false, "Recursively minify directories") flag.BoolVarP(&hidden, "all", "a", false, "Minify all files, including hidden files and files in hidden directories") flag.BoolVarP(&list, "list", "l", false, "List all accepted filetypes") flag.BoolVarP(&verbose, "verbose", "v", false, "Verbose") flag.BoolVarP(&watch, "watch", "w", false, "Watch files and minify upon changes") flag.BoolVarP(&update, "update", "u", false, "Update binary") flag.StringVar(&siteurl, "url", "", "URL of file to enable URL minification") flag.BoolVar(&htmlMinifier.KeepDefaultAttrVals, "html-keep-default-attrvals", false, "Preserve default attribute values") flag.BoolVar(&htmlMinifier.KeepWhitespace, "html-keep-whitespace", false, "Preserve whitespace characters but still collapse multiple whitespace into one") flag.BoolVar(&xmlMinifier.KeepWhitespace, "xml-keep-whitespace", false, "Preserve whitespace characters but still collapse multiple whitespace into one") flag.Parse() rawInputs := flag.Args() Error = log.New(os.Stderr, "ERROR: ", 0) if verbose { Info = log.New(os.Stderr, "INFO: ", 0) } else { Info = log.New(ioutil.Discard, "INFO: ", 0) } if update { if err := equinoxUpdate(); err != nil { Error.Fatalln(err) } return } if list { var keys []string for k := range filetypeMime { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { fmt.Println(k + "\t" + filetypeMime[k]) } return } usePipe := len(rawInputs) == 0 mimetype = getMimetype(mimetype, filetype, usePipe) var err error if match != "" { pattern, err = regexp.Compile(match) if err != nil { Error.Fatalln(err) } } tasks, dirDst, ok := expandInputs(rawInputs) if !ok { os.Exit(1) } if output != "" { output = sanitizePath(output) if dirDst { if output[len(output)-1] != '/' { output += "/" } if err := os.MkdirAll(output, 0777); err != nil { Error.Fatalln(err) } } } if ok = expandOutputs(output, usePipe, &tasks); !ok { os.Exit(1) } m = min.New() m.AddFunc("text/css", css.Minify) m.Add("text/html", htmlMinifier) m.AddFunc("text/javascript", js.Minify) m.AddFunc("image/svg+xml", svg.Minify) m.AddFuncRegexp(regexp.MustCompile("[/+]json$"), json.Minify) m.AddRegexp(regexp.MustCompile("[/+]xml$"), xmlMinifier) if m.URL, err = url.Parse(siteurl); err != nil { Error.Fatalln(err) } var watcher *RecursiveWatcher if watch { if usePipe || output == "" { Error.Fatalln("watch only works with files that do not overwrite themselves") } else if len(rawInputs) > 1 { Error.Fatalln("watch only works with one input directory") } input := sanitizePath(rawInputs[0]) info, err := os.Stat(input) if err != nil || !info.Mode().IsDir() { Error.Fatalln("watch only works with an input directory") } watcher, err = NewRecursiveWatcher(input, recursive) if err != nil { Error.Fatalln(err) } defer watcher.Close() } start := time.Now() var fails int32 if verbose { for _, t := range tasks { if ok := minify(mimetype, t); !ok { fails++ } } } else { var wg sync.WaitGroup for _, t := range tasks { wg.Add(1) go func(t task) { defer wg.Done() if ok := minify(mimetype, t); !ok { atomic.AddInt32(&fails, 1) } }(t) } wg.Wait() } if watch { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) input := sanitizePath(rawInputs[0]) files := watcher.Run() for files != nil { select { case <-c: watcher.Close() case file, ok := <-files: if !ok { files = nil break } file = sanitizePath(file) if strings.HasPrefix(file, input) { t := task{src: file, srcDir: input} if t.dst, err = getOutputFilename(output, t); err != nil { Error.Println(err) continue } if !verbose { fmt.Fprintln(os.Stderr, file, "changed") } if ok := minify(mimetype, t); !ok { fails++ } } } } } if verbose { Info.Println(time.Since(start), "total") } if fails > 0 { os.Exit(1) } }
func init() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "\n") fmt.Fprintf(os.Stderr, "nrcq(8) System Administration Utilities nrcq(8)\n") fmt.Fprintf(os.Stderr, "\n") fmt.Fprintf(os.Stderr, "NAME\n") fmt.Fprintf(os.Stderr, " nrcq - NagRestConf Query utility\n") fmt.Fprintf(os.Stderr, "\n") fmt.Fprintf(os.Stderr, "SYNOPSIS\n") fmt.Fprintf(os.Stderr, " nrcq [options] URL ENDPOINT\n") fmt.Fprintf(os.Stderr, "\n") fmt.Fprintf(os.Stderr, "DESCRIPTION\n") flag.PrintDefaults() fmt.Fprintf(os.Stderr, "\n") fmt.Fprintf(os.Stderr, "EXAMPLES\n") fmt.Fprintf(os.Stderr, " Show all valid endpoints:\n") fmt.Fprintf(os.Stderr, " nrcq -L\n") fmt.Fprintf(os.Stderr, "\n") fmt.Fprintf(os.Stderr, " List all nagios options for the servicesets table:\n") fmt.Fprintf(os.Stderr, " nrcq -l servicesets\n") fmt.Fprintf(os.Stderr, "\n") fmt.Fprintf(os.Stderr, " Show all hosts:\n") fmt.Fprintf(os.Stderr, " nrcq http://server/rest show/hosts\n") fmt.Fprintf(os.Stderr, "\n") fmt.Fprintf(os.Stderr, " Show a subset of hosts using a simple RE2 regular expression:\n") fmt.Fprintf(os.Stderr, " nrcq http://server/rest show/hosts") fmt.Fprintf(os.Stderr, " -f \"name:host2\"\n") fmt.Fprintf(os.Stderr, "\n") fmt.Fprintf(os.Stderr, " Show a subset of services using a complex RE2 regular expression:\n") fmt.Fprintf(os.Stderr, " (See https://github.com/google/re2/wiki/Syntax)\n") fmt.Fprintf(os.Stderr, " nrcq http://server/rest show/services") fmt.Fprintf(os.Stderr, " -f \"name:\\bhost2\\b|web,svcdesc:(?i)swap\"\n") fmt.Fprintf(os.Stderr, "\n") fmt.Fprintf(os.Stderr, " Add a new host:\n") fmt.Fprintf(os.Stderr, " nrcq http://server/rest add/hosts \\\n") fmt.Fprintf(os.Stderr, " -d name:server1 \\\n") fmt.Fprintf(os.Stderr, " -d alias:server1 \\\n") fmt.Fprintf(os.Stderr, " -d ipaddress:server1.there.gq \\\n") fmt.Fprintf(os.Stderr, " -d template:hsttmpl-local \\\n") fmt.Fprintf(os.Stderr, " -d servicesets:example-lin\n") fmt.Fprintf(os.Stderr, "\n") fmt.Fprintf(os.Stderr, " Delete a host and all of its services:\n") fmt.Fprintf(os.Stderr, " nrcq http://server/rest delete/services \\\n") fmt.Fprintf(os.Stderr, " -d name:server1 \\\n") fmt.Fprintf(os.Stderr, " -d \"svcdesc:.*\"\n") fmt.Fprintf(os.Stderr, " nrcq http://server/rest delete/hosts \\\n") fmt.Fprintf(os.Stderr, " -d name:server1 \\\n") fmt.Fprintf(os.Stderr, "\n") } flag.StringVarP(&Args.folder, "folder", "F", "local", "The system folder to query.") flag.StringVarP(&Args.filter, "filter", "f", "", "A client side RE2 regex filter, 'option:regex[,option:regex]...'") flag.BoolVarP(&Args.version, "version", "v", false, "Show the version of this program.") flag.BoolVarP(&Args.newline, "pack", "p", false, "Remove spaces and lines from the Json output.") flag.BoolVarP(&Args.brief, "complete", "c", false, "Also show fields with empty values.") // Done automatically now: //flag.BoolVarP(&Args.encode, "encode", "e", false, // "URL Encode output where necessary so it can be piped to another tool.") flag.BoolVarP(&Args.listendpoints, "listendpoints", "L", false, "List all endpoints/tables.") flag.StringVarP(&Args.username, "username", "U", "", "Username for Basic Auth.") flag.StringVarP(&Args.password, "password", "P", "", "Password for Basic Auth.") flag.StringVarP(&Args.list, "list", "l", "", "List all options for the specified table. Required fields are\n\t preceded by a star, '*'.") flag.BoolVarP(&Args.json, "json", "j", false, "Output in JSON format.") flag.VarP(&dataFlag, "data", "d", "Set extra data to send, 'option:value'.\n\tThe user should not urlencode data, nrcq will do it.\n\tMay be used multiple times.") }
func main() { flag.Usage = func() { type UsageContext struct { Name string } ctx := &UsageContext{ Name: filepath.Base(os.Args[0]), } usage.Execute(os.Stderr, ctx) flag.PrintDefaults() } flag.Parse() fatalif(*targetFlag == "", "") f, err := os.Create(*targetFlag) if err != nil { panic(err) } target, err := filepath.Abs(*targetFlag) if err != nil { panic(err) } pkg := path.Base(path.Dir(target)) if *pkgFlag != "" { pkg = *pkgFlag } name := pkg if *bundleFlag != "" { name = *bundleFlag } ctx := &BundleContext{ Package: pkg, Bundle: name, Compressed: *compressFlag, RetainUncompressed: *retainUncompressedFlag, UncompressOnInit: *uncompressOnInitFlag, } header.Execute(f, ctx) excludes := strings.Split(*excludeFlag, ",") for _, root := range flag.Args() { if exclude(root, excludes) { continue } if *recurseFlag { filepath.Walk(root, func(path string, info os.FileInfo, err error) error { if exclude(path, excludes) { return filepath.SkipDir } if !info.IsDir() { fmt.Println(path) writeEntry(f, root, path) } return nil }) } else { fmt.Println(root) writeEntry(f, root, root) } } footer.Execute(f, ctx) }
func usage() { PrintErr("usage: hugo [flags]", "") flag.PrintDefaults() os.Exit(0) }
func main() { log.SetFlags(0) flag.StringVarP(&infile, "in", "i", "", "input file") flag.StringVarP(&outfile, "out", "o", "", "output file; defaults to '<input file>.go'") flag.StringVarP(&packageName, "package", "p", "", "package name for generated file; defaults to 'msgs' or 'srvs'") flag.BoolVar(&dryRun, "dry-run", false, "output the file that would be generated to stdout") flag.Parse() if flag.NArg() < 1 { log.Printf("must provide type of generator") flag.PrintDefaults() os.Exit(1) } templateType := flag.Arg(0) if packageName == "" { packageName = templateType + "s" } basename := fmt.Sprintf("%s.tmpl", templateType) data, err := Asset(basename) if err != nil { log.Printf("unrecognized generator template: %s (%s)", templateType, err) flag.PrintDefaults() os.Exit(1) } tmpl := template.New(basename) tmpl = tmpl.Funcs(map[string]interface{}{ // HACK(ppg): Allow setting a loop variable a struct so we can use it "setloopvar": func(setter loopVarSetter, value interface{}) interface{} { setter.SetLoopVar(value) return setter }, }) tmpl, err = tmpl.Parse(string(data)) if err != nil { log.Printf("unable to template %s: %s", templateType, err) os.Exit(1) } data, err = Asset("msg.partial.tmpl") if err != nil { log.Printf("unrecognized generator template: %s (%s)", templateType, err) flag.PrintDefaults() os.Exit(1) } tmpl2 := tmpl.New("msg.partial.tmpl") _, err = tmpl2.Parse(string(data)) if err != nil { log.Printf("unable to template %s: %s", templateType, err) os.Exit(1) } if flag.NArg() > 1 { log.Printf("unrecognized arguments: %v", flag.Args()[1:]) flag.PrintDefaults() os.Exit(1) } if infile == "" { log.Printf("must provide input file") flag.PrintDefaults() os.Exit(1) } if outfile == "" { outfile = infile + ".go" } // Read input file data, err = ioutil.ReadFile(infile) if err != nil { log.Fatalf("failed to read infile %s: %s", infile, err) } basename = filepath.Base(infile) fileInfo := FileInfo{ InFile: infile, InFileBase: filepath.Base(infile), Raw: string(data), MD5Sum: fmt.Sprintf("%x", md5.Sum(data)), PackageName: packageName, Name: strings.TrimSuffix(basename, filepath.Ext(basename)), } // Parse by type var spec interface{} switch templateType { case "msg": var msgSpec *MsgSpec msgSpec, err = parseMsgSpec(fileInfo.PackageName, fileInfo.Name, data) if err != nil { log.Fatalf("failed to parse %s spec: %s", templateType, err) } spec = msgSpec case "srv": var srvSpec *SrvSpec srvSpec, err = parseSrvSpec(fileInfo.PackageName, fileInfo.Name, data) if err != nil { log.Fatalf("failed to parse %s spec: %s", templateType, err) } spec = srvSpec default: log.Fatalf("no parser configured: %s", templateType) } buf := bytes.NewBuffer([]byte{}) err = tmpl.Execute(buf, map[string]interface{}{"FileInfo": fileInfo, "Spec": spec}) if err != nil { log.Fatalf("failed to generate Go file: %s", err) } fset := token.NewFileSet() ast, err := parser.ParseFile(fset, "", buf.Bytes(), parser.ParseComments) if err != nil { log.Fatalf("bad Go source code was generated: %s\n%s", err, buf.String()) } buf.Reset() err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(buf, fset, ast) if err != nil { log.Fatalf("generated Go source code could not be reformatted: %s", err) } if dryRun { fmt.Println(buf.String()) return } err = ioutil.WriteFile(outfile, buf.Bytes(), 0644) if err != nil { log.Fatalf("failed to write go file: %s", err) } log.Printf("Wrote %s from %s", outfile, infile) }
func main() { output := "" mimetype := "" filetype := "" match := "" siteurl := "" htmlMinifier := &html.Minifier{} flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage: %s [options] [input]\n\nOptions:\n", os.Args[0]) flag.PrintDefaults() fmt.Fprintf(os.Stderr, "\nInput:\n Files or directories, optional when using piping\n") } flag.StringVarP(&output, "output", "o", "", "Output (concatenated) file (stdout when empty) or directory") flag.StringVar(&mimetype, "mime", "", "Mimetype (text/css, application/javascript, ...), optional for input filenames, has precendence over -type") flag.StringVar(&filetype, "type", "", "Filetype (css, html, js, ...), optional for input filenames") flag.StringVar(&match, "match", "", "Filename pattern matching using regular expressions, see https://github.com/google/re2/wiki/Syntax") flag.BoolVarP(&recursive, "recursive", "r", false, "Recursively minify directories") flag.BoolVarP(&hidden, "all", "a", false, "Minify all files, including hidden files and files in hidden directories") flag.BoolVarP(&list, "list", "l", false, "List all accepted filetypes") flag.BoolVarP(&verbose, "verbose", "v", false, "Verbose") flag.StringVar(&siteurl, "url", "", "URL of file to enable URL minification") flag.BoolVar(&htmlMinifier.KeepDefaultAttrVals, "html-keep-default-attrvals", false, "Preserve default attribute values") flag.BoolVar(&htmlMinifier.KeepWhitespace, "html-keep-whitespace", false, "Preserve whitespace characters but still collapse multiple whitespace into one") flag.Parse() rawInputs := flag.Args() if list { var keys []string for k := range filetypeMime { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { fmt.Println(k + "\t" + filetypeMime[k]) } return } usePipe := len(rawInputs) == 0 mimetype = getMimetype(mimetype, filetype, usePipe) if match != "" { var err error pattern, err = regexp.Compile(match) if err != nil { fmt.Fprintln(os.Stderr, "ERROR: "+err.Error()) os.Exit(1) } } tasks, dirDst, ok := expandInputs(rawInputs) if !ok { os.Exit(1) } if ok = expandOutputs(output, dirDst, usePipe, &tasks); !ok { os.Exit(1) } m = min.New() m.AddFunc("text/css", css.Minify) m.Add("text/html", htmlMinifier) m.AddFunc("text/javascript", js.Minify) m.AddFunc("image/svg+xml", svg.Minify) m.AddFuncRegexp(regexp.MustCompile("[/+]json$"), json.Minify) m.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify) var err error if m.URL, err = url.Parse(siteurl); err != nil { fmt.Fprintln(os.Stderr, "ERROR: "+err.Error()) os.Exit(1) } var fails int32 if verbose { for _, t := range tasks { if ok := minify(mimetype, t); !ok { fails++ } } } else { var wg sync.WaitGroup for _, t := range tasks { wg.Add(1) go func(t task) { defer wg.Done() if ok := minify(mimetype, t); !ok { atomic.AddInt32(&fails, 1) } }(t) } wg.Wait() } if fails > 0 { os.Exit(1) } }
func usage() { fmt.Fprintf(os.Stderr, "Usage: %s [OPTIONS] <url> -- <command>\n", os.Args[0]) flag.PrintDefaults() }
func main() { pflag.Usage = func() { fmt.Print(`usage: tuplespace <cmd> <args...> Commands: send <tuple> read <tuple> take <tuple> readall <tuple> takeall <tuple> Where <tuple> is in the form '[<value>|null, ...]'. Flags: `) pflag.PrintDefaults() fmt.Print(` Examples: tuplespace send '["cmd", "uname -a"]' tuplespace read '["cmd", null]' `) } pflag.Parse() runtime.GOMAXPROCS(runtime.NumCPU()) if len(pflag.Args()) < 2 { fatalf("invalid number of arguments\n") } timeout := *timeoutFlag command := pflag.Arg(0) c := client.NewTupleSpaceClient(*serverFlag) switch command { case "send": tuple := parseTuple(pflag.Arg(1)) tuples := make([]tuplespace.Tuple, *copiesFlag) for i := 0; i < *copiesFlag; i++ { tuples[i] = tuple } log.Info("Sending %d tuples", *copiesFlag) err := c.SendMany(tuples, timeout) if err != nil { fatalf("failed to send tuples: %s", err) } case "read", "take": match := pflag.Arg(1) tuple := map[string]interface{}{} var err error switch command { case "read": err = c.Read(match, timeout, tuple) case "take": err = c.Take(match, timeout, tuple) } if err != nil { fatalf("failed to read tuple: %s", err) } if !*silentFlag { fmt.Printf("%v\n", tuple) } case "readall", "takeall": match := pflag.Arg(1) tuples := []map[string]interface{}{} var err error switch command { case "readall": err = c.ReadAll(match, timeout, &tuples) case "takeall": err = c.TakeAll(match, timeout, &tuples) } if err != nil { fatalf("failed to read tuples: %s", err) } if !*silentFlag { for _, tuple := range tuples { fmt.Printf("%s\n", tuple) } } default: fatalf("unknown command: %s", command) } }