Beispiel #1
0
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)
	}
}
Beispiel #2
0
func main() {
	flag.Parse()

	switch {
	case *multiple != "":
		// ugly things about to happen...
		if flag.NArg() > 0 { // means it's using -a
			fmt.Print(performBasename(*multiple, *suffix, *zero)) // pick first from -a

			for _, v := range flag.Args() { // the rest...
				fmt.Print(performBasename(v, *suffix, *zero))
			}

		} else { // means it's using --multiple, split em all
			for _, v := range strings.Split(*multiple, " ") {
				fmt.Print(performBasename(v, *suffix, *zero))
			}
		}
	case *suffix != "": //implies -a
		fmt.Print(performBasename(flag.Args()[0], *suffix, *zero))
	default:
		name := flag.Args()[0]
		suffix := ""
		if flag.NArg() == 2 {
			suffix = flag.Args()[1]
		}
		fmt.Print(performBasename(name, suffix, *zero))
	}

}
Beispiel #3
0
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
}
Beispiel #4
0
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)
	}
}
Beispiel #5
0
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)
				}
			}
		}
	}
}
Beispiel #6
0
func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "%s", Help)
		os.Exit(1)
	}
	flag.Parse()

	switch {
	case *version:
		fmt.Fprintf(os.Stdout, "%s", Version)
		os.Exit(0)
	case *wrap < 0:
		log.Fatalf("invalid wrap size: %d", *wrap)
	default:
		if len(flag.Args()) == 0 {
			readAndHandle(os.Stdin, decode, ignore, wrap)
		} else {
			for i := 0; i < len(flag.Args()); i++ {
				file, err := os.Open(flag.Args()[i])
				if err != nil {
					log.Fatal(err)
				}
				readAndHandle(file, decode, ignore, wrap)
			}
		}
	}

}
Beispiel #7
0
/*
   check the md5sum for all of files from cmdline
*/
func check_md5sum() bool {
	if len(flag.Args()) == 0 ||
		(len(flag.Args()) == 1 && flag.Args()[0] == "-") {

		/* Known Issue:
		   Ctrl+Z on cmd can not trigger io.EOF */
		return check_md5sum_f(os.Stdin)
	}

	has_err := false

	for i := 0; i < len(flag.Args()); i++ {
		//output_e("use file: %s\n", flag.Args()[i])
		file, err := os.Open(flag.Args()[i])
		if err != nil {
			output_e("md5sum: %s\n", err.Error())
			has_err = true
			continue
		}
		if b := check_md5sum_f(file); !b {
			has_err = true
		}
		file.Close()
	}

	return !has_err
}
Beispiel #8
0
func main() {
	flag.Parse()
	if len(flag.Args()) == 0 {
		log.Fatal("need query")
	}
	args := flag.Args()
	if !*retweets {
		args = append(args, "-rt")
	}
	search := url.QueryEscape(strings.Join(args, " "))
	query := fmt.Sprintf("%s?q=%s&count=%d", twSearchBase, search, *resnum)
	for {
		tw, err := twitquery(query)
		if err != nil {
			log.Fatal(err)
		}
		r := tw.Statuses
		for i := range r {
			if *reverse {
				fmt.Println(r[i])
			} else {
				fmt.Println(r[len(r)-i-1])
			}
		}
		if !*follow { // if not in follow mode we are done
			break
		}
		query = twSearchBase + tw.Meta.RefreshUrl
		time.Sleep(*followDelay)
	}
}
Beispiel #9
0
func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "%s", Help)
		os.Exit(1)
	}
	flag.Parse()

	switch {
	case *version:
		fmt.Fprintf(os.Stdout, "%s", Version)
		os.Exit(0)
	case *multiple:
		for _, v := range flag.Args() {
			dir := baseName(v, *suffix, *zero)
			fmt.Print(dir)
		}
	case *suffix != "":
		// Implies --multiple/-a
		for _, v := range flag.Args() {
			dir := baseName(v, *suffix, *zero)
			fmt.Print(dir)
		}
	default:
		dir := baseName(flag.Args()[0], *suffix, *zero)
		fmt.Print(dir)
	}
}
Beispiel #10
0
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
}
Beispiel #11
0
// The following command `remotectl -profile test.sh -list` would result in
// len(args) <= i returning false.
func parseArgs(args []string) (query, cmd string) {
	i := flag.NFlag() + 1

	cmd = strings.Join(flag.Args(), " ")

	if len(args) > i && args[i] != "--" {
		query = flag.Args()[0]
		cmd = strings.Join(flag.Args()[1:], " ")
	}

	return query, cmd
}
Beispiel #12
0
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)
	}
}
Beispiel #13
0
// Parse the command from the command line
func ParseCommand() (*Command, []string) {
	args := pflag.Args()
	if len(args) < 1 {
		fatal("No command supplied\n")
	}

	cmd := strings.ToLower(args[0])
	args = args[1:]

	// Find the command doing a prefix match
	var command *Command
	for i := range Commands {
		trialCommand := &Commands[i]
		// exact command name found - use that
		if trialCommand.Name == cmd {
			command = trialCommand
			break
		} else if strings.HasPrefix(trialCommand.Name, cmd) {
			if command != nil {
				fs.Stats.Error()
				log.Fatalf("Not unique - matches multiple commands %q", cmd)
			}
			command = trialCommand
		}
	}
	if command == nil {
		fs.Stats.Error()
		log.Fatalf("Unknown command %q", cmd)
	}
	if command.Run == nil {
		syntaxError()
	}
	command.checkArgs(args)
	return command, args
}
Beispiel #14
0
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)
	}

	args := flag.Args()
	if flag.NArg() == 0 {
		args = []string{"y"}
	}

	for {
		for i, arg := range args {
			os.Stdout.WriteString(arg)

			if i == len(args)-1 {
				os.Stdout.Write(LineFeed)
			} else {
				os.Stdout.Write(Space)
			}
		}
	}
}
Beispiel #15
0
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
}
Beispiel #16
0
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)
		}
	}
}
Beispiel #17
0
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")
	}
}
Beispiel #18
0
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)
	}

}
Beispiel #19
0
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()
}
Beispiel #20
0
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)
	}
}
Beispiel #21
0
func calculate(s *Stats) {
	if len(flag.Args()) == 0 {
		parse("<stdin>", os.Stdin, s)
	}

	for _, filename := range flag.Args() {
		if filename == "-" {
			parse("<stdin>", os.Stdin, s)
			continue
		}
		file, err := os.Open(filename)
		if err != nil {
			fail("%s\n", err.Error())
		}
		parse(filename, file, s)
	}
}
Beispiel #22
0
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)
	}
}
Beispiel #23
0
func main() {
	flag.Parse()

	if len(flag.Args()) < 1 {
		flag.Usage()
		os.Exit(-1)
	}

	config = NewConfig(flag.Args()[0])

	r := mux.NewRouter()
	r.HandleFunc("/lambda", lambdaHandler)
	r.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("OK"))
	})

	loggedRouter := handlers.LoggingHandler(os.Stdout, r)

	log.Fatal(http.ListenAndServe(":8080", loggedRouter))
}
Beispiel #24
0
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])
				}
			}
		}
	}
}
Beispiel #25
0
/*
   generate the md5sum for all of files from cmdline
*/
func gen_md5sum() bool {
	if len(flag.Args()) == 0 ||
		(len(flag.Args()) == 1 && flag.Args()[0] == "-") {

		/* Known Issue:
		   Ctrl+Z on cmd can not trigger io.EOF */
		sum := calc_md5sum(os.Stdin)

		fmt.Fprintf(os.Stdout, "%s *%s\n", sum, "-")
		return true
	}

	has_error := false

	for i := 0; i < len(flag.Args()); i++ {
		fn := flag.Args()[i]

		/* extends file lists when filename contains '*' */
		filenames, _ := filepath.Glob(fn)
		if filenames == nil {
			filenames = append(filenames, fn)
		}

		for _, f := range filenames {
			file, err := os.Open(f)
			if err != nil {
				has_error = true
				fmt.Fprintf(os.Stderr, "md5sum: %s\n", err.Error())
				continue
			}
			sum := calc_md5sum(file)
			file.Close()
			if sum != "" {
				has_error = true
				fmt.Fprintf(os.Stdout, "%s *%s\n", sum, f)
			}
		}
	}

	return !has_error
}
Beispiel #26
0
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)
					}
				}
			}
		}
	}
}
Beispiel #27
0
func main() {
	flag.Parse()

	for _, fname := range flag.Args() {
		if flagVerbose {
			log.Println("Checking file:", fname)
		}

		if err := check(fname); err != nil {
			log.Printf("Error checking file:", err)
		}
	}
}
Beispiel #28
0
func main() {

	cfg, err := ReadConfig()
	if err != nil {
		log.Fatalf("Coult not read config: %v", err)
	}

	pflag.Usage = func() {
		fmt.Fprintln(os.Stderr, "Usage: slackcat [-c #channel] [-n name] [message]")
	}

	channel := pflag.StringP("channel", "c", cfg.Channel, "channel")
	name := pflag.StringP("name", "n", username(), "name")
	pflag.Parse()

	// was there a message on the command line? If so use it.
	args := pflag.Args()
	if len(args) > 0 {
		msg := SlackMsg{
			Channel:  *channel,
			Username: *name,
			Parse:    "full",
			Text:     strings.Join(args, " "),
		}

		err = msg.Post(cfg.WebhookUrl)
		if err != nil {
			log.Fatalf("Post failed: %v", err)
		}
		os.Exit(0)
	}

	// ...Otherwise scan stdin
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		msg := SlackMsg{
			Channel:  *channel,
			Username: *name,
			Parse:    "full",
			Text:     scanner.Text(),
		}

		err = msg.Post(cfg.WebhookUrl)
		if err != nil {
			log.Fatalf("Post failed: %v", err)
		}
	}
	if err := scanner.Err(); err != nil {
		log.Fatalf("Error reading: %v", err)
	}
}
Beispiel #29
0
func main() {
	flagAppend := flag.BoolP("append", "a", false, "append to file")
	flag.Parse()
	bytes, _ := ioutil.ReadAll(os.Stdin)
	for i := 0; i < len(flag.Args()); i++ {
		if *flagAppend {
			f, err := os.OpenFile(flag.Args()[i], os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
			if err != nil {
				log.Fatal(err)
			}
			f.Write(bytes)
			f.Close()
		} else {
			f, err := os.OpenFile(flag.Args()[i], os.O_WRONLY|os.O_CREATE, 0644)
			if err != nil {
				log.Fatal(err)
			}
			f.Write(bytes)
			f.Close()
		}
	}
	fmt.Printf("%s", string(bytes))
}
Beispiel #30
0
func main() {
	pflag.Usage = func() {
		fmt.Fprintln(os.Stderr, "Usage: hipcat [-r room] [message]")
	}

	cfg := Config{}
	err := cfg.Load()
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}
	cfg.bindFlags()
	pflag.Parse()

	if cfg.Room == "" {
		log.Println("Could not find a Room in HIPCAT_ROOM, /etc/hipcat.conf, /.hipcat.conf, ./hipcat.conf or passed with -r")
		pflag.Usage()
		os.Exit(1)
	}
	// was there a message on the command line? If so use it.
	args := pflag.Args()
	if len(args) > 0 {
		msg := RoomMessage{
			Message: strings.Join(args, " "),
		}

		err = msg.Post(&cfg)
		if err != nil {
			log.Fatalf("Post failed: %v", err)
		}
		return
	}

	// ...Otherwise scan stdin
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		msg := RoomMessage{
			Message: scanner.Text(),
		}

		err = msg.Post(&cfg)
		if err != nil {
			log.Fatalf("Post failed: %v", err)
		}
	}
	if err = scanner.Err(); err != nil {
		log.Fatalf("Error reading: %v", err)
	}
}