func main() { flag.Parse() if len(flag.Args()) == 0 { year := int(time.Now().Year()) month := int(time.Now().Month()) calendar(month, year) } else if len(flag.Args()) == 1 { year, err := strconv.Atoi(flag.Arg(0)) if err != nil { log.Fatal(err) } for month := 1; month <= 12; month++ { calendar(month, year) fmt.Println() } } else if len(flag.Args()) == 2 { month, err := strconv.Atoi(flag.Arg(0)) if err != nil { log.Fatal(err) } year, err := strconv.Atoi(flag.Arg(1)) if err != nil { log.Fatal(err) } calendar(month, year) } }
func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s", Help) os.Exit(1) } flag.Parse() if *version { fmt.Printf("%s\n", Version) os.Exit(0) } if flag.NArg() > 1 { fatal.Fatalf("extra operand %s", flag.Arg(1)) } var ( file *os.File err error ) if flag.Arg(0) == "-" || flag.NArg() == 0 { file = os.Stdin } else { file, err = os.Open(flag.Arg(0)) if err != nil { fatal.Fatalln(err) } defer file.Close() } ok := tsort(file) os.Exit(ok) }
func main() { flag.Usage = func() { // This is a little weird because I want to insert the correct // UTMP/WTMP file names into the Help output, but usually my // Help constants are raw string literals, so I had to // break it up into a couple chunks and move around some formatting. fmt.Fprintf(os.Stderr, "%s %s. %s %s", Help1, utmp.UtmpFile, utmp.WtmpFile, Help2) os.Exit(1) } flag.Parse() if *version { fmt.Printf("%s\n", Version) os.Exit(0) } switch flag.NArg() { case 0: uptime(utmp.UtmpFile, utmp.CheckPIDs) case 1: uptime(flag.Arg(0), 0) default: fatal.Fatalf("extra operand %s\n", flag.Arg(1)) } }
func main() { board, id, err := parseThreadId(flag.Arg(0)) if err != nil { fmt.Printf("Invalid input: %s\n", flag.Arg(0)) flag.Usage() os.Exit(1) } ticker := time.NewTicker(*refresh) for { log.Println("Loading thread") go loadThread(board, id) <-ticker.C } }
func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s", Help) os.Exit(1) } flag.Parse() if *version { fmt.Printf("%s", Version) os.Exit(0) } if *unset != "" { os.Unsetenv(*unset) } cmd := new(exec.Cmd) cmd.Env = env // Check for "-" as an argument, because it means the same as "-i" if flag.Arg(0) == "-" { cmd.Env = make([]string, 0) } for i, arg := range flag.Args() { if strings.Index(arg, delim) > 0 { cmd.Env = append(cmd.Env, arg) } else if arg != "-" { if *nullEol { fatal.Fatalln("cannot specify --null (-0) with command") } cmd.Path = arg cmd.Args = append(cmd.Args, flag.Args()[i:]...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := execvp(cmd) if err != nil { fatal.Fatalln(err) } return } i++ } eol := '\n' if *nullEol { eol = '\x00' } for _, e := range env { fmt.Printf("%s%c", e, eol) } return }
func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s", Help) os.Exit(1) } flag.Parse() if *version { fmt.Fprintf(os.Stdout, "%s", Version) os.Exit(0) } if len(flag.Args()) > 0 { for i := 0; i < len(flag.Args()); i++ { filename := flag.Arg(i) _, err := os.Stat(filename) if err == nil { now := time.Now() os.Chtimes(filename, now, now) } else if !(*nocreate) { f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0644) f.Close() if err != nil { log.Fatal(err) } } } } }
func main() { logmgr.SetOutput(os.Stderr) if flagVerbose { logmgr.SetLevel(logrus.DebugLevel) } else { logmgr.SetLevel(logrus.InfoLevel) } flag.Parse() conf := &config.BuildConfig{ BuildDir: flagBuildDir, OutputDir: flag.Arg(0), Platform: flagPlatform, Arch: flagArch, } recipes := flag.Args()[1:] // Special case - passing a single 'all' means build all binaries. if len(recipes) == 1 && recipes[0] == "all" { recipes = builder.AllBinaries() } log.WithField("recipes", recipes).Info("Starting build") err := builder.Build(recipes, conf) if err != nil { log.WithField("err", err).Error("Error building") } else { log.Info("Successfully built") } }
func parseFlags() (*cmdConfig, *busltee.Config, error) { publisherConf := &busltee.Config{} cmdConf := &cmdConfig{} cmdConf.RollbarEnvironment = os.Getenv("ROLLBAR_ENVIRONMENT") cmdConf.RollbarToken = os.Getenv("ROLLBAR_TOKEN") // Connection related flags flag.BoolVarP(&publisherConf.Insecure, "insecure", "k", false, "allows insecure SSL connections") flag.IntVar(&publisherConf.Retry, "retry", 5, "max retries for connect timeout errors") flag.IntVar(&publisherConf.StreamRetry, "stream-retry", 60, "max retries for streamer disconnections") flag.Float64Var(&publisherConf.Timeout, "connect-timeout", 1, "max number of seconds to connect to busl URL") // Logging related flags flag.StringVar(&publisherConf.LogPrefix, "log-prefix", "", "log prefix") flag.StringVar(&publisherConf.LogFile, "log-file", "", "log file") flag.StringVar(&publisherConf.RequestID, "request-id", "", "request id") if flag.Parse(); len(flag.Args()) < 2 { return nil, nil, errors.New("insufficient args") } publisherConf.URL = flag.Arg(0) publisherConf.Args = flag.Args()[1:] return cmdConf, publisherConf, nil }
func main() { var cluster *string = flag.String("cluster", "default", "Name of cluster") flag.Parse() if flag.NArg() < 2 { fmt.Println("Usage:\n\taws-rollout [service] [image]") return } var service string = flag.Arg(0) var image string = flag.Arg(1) svc := ecs.New(session.New()) clusterArn, err := findClusterArn(svc, *cluster) if err != nil { fmt.Println(err.Error()) return } serviceArn, err := findServiceArn(svc, clusterArn, service) if err != nil { fmt.Println(err.Error()) return } taskArn, err := findTaskArn(svc, clusterArn, serviceArn) newTaskArn, err := setImage(svc, taskArn, image) params := &ecs.UpdateServiceInput{ Service: aws.String(serviceArn), Cluster: aws.String(clusterArn), TaskDefinition: aws.String(newTaskArn), } serv, err := svc.UpdateService(params) if err != nil { fmt.Println(err.Error()) return } fmt.Printf("Deployed %s %d", newTaskArn, *serv.Service.PendingCount) }
func main() { flag.Parse() // Scan the arguments list fmt.Fprintln(os.Stdout, LOGO) if *versionFlag { fmt.Println("Version:", APP_VERSION) return } cmd := flag.Arg(0) name := flag.Arg(1) switch cmd { case "help": printHelpCommand(nil) case "init": createNewProject(name) case "get": getNewImport(name) case "run": runDevelopmentServer(name) default: printHelpCommand("Do Not Recognize command: [" + cmd + "]") } }
func main() { flag.Usage = func() { fmt.Fprint(os.Stderr, Usage) } flag.IntVarP(&options.Port, "port", "p", 8080, "") flag.StringVar(&options.CustomCSS, "custom-css", "", "") flag.Parse() options.Dir = flag.Arg(0) if options.Dir == "" { flag.Usage() os.Exit(1) } log.Println("Serving wiki from", options.Dir) // Parse base template var err error options.template, err = template.New("base").Parse(Template) if err != nil { log.Fatalln("Error parsing HTML template:", err) } // Trim trailing slash from root path if strings.HasSuffix(options.Dir, "/") { options.Dir = options.Dir[:len(options.Dir)-1] } // Verify that the wiki folder exists _, err = os.Stat(options.Dir) if os.IsNotExist(err) { log.Fatalln("Directory not found") } // Check if the wiki folder is a Git repository options.git = IsGitRepository(options.Dir) if options.git { log.Println("Git repository found in directory") } else { log.Println("No git repository found in directory") } http.Handle("/api/diff/", commonHandler(DiffHandler)) http.Handle("/", commonHandler(WikiHandler)) log.Println("Listening on:", options.Port) http.ListenAndServe(fmt.Sprintf(":%d", options.Port), nil) }
func main() { NAME = path.Base(os.Args[0]) flags := make(map[string]*bool) flag.Usage = usageLong flags["version"] = flag.BoolP("version", "v", false, "Print version number and exit") flags["help"] = flag.BoolP("help", "h", false, "Print this help message and exit") flags["index"] = flag.BoolP("index", "i", false, "Create indexes for the lexicon") flag.Parse() // Handle -v/--version if *flags["version"] { fmt.Println(Version) os.Exit(0) } // Handle -h/--help if *flags["help"] { if strings.Contains(strings.Join(os.Args, " "), "--help") { usageLong() } else { usageShort() } os.Exit(0) } // Handle -i/--index if *flags["index"] { fmt.Println("Creating indexes") if err := index.Create(); err != nil { fmt.Fprintf(os.Stderr, "Error creating indexes: %v", err) os.Exit(1) } else { fmt.Println("Done") os.Exit(0) } } // Handle missing <text> argument if flag.NArg() == 0 { fmt.Fprintf(os.Stderr, "%s: missing <text> argument\n", NAME) usageLong() os.Exit(1) } fmt.Printf("Searching for %q\n", flag.Arg(0)) }
func main() { pflag.Usage = func() { fmt.Fprintf(os.Stderr, USAGE) } var output = pflag.StringP("output", "o", ".", "output directory") pflag.Parse() if pflag.NArg() == 1 { genRoutes(pflag.Arg(0), *output) } else { pflag.Usage() } }
func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s", Help) os.Exit(1) } flag.Parse() if *version { fmt.Printf("%s\n", Version) os.Exit(0) } if flag.NArg() > 1 { fatal.Fatalf("extra operand %s", flag.Arg(1)) } file := os.Stdin if (flag.Arg(0) != "-" && flag.Arg(0) != "") || flag.NArg() != 0 { var err error file, err = os.Open(flag.Arg(0)) if err != nil { fatal.Fatalln(err) } defer file.Close() } os.Exit(tsort(struct { io.Reader io.Writer }{ file, os.Stdout, })) }
// Run the program and return exit code. func run() int { flag.Usage = usageLong // make "-h" work similarly to "help" if err := config(); err != nil { errf("%s\n", err) return 1 } switch cmd := flag.Arg(0); cmd { case "download": return cmdDownload() case "init": return cmdInit() case "up", "start", "boot", "resume": return cmdUp() case "save", "suspend": return cmdSave() case "down", "halt", "stop": return cmdStop() case "poweroff": return cmdPoweroff() case "restart": return cmdRestart() case "reset": return cmdReset() case "delete": return cmdDelete() case "info": return cmdInfo() case "status": return cmdStatus() case "ssh": return cmdSSH() case "version": outf("Client version: %s\nGit commit: %s\n", Version, GitSHA) return 0 case "help": flag.Usage() return 0 case "": usageShort() return 0 default: errf("Unknown command %q\n", cmd) usageShort() return 1 } }
func main() { verbose := flag.BoolP("verbose", "v", false, "Verbose mode") flag.Parse() logger = initLogger(*verbose) switch { case len(flag.Args()) == 0: Serve() case len(flag.Args()) >= 1: RunCommand(flag.Arg(0), flag.Args()[1:]) default: printUsage() os.Exit(2) } }
func main() { args := parseFlags(os.Args) if unset != "" { os.Unsetenv(unset) } cmd := exec.Cmd{Env: env} // Check for "-" as an argument, because it means the same as "-i" if flag.Arg(0) == "-" { cmd.Env = []string{} } for i, arg := range args { if strings.Index(arg, "=") > 0 { cmd.Env = append(cmd.Env, arg) } else if arg != "-" { if nullEol { fatal.Fatalln("cannot specify --null (-0) with command") } cmd.Path = arg cmd.Args = append(cmd.Args, args[i:]...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := execvp(cmd); err != nil { fatal.Fatalln(err) } return } } eol := '\n' if nullEol { eol = '\x00' } for _, e := range env { fmt.Printf("%s%c", e, eol) } return }
func main() { pflag.Usage = func() { fmt.Fprintf(os.Stderr, USAGE) } var output = pflag.StringP("output", "o", ".", "output directory") var version = pflag.BoolP("version", "", false, "version") pflag.Parse() if *version { fmt.Println(VERSION) } else if pflag.NArg() == 1 { genRoutes(pflag.Arg(0), *output) } else { pflag.Usage() } }
func main() { versionFlag := flag.BoolP("version", "V", false, "Print version.") numberNonblank := flag.BoolP("number-nonblank", "b", false, "Number nonblank lines.") flag.Parse() version := "0.0.4" if *versionFlag { println(version) os.Exit(0) } if *numberNonblank { } file := flag.Arg(0) processInputFile(file) }
func main() { bFlag := flag.StringP("body-numbering", "b", "t", "style") flag.Parse() if len(flag.Args()) == 0 { bytes, _ := ioutil.ReadAll(os.Stdin) lines := strings.Split(string(bytes), "\n") linecount := 0 for i := 0; i < len(lines)-1; i++ { if *bFlag == "t" { if len(strings.TrimSpace(lines[i])) > 0 { linecount++ fmt.Printf("%6d %s\n", linecount, lines[i]) } else { fmt.Println(lines[i]) } } else { linecount++ fmt.Printf("%6d %s\n", linecount, lines[i]) } } } else if len(flag.Args()) > 0 { linecount := 0 for j := 0; j < len(flag.Args()); j++ { bytes, _ := ioutil.ReadFile(flag.Arg(j)) lines := strings.Split(string(bytes), "\n") for i := 0; i < len(lines)-1; i++ { if *bFlag == "t" { if len(strings.TrimSpace(lines[i])) > 0 { linecount++ fmt.Printf("%6d %s\n", linecount, lines[i]) } else { fmt.Println(lines[i]) } } else { linecount++ fmt.Printf("%6d %s\n", linecount, lines[i]) } } } } }
func main() { cFlag := flag.BoolP("no-create", "c", false, "do not create file") flag.Parse() if len(flag.Args()) > 0 { for i := 0; i < len(flag.Args()); i++ { filename := flag.Arg(i) _, err := os.Stat(filename) if err == nil { now := time.Now() os.Chtimes(filename, now, now) } else { if !(*cFlag) { f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0644) f.Close() if err != nil { log.Fatal(err) } } } } } }
func main() { var ( // general options stateDir = pflag.String("statedir", "", "the server state directory") help = pflag.BoolP("help", "h", false, "show this help") // server options server = pflag.BoolP("server", "s", false, "run the server in the foreground") port = pflag.IntP("port", "p", 40000, "server port to listen on") // client options method = pflag.StringP("method", "X", "GET", "client method") plugin = pflag.String("plugin", "", "client plugin") data = pflag.StringP("data", "d", "", "client body") headers = &repString{[]string{}} verbose = pflag.BoolP("verbose", "v", false, "show full http response") ) pflag.VarP(headers, "header", "H", "client request header") pflag.Parse() if *help { os.Exit(runHelp()) } if *server { os.Exit(runServer(*port, *stateDir)) } if pflag.NArg() < 1 { fmt.Fprintln(os.Stderr, "must pass in path to make api call") runHelp() os.Exit(1) } os.Exit(runClient(*stateDir, *plugin, *method, pflag.Arg(0), *data, headers.strs, *verbose)) }
func main() { flag.Parse() var bucketname string // TODO, remove channel? not using it or waiter uploads := make(chan FileUpload, 1) waiter := &sync.WaitGroup{} directory := flag.Arg(0) if *bucket == "" { bucketname = directory } else { bucketname = *bucket } fmt.Println("Uploading to bucket named: ", bucketname) fmt.Println("Publicly visible:", *public) s3bucket := sss.GetBucket(sss.Auth(), sss.Region, bucketname) err := filepath.Walk(directory, makeVisitor(uploads, s3bucket, waiter, args{ force: *force, mimetype: *mimetype, newer: *newer, newermetamtime: *newermetamtime, prefix: *prefix, public: *public, sse: *sse, })) if err != nil { fmt.Println(err) os.Exit(1) } waiter.Wait() // fmt.Printf("filepatxh.Walk() returned %v\n", err) }
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) } }
func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s\n", Help) os.Exit(0) } flag.Parse() if flag.NArg() == 0 { fmt.Fprintf(os.Stderr, "no input file given\n%s\n", Help) os.Exit(1) } if *version { fmt.Fprintf(os.Stderr, "%s\n", Version) os.Exit(0) } if flag.NArg() > 2 { log.Fatalf("too many arguments after %s\n", flag.Arg(1)) } var ( err error file string ) if flag.NArg() >= 1 { file = flag.Arg(0) } else { file = "-" } var inFile *os.File if file == "-" { inFile = os.Stdin file = "stdin" } else { inFile, err = os.Open(file) if err != nil { log.Fatalln(err) } } defer inFile.Close() // Start *seek bytes into file if *seek != "" { sv := parseSeek(*seek) _, err := inFile.Seek(sv, os.SEEK_SET) if err != nil { log.Fatalln(err) } } var outFile *os.File if flag.NArg() == 2 { outFile, err = os.OpenFile(flag.Arg(1), os.O_RDWR|os.O_CREATE, 0660) if err != nil { log.Fatalln(err) } } else { outFile = os.Stdout } defer outFile.Close() switch true { case *binary: dumpType = dumpBinary case *cfmt: dumpType = dumpCformat case *postscript: dumpType = dumpPostscript default: dumpType = dumpHex } out := bufio.NewWriter(outFile) defer out.Flush() if *reverse { if err := xxdReverse(inFile, out); err != nil { log.Fatalln(err) } } else { if err := xxd(inFile, out, file); err != nil { log.Fatalln(err) } } }
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() { flag.Parse() Args.data = []string(dataFlag) if Args.version { fmt.Printf("Nrcq version is %s\n", Version) os.Exit(0) } if Args.json { Args.encode = true } else { Args.encode = false } // Xfer the encode setting to the library nrc.SetEncode(Args.encode) // Args left after flag finishes url := flag.Arg(0) // Base URL, eg. "http://1.2.3.4/rest" ep := flag.Arg(1) // end point, eg. "show/hosts" if Args.list != "" { n := createObject(Args.list) if Args.json == true { fmt.Printf("%s\n", []byte(n.OptionsJson())) } else { DisplayArray(n.Options(), n.RequiredOptions()) } os.Exit(0) } if Args.listendpoints { n := endpointarr() if Args.json == true { fmt.Printf("%s\n", n) } else { DisplayArray(n, []string{}) } os.Exit(0) } if url == "" || ep == "" { fmt.Fprintf(os.Stderr, "ERROR: 2 non-option arguments expected.\n") flag.Usage() } if strings.HasPrefix(ep, "check/") { // GET REQUESTS n := createObject("check") err := n.Get(url, ep, Args.folder, Args.data) if err != nil { fmt.Printf("ERROR: %s\n", err.Error()) os.Exit(1) } if Args.json == true { n.ShowJson(Args.newline, false, "") } else { n.Show(false, "") } } else if strings.HasPrefix(ep, "show/") { // GET REQUESTS cmd := strings.Split(ep, "/") n := createObject(cmd[1]) err := n.Get(url, ep, Args.folder, Args.data) if err != nil { fmt.Printf("ERROR: %s\n", err.Error()) os.Exit(1) } if Args.json == true { n.ShowJson(Args.newline, Args.brief, Args.filter) } else { n.Show(Args.brief, Args.filter) } } else if strings.HasPrefix(ep, "add/") || strings.HasPrefix(ep, "modify/") || strings.HasPrefix(ep, "delete/") || strings.HasPrefix(ep, "restart/") || ep == "apply/nagioslastgoodconfig" { // POST REQUESTS cmd := strings.Split(ep, "/") n := createObject(cmd[1]) err := n.Post(url, ep, Args.folder, Args.data) if err != nil { fmt.Printf("ERROR: %s\n", err.Error()) os.Exit(1) } fmt.Printf("SUCCESS\n") } else if ep == "apply/nagiosconfig" { // This is the only Post request that produces output n := createObject("applynagiosconfig") err := n.Post(url, ep, Args.folder, Args.data) if err != nil { fmt.Printf("ERROR: %s\n", err.Error()) os.Exit(1) } if Args.json == true { n.ShowJson(Args.newline, Args.brief, Args.filter) } else { n.Show(Args.brief, Args.filter) } } }
// Read configuration from both profile and flags. Flags override profile. func config() error { var err error if B2D.Dir, err = getCfgDir(".boot2docker"); err != nil { return fmt.Errorf("failed to get current directory: %s", err) } filename := os.Getenv("BOOT2DOCKER_PROFILE") if filename == "" { filename = filepath.Join(B2D.Dir, "profile") } profile, err := getProfile(filename) if err != nil && !os.IsNotExist(err) { // undefined/empty profile works return err } if p := os.Getenv("VBOX_INSTALL_PATH"); p != "" && runtime.GOOS == "windows" { B2D.VBM = profile.Get("", "vbm", filepath.Join(p, "VBoxManage.exe")) } else { B2D.VBM = profile.Get("", "vbm", "VBoxManage") } B2D.SSH = profile.Get("", "ssh", "ssh") B2D.VM = profile.Get("", "vm", "boot2docker-vm") B2D.ISO = profile.Get("", "iso", filepath.Join(B2D.Dir, "boot2docker.iso")) if diskSize, err := strconv.ParseUint(profile.Get("", "disksize", "20000"), 10, 32); err != nil { return fmt.Errorf("invalid disk image size: %s", err) } else { B2D.DiskSize = uint(diskSize) } if memory, err := strconv.ParseUint(profile.Get("", "memory", "1024"), 10, 32); err != nil { return fmt.Errorf("invalid memory size: %s", err) } else { B2D.Memory = uint(memory) } if sshPort, err := strconv.ParseUint(profile.Get("", "sshport", "2022"), 10, 16); err != nil { return fmt.Errorf("invalid SSH port: %s", err) } else { B2D.SSHPort = uint16(sshPort) } if dockerPort, err := strconv.ParseUint(profile.Get("", "dockerport", "4243"), 10, 16); err != nil { return fmt.Errorf("invalid DockerPort: %s", err) } else { B2D.DockerPort = uint16(dockerPort) } // Host only networking settings B2D.HostIP = profile.Get("", "hostiP", "192.168.59.3") B2D.DHCPIP = profile.Get("", "dhcpip", "192.168.59.99") B2D.NetworkMask = profile.Get("", "netmask", "255.255.255.0") B2D.LowerIPAddress = profile.Get("", "lowerip", "192.168.59.103") B2D.UpperIPAddress = profile.Get("", "upperip", "192.168.59.254") B2D.DHCPEnabled = profile.Get("", "dhcp", "Yes") // Commandline flags override profile settings. flag.StringVar(&B2D.VBM, "vbm", B2D.VBM, "Path to VirtualBox management utility") flag.StringVar(&B2D.SSH, "ssh", B2D.SSH, "Path to SSH client utility") flag.StringVarP(&B2D.Dir, "dir", "d", B2D.Dir, "boot2docker config directory") flag.StringVar(&B2D.ISO, "iso", B2D.ISO, "Path to boot2docker ISO image") flag.UintVarP(&B2D.DiskSize, "disksize", "s", B2D.DiskSize, "boot2docker disk image size (in MB)") flag.UintVarP(&B2D.Memory, "memory", "m", B2D.Memory, "Virtual machine memory size (in MB)") flag.Var(newUint16Value(B2D.SSHPort, &B2D.SSHPort), "sshport", "Host SSH port (forward to port 22 in VM)") flag.Var(newUint16Value(B2D.DockerPort, &B2D.DockerPort), "dockerport", "Host Docker port (forward to port 4243 in VM)") flag.StringVar(&B2D.HostIP, "hostip", B2D.HostIP, "VirtualBox host-only network IP address") flag.StringVar(&B2D.NetworkMask, "netmask", B2D.NetworkMask, "VirtualBox host-only network mask") flag.StringVar(&B2D.DHCPEnabled, "dhcp", B2D.DHCPEnabled, "Enable VirtualBox host-only network DHCP") flag.StringVar(&B2D.DHCPIP, "dhcpip", B2D.DHCPIP, "VirtualBox host-only network DHCP server address") flag.StringVar(&B2D.LowerIPAddress, "lowerip", B2D.LowerIPAddress, "VirtualBox host-only network DHCP lower bound") flag.StringVar(&B2D.UpperIPAddress, "upperip", B2D.UpperIPAddress, "VirtualBox host-only network DHCP upper bound") flag.Parse() // Name of VM is the second argument. if vm := flag.Arg(1); vm != "" { B2D.VM = vm } return nil }