func (cm *ConfigManager) parseFlags() { pflag.StringVarP(&cm.Flags.ConfigFile, "configfile", "c", DefaultConfigFile, "Path to config") pflag.StringVarP(&cm.Flags.DestHost, "dest-host", "d", "", "Destination syslog hostname or IP") pflag.IntVarP(&cm.Flags.DestPort, "dest-port", "p", 0, "Destination syslog port") if utils.CanDaemonize { pflag.BoolVarP(&cm.Flags.NoDaemonize, "no-detach", "D", false, "Don't daemonize and detach from the terminal") } else { cm.Flags.NoDaemonize = true } pflag.StringVarP(&cm.Flags.Facility, "facility", "f", "user", "Facility") pflag.StringVar(&cm.Flags.Hostname, "hostname", "", "Local hostname to send from") pflag.StringVar(&cm.Flags.PidFile, "pid-file", "", "Location of the PID file") // --parse-syslog pflag.StringVarP(&cm.Flags.Severity, "severity", "s", "notice", "Severity") // --strip-color pflag.BoolVar(&cm.Flags.UseTCP, "tcp", false, "Connect via TCP (no TLS)") pflag.BoolVar(&cm.Flags.UseTLS, "tls", false, "Connect via TCP with TLS") pflag.BoolVar(&cm.Flags.Poll, "poll", false, "Detect changes by polling instead of inotify") pflag.Var(&cm.Flags.RefreshInterval, "new-file-check-interval", "How often to check for new files") _ = pflag.Bool("no-eventmachine-tail", false, "No action, provided for backwards compatibility") _ = pflag.Bool("eventmachine-tail", false, "No action, provided for backwards compatibility") pflag.StringVar(&cm.Flags.DebugLogFile, "debug-log-cfg", "", "the debug log file") pflag.StringVar(&cm.Flags.LogLevels, "log", "<root>=INFO", "\"logging configuration <root>=INFO;first=TRACE\"") pflag.Parse() cm.FlagFiles = pflag.Args() }
func main() { // Handle cli flags var port uint var bridge, logLevel string flag.UintVarP(&port, "port", "p", 40001, "listen port") flag.StringVarP(&bridge, "bridge", "b", "mistify0", "bridge to join interfaces to with OVS") flag.StringVarP(&logLevel, "log-level", "l", "warning", "log level: debug/info/warning/error/fatal") flag.Parse() // Set up logging if err := logx.DefaultSetup(logLevel); err != nil { log.WithFields(log.Fields{ "error": err, "func": "logx.DefaultSetup", }).Fatal("Could not set up logging") } o, err := ovs.NewOVS(bridge) if err != nil { os.Exit(1) } // Run HTTP Server if err := o.RunHTTP(port); err != nil { os.Exit(1) } }
func main() { var port uint var etcdAddr, logLevel string flag.UintVarP(&port, "port", "p", 19000, "listen port") flag.StringVarP(&etcdAddr, "etcd", "e", defaultEtcdAddr, "address of etcd machine") flag.StringVarP(&logLevel, "log-level", "l", "warn", "log level") flag.Parse() if err := logx.DefaultSetup(logLevel); err != nil { log.WithFields(log.Fields{ "error": err, "level": logLevel, }).Fatal("failed to set up logging") } etcdClient := etcd.NewClient([]string{etcdAddr}) if !etcdClient.SyncCluster() { log.WithFields(log.Fields{ "addr": etcdAddr, }).Fatal("unable to sync etcd cluster") } ctx := lochness.NewContext(etcdClient) _ = Run(port, ctx) }
func init() { flag.Usage = printUsage // set the defaults defaultSSL = true defaultPort = 38332 defaultAddress = "localhost" defaultConfigPath := computeDefaultConfigPath() flag.StringVarP(&flagConfigPath, "config", "c", defaultConfigPath, "config file path") flag.StringVarP(&flagUsername, "rpcuser", "u", "", "rpc user name") flag.StringVarP(&flagPassword, "rpcpassword", "p", "", "rpc password") flag.BoolVar(&flagSSL, "ssl", defaultSSL, "use secure sockets SSL") flag.IntVarP(&flagPort, "port", "n", defaultPort, "port number") flag.StringVarP(&flagAddress, "host", "a", defaultAddress, "server address") flag.BoolVarP(&verbose, "verbose", "v", false, "verbose output for debugging") // k , ignore server certificate errors (not recommended, only for testing self-signed certificates") flag.BoolVar(&flagHelp, "help", false, "Display this information") flag.BoolVar(&flagVersion, "version", false, "Display version information") flag.BoolVarP(&flagInsecure, "insecure", "k", false, "Allow connections to servers with 'insecure' SSL connections e.g. self-signed certificates. By default, this option is false, unless the server is localhost or an explicit IP address, in which case the option is true.") flag.Parse() flagSetMap = make(map[string]bool) flag.Visit(visitFlagSetMap) }
func init() { flag.StringVarP(&flagPlatform, "platform", "p", "linux", "the platform to build for") flag.StringVarP(&flagArch, "arch", "a", "amd64", "the architecture to build for") flag.StringVar(&flagBuildDir, "build-dir", "/tmp/sbuild", "the directory to use as a build directory") flag.BoolVarP(&flagVerbose, "verbose", "v", false, "be verbose") }
func main() { var port uint var etcdAddr, bstalk, logLevel string // Command line flags flag.StringVarP(&bstalk, "beanstalk", "b", "127.0.0.1:11300", "address of beanstalkd server") flag.StringVarP(&logLevel, "log-level", "l", "warn", "log level") flag.StringVarP(&etcdAddr, "etcd", "e", "http://127.0.0.1:4001", "address of etcd server") flag.UintVarP(&port, "http", "p", 7544, "http port to publish metrics. set to 0 to disable") flag.Parse() // Set up logger if err := logx.DefaultSetup(logLevel); err != nil { log.WithFields(log.Fields{ "error": err, "level": logLevel, }).Fatal("unable to to set up logrus") } etcdClient := etcd.NewClient([]string{etcdAddr}) if !etcdClient.SyncCluster() { log.WithFields(log.Fields{ "addr": etcdAddr, }).Fatal("unable to sync etcd cluster") } ctx := lochness.NewContext(etcdClient) log.WithField("address", bstalk).Info("connection to beanstalk") jobQueue, err := jobqueue.NewClient(bstalk, etcdClient) if err != nil { log.WithFields(log.Fields{ "error": err, "address": bstalk, }).Fatal("failed to create jobQueue client") } // Set up metrics m := setupMetrics(port) if m != nil { } agent := ctx.NewMistifyAgent() // Start consuming consume(jobQueue, agent, m) }
// Start the game and then, based on command line input, start up client // interface listeners. Finally, wait for ^C before exiting. func main() { var local, serve bool var endpoint string pflag.BoolVarP(&local, "local", "l", true, "run a local interactive REPL") pflag.BoolVarP(&serve, "serve", "s", false, "run a networked multiuser server") pflag.StringVarP(&endpoint, "endpoint", "e", ":4000", "where to run the networked server") pflag.Parse() done, events, spellbook := StartGame() if serve { go ListenTCP(endpoint, events, spellbook) } if local { go ListenLocal(events, spellbook) } interrupt := make(chan os.Signal) signal.Notify(interrupt, os.Interrupt) quitting := false for !quitting { select { case <-interrupt: events <- &ShutdownEvent{} case err := <-done: log.Print("main() stopping: ", err) quitting = true } } }
func main() { var widthstr string flag.StringVarP(&widthstr, "width", "w", "100%", "Output width. Supports column count, percentage and decimals.") flag.Usage = usage flag.Parse() if len(flag.Args()) == 0 { flag.Usage() os.Exit(1) } width := getColumns(widthstr) - 1 // -1 for the reset column for _, fpath := range flag.Args() { im := aimg.NewImage(width) handleErr(im.ParseFile(fpath)) if terminal.IsTerminal(os.Stdout) { fmt.Print(im.BlankReset()) } im.WriteTo(os.Stdout) w, h := im.ActualSize() fmt.Println("File:", filepath.Base(fpath), "size:", w, "x", h) } }
func parseArgs() args { result := args{} pflag.Usage = usage pflag.BoolVarP(&result.options.KeepGoing, "keep-going", "k", false, "") pflag.BoolVar(&result.options.CheckAll, "check-all", false, "") pflag.StringVarP(&result.scriptFile, "file", "f", "", "") verbose := pflag.BoolP("verbose", "v", false, "") quiet := pflag.BoolP("quiet", "q", false, "") topics := pflag.String("debug", "", "") pflag.Parse() if *topics != "" { result.debugTopics = strings.Split(*topics, ",") } // argh: really, we just want a callback for each occurence of -q // or -v, which decrements or increments verbosity if *quiet { result.verbosity = 0 } else if *verbose { result.verbosity = 2 } else { result.verbosity = 1 } result.options.Targets = pflag.Args() return result }
func Go() { smtpAddr := "localhost:1025" goflag := false for _, g := range os.Args[1:] { if strings.HasPrefix(g, "-") && !strings.HasPrefix(g, "--") { if strings.HasPrefix(g, "-from ") || strings.HasPrefix(g, "-from=") || strings.HasPrefix(g, "-smtp-addr ") || strings.HasPrefix(g, "-smtp-addr=") { goflag = true break } } } host, err := os.Hostname() if err != nil { host = "localhost" } username := "******" user, err := user.Current() if err == nil && user != nil && len(user.Username) > 0 { username = user.Username } fromAddr := username + "@" + host var recip []string if goflag { flag.StringVar(&smtpAddr, "smtp-addr", smtpAddr, "SMTP server address") flag.StringVar(&fromAddr, "from", fromAddr, "SMTP sender") flag.Parse() recip = flag.Args() } else { pflag.StringVar(&smtpAddr, "smtp-addr", smtpAddr, "SMTP server address") pflag.StringVarP(&fromAddr, "from", "f", fromAddr, "SMTP sender") pflag.Parse() recip = pflag.Args() } if len(recip) == 0 { fmt.Fprintln(os.Stderr, "missing recipient") os.Exit(10) } body, err := ioutil.ReadAll(os.Stdin) if err != nil { fmt.Fprintln(os.Stderr, "error reading stdin") os.Exit(11) } err = smtp.SendMail(smtpAddr, nil, fromAddr, recip, body) if err != nil { fmt.Fprintln(os.Stderr, "error sending mail") log.Fatal(err) } }
func main() { path := "" pflag.StringVarP(&path, "tsconfig", "t", "tsconfig.json", "your tsconfig.json path") pflag.Parse() if err := Update(path, pflag.Args()); err != nil { panic(err) } }
func init() { flag.BoolVar(&flagListProtocols, "list-protocols", false, "list all registered protocols and then exit") flag.BoolVar(&flagUseTransparent, "transparent", false, "use transparent proxying (only available on Linux)") flag.Uint16VarP(&flagListenPort, "port", "p", 0, "port to listen on") flag.StringVarP(&flagListenHost, "host", "h", "0.0.0.0", "host to listen on") }
func init() { flag.BoolVarP(&Version, "version", "v", false, "Output the current version of the application.") flag.StringVarP(&WorkingDir, "working-dir", "w", "./", "The directory where all the other directories reside. This "+ "will be prepended to the rest of the configurable directories.") flag.StringVarP(&OutputDir, "output-dir", "o", "public", "The directory where the results should be placed.") flag.BoolVarP(&EmptyOutputDir, "empty-output-dir", "x", false, "Before writing to the output-dir, delete anything inside of it.") flag.StringVarP(&TemplateDir, "template-dir", "t", "templates", "The directory where the site templates are located.") flag.StringVarP(&BlogDir, "blog-dir", "b", "blogs", "The directory where the blogs are located.") flag.StringVarP(&StaticDir, "static-dir", "s", "static", "The directory where the static assets are located.") flag.StringVarP(&URL, "url", "u", "", "The url to be prepended to link in the RSS feed. Defaults to "+ "the value in the channel <link>.") flag.IntVarP(&MaxIndexEntries, "index-entries", "i", 3, "The maximum number of entries to display on the index page.") }
func init() { flag.BoolVarP(&flagVerbose, "verbose", "v", false, "be more verbose") flag.BoolVarP(&flagQuiet, "quiet", "q", false, "be quiet") flag.BoolVarP(&flagTrace, "trace", "t", false, "trace bytes copied") flag.StringVarP(&flagHost, "host", "h", "", "host to listen on") flag.Uint16VarP(&flagPort, "port", "p", 8000, "port to listen on") flag.VarP(&flagAllowedSourceIPs, "source-ips", "s", "valid source IP addresses (if none given, all allowed)") flag.VarP(&flagAllowedDestinationIPs, "dest-ips", "d", "valid destination IP addresses (if none given, all allowed)") flag.StringVar(&flagRemoteListener, "remote-listener", "", "open the SOCKS port on the remote address (e.g. ssh://user:pass@host:port)") }
func init() { pflag.DurationVar(&config.TickerTime, "ticker-time", 60*time.Second, "Ticker time.") pflag.DurationVar(&config.DeleteTime, "delete-time", 60*time.Minute, "Time before deleting undesired units.") pflag.DurationVar(&config.UpdateCooldownTime, "update-cooldown-time", 15*time.Minute, "Time between updates of changed units.") pflag.StringVar(&config.MachineTag, "machine-tag", "", "The machine-tag to filter for.") pflag.StringVar(&config.UnitTemplate, "unit-template", "", "The template to render for new units. Prefix with @ to load from a file.") pflag.StringVar(&config.UnitPrefix, "unit-prefix", "", "The prefix for the units to identify.") pflag.StringVar(&glogFlags.logToStderr, "logtostderr", "true", "log to standard error instead of files") pflag.StringVar(&glogFlags.alsoLogToStderr, "alsologtostderr", "false", "log to standard error as well as files") pflag.StringVarP(&glogFlags.verbosity, "verbose", "v", "1", "log level for V logs") pflag.StringVar(&glogFlags.vmodule, "vmodule", "", "comma-separated list of pattern=N settings for file-filtered logging") pflag.StringVar(&glogFlags.logBacktraceAt, "log_backtrace_at", "", "when logging hits line file:N, emit a stack trace") }
// Initial setup when the program starts. func setup() { // ensure that zpool/zfs commands do not use localized messages: os.Setenv("LC_ALL", "C") // command line flags: pflag.StringVarP(&cfgFile, "conf", "c", CFGFILE, "configuration file path") pflag.BoolVarP(&optDebug, "debug", "d", false, "print debug information to stdout") optHashPassword := pflag.BoolP("passwordhash", "P", false, "hash web password") optTest := pflag.BoolP("test", "t", false, "test configuration and exit") optVersion := pflag.BoolP("version", "v", false, "print version information and exit") pflag.Parse() if pflag.NArg() > 0 { pflag.Usage() os.Exit(2) } if *optVersion { version() os.Exit(0) } if *optHashPassword { wwwHashPassword() os.Exit(0) } // initialize logging & notification: if *optTest { optDebug = true } cfg = getCfg() if cfg == nil { os.Exit(2) } notify = setupLog(cfg) if *optTest { notifyCloseC := notify.Close() select { // wait max 1 second for loggers to finish case <-notifyCloseC: case <-time.After(time.Second): } os.Exit(0) } }
func main() { var err error var cp string var initial bool var conferr error flag.StringVarP(&cp, "conf", "c", "conf.yml", "Local path to configuration file.") flag.BoolVarP(&initial, "initial", "i", false, "Run the initial setup of the server.") flag.Parse() conferr = conf.Load(cp) if conferr != nil || initial { setup.Run() } if err = utils.EnsureDir(conf.C.UploadDir); err != nil { log.Fatal(err) } if db, err = gorm.Open("sqlite3", conf.C.DB); err != nil { log.Fatal(err) } db.AutoMigrate(&models.ResourceEntry{}) go monitoring.Monit(&db) log.Printf("[INFO][System]\tStarted goploader server on port %d\n", conf.C.Port) if !conf.C.Debug { gin.SetMode(gin.ReleaseMode) } // Default router r := gin.Default() // Templates and static files r.LoadHTMLGlob("templates/*") r.Static("/static", "./assets") r.Static("/favicon.ico", "./assets/favicon.ico") // Routes r.GET("/", index) r.POST("/", create) r.GET("/v/:uniuri/:key", view) // Run r.Run(fmt.Sprintf(":%d", conf.C.Port)) }
func main() { var err error var cp string var initial bool var r *gin.Engine tbox, _ := rice.FindBox("templates") abox, _ := rice.FindBox("assets") flag.StringVarP(&cp, "conf", "c", "conf.yml", "Local path to configuration file.") flag.BoolVarP(&initial, "initial", "i", false, "Run the initial setup of the server.") flag.Parse() if err = conf.Load(cp, !initial); err != nil || initial { setup.Run() } if err = database.Initialize(); err != nil { log.Fatal(err) } defer database.DB.Close() if err = models.Initialize(); err != nil { log.Fatal(err) } go monitoring.Monit() if r, err = router.Setup(tbox, abox); err != nil { log.Fatal(err) } logger.Info("server", "Started goploader server on port", conf.C.Port) if conf.C.ServeHTTPS { if err = http.ListenAndServeTLS(fmt.Sprintf(":%d", conf.C.Port), conf.C.SSLCert, conf.C.SSLPrivKey, r); err != nil { logger.Err("server", "Fatal error", err) } } else { if err = r.Run(fmt.Sprintf(":%d", conf.C.Port)); err != nil { logger.Err("server", "Fatal error", err) } } }
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() { // environment can only override default address eaddr := os.Getenv("NCONFIGD_ETCD_ADDRESS") if eaddr == "" { eaddr = eaddress } logLevel := flag.StringP("log-level", "l", "warn", "log level") flag.StringVarP(&ansibleDir, "ansible", "a", ansibleDir, "directory containing the ansible run command") flag.StringP("etcd", "e", eaddress, "address of etcd server") configPath := flag.StringP("config", "c", "", "path to config file with prefixs") once := flag.BoolP("once", "o", false, "run only once and then exit") flag.Parse() flag.Visit(func(f *flag.Flag) { if f.Name == "etcd" { eaddr = f.Value.String() } }) // Set up logging if err := logx.DefaultSetup(*logLevel); err != nil { log.WithFields(log.Fields{ "error": err, "func": "logx.DefaultSetup", "level": *logLevel, }).Fatal("failed to set up logging") } // Load config containing prefixs to watch config, err := loadConfig(*configPath) if err != nil { log.WithFields(log.Fields{ "error": err, "configPath": *configPath, }).Fatal("failed to load config") } log.WithField("config", config).Info("config loaded") // set up etcd connection log.WithField("address", eaddr).Info("connection to etcd") etcdClient := etcd.NewClient([]string{eaddr}) // make sure we can actually connect to etcd if !etcdClient.SyncCluster() { log.WithFields(log.Fields{ "error": err, "address": eaddr, }).Fatal("failed to connect to etcd cluster") } // always run initially runAnsible(config, eaddr, "") if *once { return } // set up watcher w := watchKeys(config, etcdClient) // to coordinate clean exiting between the consumer and the signal handler ready := make(chan struct{}, 1) ready <- struct{}{} // handle events go consumeResponses(config, eaddr, w, ready) // handle signals for clean shutdown sigs := make(chan os.Signal) signal.Notify(sigs, os.Interrupt, syscall.SIGTERM) s := <-sigs log.WithField("signal", s).Info("signal received. waiting for current task to process") // wait until any current processing is finished <-ready _ = w.Close() log.Info("exiting") }
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 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{} 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.") }
/* * Queries the given table name and copies the column values to either an INSERT statement or * an UPDATE statement. * * Example: pgcp -U myuser -d mydb INSERT t_user "WHERE user_id < 4" */ func main() { var outputFileName string flag.StringVarP(&outputFileName, "output-file", "o", "", "Sends output to a file") dbInfo := pgutil.DbInfo{} verFlag, helpFlag := dbInfo.Populate() if verFlag { fmt.Fprintf(os.Stderr, "%s version %s\n", os.Args[0], version) fmt.Fprintln(os.Stderr, "Copyright (c) 2015 Jon Carlson. All rights reserved.") fmt.Fprintln(os.Stderr, "Use of this source code is governed by the MIT license") fmt.Fprintln(os.Stderr, "that can be found here: http://opensource.org/licenses/MIT") os.Exit(1) } if helpFlag { usage() } // Remaining args: args := flag.Args() if len(args) < 2 { fmt.Fprintln(os.Stderr, "Missing some arguments") usage() } // genType genType := strings.ToUpper(args[0]) if genType != "INSERT" && genType != "UPDATE" { fmt.Fprintf(os.Stderr, "Invalid generation type: %s. Requires either INSERT or UPDATE\n", genType) usage() } if len(outputFileName) > 0 { var err error out, err = os.Create(outputFileName) if err != nil { fmt.Fprintf(os.Stderr, "Cannot open file: %s. \n", outputFileName) fmt.Fprintln(os.Stderr, err) os.Exit(2) } } // tableName tableName := args[1] // idColumn (UPDATE only) and whereClause whereClause := "" idCol := "" if genType == "INSERT" { if len(args) > 2 { whereClause = args[2] } } else { if len(args) < 3 { fmt.Fprintf(os.Stderr, "UPDATE requires an idColumn.") usage() } idCol = args[2] if len(args) > 3 { whereClause = args[3] } } if len(whereClause) == 0 { // Make sure user intended there to be no where clause if !misc.PromptYesNo("Did you intend to have no where clause?", true) { os.Exit(1) } } db, err := dbInfo.Open() check("opening database", err) query := "SELECT * FROM " + tableName + " " + whereClause printf("-- Creating %s(s) from query: %s\n", genType, query) rowChan, columnNames := querySqlValues(db, query) for row := range rowChan { if genType == "INSERT" { generateInsert(tableName, row, columnNames) } else { generateUpdate(tableName, row, idCol) } } }
func main() { eaddr := "http://localhost:4001" hn := "" rules := "/etc/nftables.conf" flag.StringVarP(&eaddr, "etcd", "e", eaddr, "etcd cluster address") flag.StringVarP(&hn, "id", "i", hn, "hypervisor id") flag.StringVarP(&rules, "file", "f", rules, "nft configuration file") flag.Parse() rules = canonicalizeRules(rules) cleanStaleFiles(rules) e := etcd.NewClient([]string{eaddr}) c := ln.NewContext(e) hv := getHV(hn, e, c) watcher, err := watcher.New(e) if err != nil { log.WithFields(log.Fields{ "error": err, "func": "watcher.New", }).Fatal("failed to start watcher") } if err = watcher.Add("/lochness/guests"); err != nil { log.WithFields(log.Fields{ "error": err, "func": "watcher.Add", "prefix": "/lochness/guests", }).Fatal("failed to add prefix to watch list") } if err := watcher.Add("/lochness/fwgroups"); err != nil { log.WithFields(log.Fields{ "error": err, "func": "watcher.Add", "prefix": "/lochness/fwgroups", }).Fatal("failed to add prefix to watch list") } // load rules at startup td, err := genRules(hv, c) if err != nil { log.WithField("error", err).Fatal("could not load intial rules") } if err := applyRules(rules, td); err != nil { log.WithField("error", err).Fatal("could not apply intial rules") } for watcher.Next() { td, err := genRules(hv, c) if err != nil { continue } if err := applyRules(rules, td); err != nil { log.WithField("error", err).Fatal("could not apply rules") } } if err := watcher.Err(); err != nil { log.Fatal(err) } }
// 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 }
// Go runs the MailHog sendmail replacement. func Go() { smtpAddr := "localhost:1025" goflag := false for _, g := range os.Args[1:] { if strings.HasPrefix(g, "-") && !strings.HasPrefix(g, "--") { if strings.HasPrefix(g, "-from ") || strings.HasPrefix(g, "-from=") || strings.HasPrefix(g, "-smtp-addr ") || strings.HasPrefix(g, "-smtp-addr=") { goflag = true break } } } host, err := os.Hostname() if err != nil { host = "localhost" } username := "******" user, err := user.Current() if err == nil && user != nil && len(user.Username) > 0 { username = user.Username } fromAddr := username + "@" + host var recip []string if goflag { flag.StringVar(&smtpAddr, "smtp-addr", smtpAddr, "SMTP server address") flag.StringVar(&fromAddr, "from", fromAddr, "SMTP sender") flag.Parse() recip = flag.Args() } else { pflag.StringVar(&smtpAddr, "smtp-addr", smtpAddr, "SMTP server address") pflag.StringVarP(&fromAddr, "from", "f", fromAddr, "SMTP sender") pflag.Parse() recip = pflag.Args() } body, err := ioutil.ReadAll(os.Stdin) if err != nil { fmt.Fprintln(os.Stderr, "error reading stdin") os.Exit(11) } msg, err := mail.ReadMessage(bytes.NewReader(body)) if err != nil { fmt.Fprintln(os.Stderr, "error parsing message body") os.Exit(11) } if len(recip) == 0 { // We only need to parse the message to get a recipient if none where // provided on the command line. recip = append(recip, msg.Header.Get("To")) } err = smtp.SendMail(smtpAddr, nil, fromAddr, recip, body) if err != nil { fmt.Fprintln(os.Stderr, "error sending mail") log.Fatal(err) } }
// Go runs the MailHog sendmail replacement. func Go() { smtpAddr := "localhost:1025" goflag := false for _, g := range os.Args[1:] { if strings.HasPrefix(g, "-") && !strings.HasPrefix(g, "--") { if strings.HasPrefix(g, "-from ") || strings.HasPrefix(g, "-from=") || strings.HasPrefix(g, "-smtp-addr ") || strings.HasPrefix(g, "-smtp-addr=") { goflag = true break } } } host, err := os.Hostname() if err != nil { host = "localhost" } username := "******" user, err := user.Current() if err == nil && user != nil && len(user.Username) > 0 { username = user.Username } fromAddr := username + "@" + host var recip []string if goflag { flag.StringVar(&smtpAddr, "smtp-addr", smtpAddr, "SMTP server address") flag.StringVar(&fromAddr, "from", fromAddr, "SMTP sender") flag.Parse() recip = flag.Args() } else { pflag.StringVar(&smtpAddr, "smtp-addr", smtpAddr, "SMTP server address") pflag.StringVarP(&fromAddr, "from", "f", fromAddr, "SMTP sender") pflag.Parse() recip = pflag.Args() } body, err := ioutil.ReadAll(os.Stdin) if err != nil { fmt.Fprintln(os.Stderr, "error reading stdin") os.Exit(11) } if len(recip) == 0 { // We only need to parse the message to get a recipient if none where // provided on the command line. // re := regexp.MustCompile("(?im)^To: (.*)\r*\n$") re := regexp.MustCompile("(?im)^To: (.*)\r*$") n := bytes.IndexByte(body, 0) var bodyStr string if n < 0 { bodyStr = string(body) } else { bodyStr = string(body[:n]) } includedRecip := re.FindAllString(bodyStr, -1) if includedRecip == nil { fmt.Fprintln(os.Stderr, "missing recipient") os.Exit(10) } newRecip := make([]string, len(recip), len(recip)+len(includedRecip)) copy(newRecip, recip) recip = append(newRecip, includedRecip...) } err = smtp.SendMail(smtpAddr, nil, fromAddr, recip, body) if err != nil { fmt.Fprintln(os.Stderr, "error sending mail") log.Fatal(err) } }
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) } }