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)) } }
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() { 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) } } } }
func main() { dir, _ := os.Getwd() port := flag.IntP("port", "p", 8080, "help message for flagname") flag.Parse() if flag.NArg() > 1 { flag.Usage() os.Exit(1) } else if flag.NArg() == 1 { dir = flag.Args()[0] } bindTo := fmt.Sprintf(":%d", *port) fmt.Printf("Serving '%s' on %s...\n", dir, bindTo) panic(http.ListenAndServe(bindTo, http.FileServer(http.Dir(dir)))) }
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, })) }
// 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() { 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() { 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 init() { flag.Usage = func() { fmt.Fprintln(os.Stderr, "Usage: chanloader [options] /b/res/123456\nOptions:") flag.PrintDefaults() } flag.Parse() if *refresh < time.Second*30 { *refresh = time.Second * 30 } if *showVersion { fmt.Println(version) os.Exit(0) } if flag.NArg() < 1 { flag.Usage() os.Exit(1) } runtime.GOMAXPROCS(runtime.NumCPU()) }
func 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() { var ok int // return status outHandle := syscall.Handle(os.Stdout.Fd()) outType, err := syscall.GetFileType(outHandle) if err != nil { fatal.Fatalln(err) } outBsize := 4096 // catch (./cat) < /etc/group var args []string if flag.NArg() == 0 { args = []string{"-"} } else { args = flag.Args() } // the main loop var file *os.File for _, arg := range args { var inStat os.FileInfo if arg == "-" { file = os.Stdin } else { file, err = os.Open(arg) if err != nil { fatal.Fatalln(err) } inStat, err = file.Stat() if err != nil { fatal.Fatalln(err) } if inStat.IsDir() { fatal.Printf("%s: Is a directory\n", file.Name()) } } inHandle := syscall.Handle(file.Fd()) inBsize := 4096 // See http://stackoverflow.com/q/29360969/2967113 // for why this differs from the Unix versions. // // Make sure we're not catting a file to itself, // provided it's a regular file. Catting a non-reg // file to itself is cool, e.g. cat file > file if outType == syscall.FILE_TYPE_DISK { inPath := make([]byte, syscall.MAX_PATH) outPath := make([]byte, syscall.MAX_PATH) err = k32.GetFinalPathNameByHandleA(inHandle, inPath, 0) if err != nil { fatal.Fatalln(err) } err = k32.GetFinalPathNameByHandleA(outHandle, outPath, 0) if err != nil { fatal.Fatalln(err) } if string(inPath) == string(outPath) { if n, _ := file.Seek(0, os.SEEK_CUR); n < inStat.Size() { fatal.Fatalf("%s: input file is output file\n", file.Name()) } } } if simple { outBuf := bufio.NewWriterSize(os.Stdout, 4096) ok ^= simpleCat(file, outBuf) // Flush because we don't have a chance to in // simpleCat() because we use io.Copy() outBuf.Flush() } else { // If you want to know why, exactly, I chose // outBsize -1 + inBsize*4 + 20, read GNU's cat // source code. The tl;dr is the 20 is the counter // buffer, inBsize*4 is from potentially prepending // the control characters (M-^), and outBsize is // due to new tests for newlines. size := outBsize - 1 + inBsize*4 + 20 outBuf := bufio.NewWriterSize(os.Stdout, size) inBuf := make([]byte, inBsize+1) ok ^= cat(file, inBuf, outBuf) } file.Close() } os.Exit(ok) }
func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s", Help) os.Exit(1) } flag.Parse() if *constVersion { fmt.Printf("Unicode Version: %s\n", unicode.Version) os.Exit(0) } else if *version { fmt.Printf("%s\n", Version) os.Exit(0) } if !(*printBytes || *printChars || *printLines || *printWords || *printLineLength) { *printLines = true *printBytes = true *printWords = true } // This is a gross attempt to simulate this... // (print_lines + print_words + print_chars + // print_bytes + print_linelength) == 1 // // Since Go can't add booleans (e.g. false + true == 1) // and checking that *only* one of 5 bool variables would be sloppy, // we check the number of set flags and the remaining non-'print' flags // which is a much smaller set of conditions to check // // 1 flag and it's --files0-from if (flag.NFlag() == 1 && *filesFrom == "" && *tabWidth == 8) || // 2 flags and one's *filesFrom OR *tabWidth (flag.NFlag() == 2 && (*filesFrom != "" || *tabWidth != 8)) || // 3 flags and two are *filesFrom AND *tabWidth (flag.NFlag() == 3 && *filesFrom != "" && *tabWidth != 8) { printOne = true } var ( ok = 0 // Return status. files = flag.Args() // List of files. numFiles = len(files) // Number of files to wc. reasonable = true // Can we read file list into memory? stdin = true // Are we reading from stdin? size int64 ) if *filesFrom != "" { // Cannot specify files with --files0-from. if flag.NArg() > 0 { fatal.Fatalln("file operands cannot be combined with --files0-from") } // --files0-from is small enough to fit into RAM. if reasonable, size = isReasonable(*filesFrom); reasonable { files, numFiles = getFileList(*filesFrom, size) stdin = false } } fs := getFileStatus(numFiles, files) numberWidth = findNumberWidth(numFiles, fs) if !reasonable { var ( file *os.File err error ) file = os.Stdin if *filesFrom != "-" { file, err = os.Open(*filesFrom) } if err != nil { fatal.Fatalf("cannot open: %s\n", *filesFrom) } defer file.Close() r := bufio.NewReader(file) i := 0 for { fname, err := r.ReadString(NullByte) if err != nil { if err != io.EOF && i < 1 { fatal.Fatalln(err) } break } if len(fname) > 1 { // Trim trailing null-byte. if fname[len(fname)-1] == NullByte { fname = fname[:len(fname)-1] } } else { log.Fatalf("invalid zero-length file name at position: %d\n", i) } ok ^= wcFile(fname, nil) i++ } numFiles = i } else { if stdin { // We're reading from Stdin. ok ^= wcFile("", fs[0]) } else { for i, v := range files { ok ^= wcFile(v, fs[i]) } } } if numFiles > 1 { writeCounts(totalLines, totalWords, totalChars, totalBytes, maxLineLength, "total") } // Return status. os.Exit(ok) }
func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s\n", HELP) return } flag.Parse() if *version { fmt.Printf("%s\n", VERSION) return } o := &Options{ AsRegular: true, Dereference: derefUndefined, } if *sparse != "界" { if v := argmatch(*sparse, sparseArgList); v >= 0 { o.SparseMode = v } else { log.Fatalf("invalid agument %s\n", *sparse) } } if *reflink != "世" { if *reflink == "" { o.RefLinkMode = reflinkAlways } else { if v := argmatch(*reflink, reflinkArgList); v >= 0 { o.RefLinkMode = v } else { log.Fatalf("invalid agument %s\n", *reflink) } } } if *archive { o.Dereference = derefNever o.PreserveLinks = true o.PreserveOwnership = true o.PreserveMode = true o.PreserveTimestamps = true o.RequirePreserve = true //if selinux is enabled o.PreserveSecurity = true log.Println("unable to preserve security context at the moment") o.PreserveXattr = true o.ReduceDiagnostics = true o.Recursive = true } if *backup != "" || *backup2 { makeBackups = true if *backup != "" { versControl = *backup } } if *attrOnly { o.DataCopyRequired = false } if *copyContents { copyConts = true } if *ndrpl { o.PreserveLinks = true o.Dereference = derefNever } if *force { o.UnlinkAfterFailed = true } if *hopt { o.Dereference = derefArgs } if *interactive { o.Interactive = alwaysAsk } if *link { o.HardLink = true } if *dereference { o.Dereference = derefAlways } if *noClobber { o.Interactive = alwaysNo } if *noDereference { o.Dereference = derefNever } if *noPreserve != "" { o.decodePreserve(noPreserve, false) } if *preserve == "" && *pmot { o.PreserveOwnership = true o.PreserveMode = true o.PreserveTimestamps = true o.RequirePreserve = true } else if *preserve != "" { o.decodePreserve(preserve, true) } if *pmot { o.PreserveOwnership = true o.PreserveMode = true o.PreserveTimestamps = true o.RequirePreserve = true } if *parents { parentsOpt = true } if *recursive || *recursive2 { o.Recursive = true } if *removeDestination { o.UnlinkBefore = true } if *stripTrailSlash { removeTrailSlash = true } if *symLink { o.SymbolicLink = true } if *targetDir != "" { if s, err := os.Stat(*targetDir); err != nil { log.Fatalf("failed to acces %s\n", *targetDir) } else { if !s.Mode().IsDir() { log.Fatalf("target %s is not a directory\n", *targetDir) } targDir = *targetDir } } if *noTargetDir { noTargDir = true } if *update { o.Update = true } if *verbose { o.Verbose = true } if *oneFS { o.OneFS = true } if *selinux { log.Fatalln("no current way to detect SELinux yet, sorry") } if *suffix != "" { makeBackups = true suffixString = *suffix } if o.HardLink && o.SymbolicLink { log.Fatal("cannot make both hard and symbolic links") } if makeBackups && o.Interactive == alwaysNo { log.Fatalln("options --backup and --no-clobber are mutually exclusive") } if o.RefLinkMode == reflinkAlways && o.SparseMode != sparseAuto { log.Fatalln("--reflink can only be used with --sparse=auto") } if suffixString != "" { if makeBackups { o.BackupOpts = getVersion(versControl) } else { o.BackupOpts = noBackups } } if o.Dereference == derefUndefined { if o.Recursive && !o.HardLink { o.Dereference = derefNever } else { o.Dereference = derefAlways } } if o.Recursive { o.AsRegular = copyConts } if o.UnlinkAfterFailed && (o.HardLink || o.SymbolicLink) { o.UnlinkBefore = true } if cp(flag.NArg()-1, flag.Args(), targDir, noTargDir, o) { return } os.Exit(1) }
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() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s", Help) os.Exit(0) } flag.Parse() p := profile.Start(profile.CPUProfile) if *constVersion { fmt.Printf("Unicode Version: %s\n", unicode.Version) os.Exit(0) } if *version { fmt.Printf("%s\n", Version) os.Exit(0) } if !(*printBytes || *printChars || *printLines || *printWords || *printLineLength) { *printLines = true *printBytes = true *printWords = true } // This is a gross attempt to simulate this... // (print_lines + print_words + print_chars + // print_bytes + print_linelength) == 1 // // Since Go can't add booleans (e.g. false + true == 1) // and checking that *only* one of 5 bool variables would be sloppy, // we check the number of set flags and the remaining non-'print' flags // which is a much smaller set of conditions to check // // I could just use a loop, but this also removes a branch soooo... printOne = // 1 flag and it's not *filesFrom OR *tabWidth ((flag.NFlag() == 1 && *filesFrom == "" && *tabWidth == 8) || // 2 flags and one is *filesFrom OR *tabWidth (flag.NFlag() == 2 && (*filesFrom != "" || *tabWidth != 8)) || // 3 flags and two are *filesFrom AND *tabWidth (flag.NFlag() == 3 && *filesFrom != "" && *tabWidth != 8)) var ( ok int // Return status. files = flag.Args() // List of files. numFiles = len(files) // Number of files to wc. reasonable = true // Can we read file list into memory? size int64 ) if *filesFrom != "" { // Cannot specify files with --files0-from. if flag.NArg() > 0 { fatal("file operands cannot be combined with --files0-from") } // --files0-from is small enough to fit into RAM. if reasonable, size = isReasonable(*filesFrom); reasonable { files, numFiles = getFileList(*filesFrom, size) } } fs := getFileStatus(files) numberWidth = findNumberWidth(fs) if reasonable { for i, file := range files { ok ^= wcFile(file, fs[i]) } } else { var err error file := os.Stdin if *filesFrom != "-" { file, err = os.Open(*filesFrom) } if err != nil { fatal("cannot open %q for reading: No such file or directory", *filesFrom) } defer file.Close() s := bufio.NewScanner(file) s.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) { if atEOF && len(data) == 0 { return 0, nil, nil } if i := bytes.IndexByte(data, NullByte); i >= 0 { // We have a full newline-terminated line. return i + 1, dropNullByte(numFiles, data[0:i]), nil } // If we're at EOF, we have a final, non-terminated line. Return it. if atEOF { return len(data), dropNullByte(numFiles, data), nil } // Request more data. return 0, nil, nil }) for ; s.Scan(); numFiles++ { ok ^= wcFile(s.Text(), fstatus{}) } if err := s.Err(); err != nil { fatal("%v", err) } } if numFiles > 1 { writeCounts(totalLines, totalWords, totalChars, totalBytes, maxLineLength, "total") } p.Stop() // Return status. os.Exit(ok) }
func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s", Help) os.Exit(1) } flag.Parse() if *constVersion { fmt.Printf("Unicode Version: %s\n", unicode.Version) os.Exit(0) } else if *version { fmt.Printf("%s\n", Version) os.Exit(0) } if !(*printBytes || *printChars || *printLines || *printWords || *printLineLength) { *printLines = true *printBytes = true *printWords = true } // This is a gross attempt to simulate this... // (print_lines + print_words + print_chars + // print_bytes + print_linelength) == 1 // // Since Go can't add booleans (e.g. false + true == 1) // and checking that *only* one of 5 bool variables would be sloppy, // we check the number of set flags and the remaining non-'print' flags // which is a much smaller set of conditions to check // // 1 flag and it's --files0-from if (flag.NFlag() == 1 && *filesFrom == "" && *tabWidth == 8) || // 2 flags and one's *filesFrom OR *tabWidth (flag.NFlag() == 2 && (*filesFrom != "" || *tabWidth != 8)) || // 3 flags and two are *filesFrom AND *tabWidth (flag.NFlag() == 3 && *filesFrom != "" && *tabWidth != 8) { printOne = true } var ( ok = 0 // dictates return status total bool // print totals? files = flag.Args() // list of files numFiles = len(files) // number of files to wc() reasonable = true // can we read file list into memory? ) if *filesFrom != "" { // cannot specify files with --files0-from if flag.NArg() > 0 { fatal.Fatalln("file operands cannot be combined with --files0-from") } // is small enough to fit into RAM if good, stat := isReasonable(*filesFrom); good { reasonable = true files = getFileList(*filesFrom, stat) numFiles = len(files) if numFiles == 0 { fatal.Fatalln("--files0-from contained no usable files") } } else { reasonable = false } // stdin } else if numFiles == 0 { files = nil numFiles = 1 } fs := getFileStatus(numFiles, files) numberWidth = findNumberWidth(numFiles, fs) if !reasonable { var ( fi *os.File err error ) if *filesFrom == "-" { fi = os.Stdin } else { fi, err = os.Open(*filesFrom) } if err != nil { fatal.Fatalf("cannot open: %s", *filesFrom) } defer fi.Close() r := bufio.NewReader(fi) i := 0 for { fname, err := r.ReadString(NullByte) if err != nil { if err == io.EOF { if i > 0 { break } } else { fatal.Fatalln(err) } } if len(fname) > 1 { // \0 if fname[len(fname)-1] == NullByte { fname = fname[:len(fname)-1] } } ok ^= wcFile(fname, nil) i++ } if i > 1 { total = true } } else { // stdin if files == nil { ok ^= wcFile("", fs[0]) } else { for i, v := range files { ok ^= wcFile(v, fs[i]) } } } if numFiles > 1 { total = true } if total { writeCounts(totalLines, totalWords, totalChars, totalBytes, maxLineLength, "total") } // return status os.Exit(ok) }
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) } var ( ok int // return status simple bool // no non-printing ) // -vET if *all { *nonPrint = true *npTabs = true *npEnds = true } if *npEnds { *ends = true } if *blank { *number = true } if *npTabs { *tabs = true } if *all || *npEnds || *npTabs || *nonPrint { showNonPrinting = true } outStat, err := os.Stdout.Stat() if err != nil { fatal.Fatalln(err) } outReg := outStat.Mode().IsRegular() outBsize := int(outStat.Sys().(*syscall.Stat_t).Blksize) // catch (./cat) < /etc/group var args []string if flag.NArg() == 0 { args = []string{"-"} } else { args = flag.Args() } // the main loop var file *os.File for _, arg := range args { if arg == "-" { file = os.Stdin } else { file, err = os.Open(arg) if err != nil { fatal.Fatalln(err) } } inStat, err := file.Stat() if err != nil { fatal.Fatalln(err) } if inStat.IsDir() { fatal.Printf("%s: Is a directory\n", file.Name()) } inBsize := int(inStat.Sys().(*syscall.Stat_t).Blksize) // prefetch! prefetch! prefetch! unix.Fadvise(int(file.Fd()), 0, 0, unix.FADV_SEQUENTIAL) // Make sure we're not catting a file to itself, // provided it's a regular file. Catting a non-reg // file to itself is cool. // e.g. cat file > file if outReg && os.SameFile(outStat, inStat) { if n, _ := file.Seek(0, os.SEEK_CUR); n < inStat.Size() { fatal.Fatalf("%s: input file is output file\n", file.Name()) } } if simple { // Select larger block size size := max(inBsize, outBsize) outBuf := bufio.NewWriterSize(os.Stdout, size) ok ^= simpleCat(file, outBuf) // Flush because we don't have a chance to in // simpleCat() because we use io.Copy() outBuf.Flush() } else { // If you want to know why, exactly, I chose // outBsize -1 + inBsize*4 + 20, read GNU's cat // source code. The tl;dr is the 20 is the counter // buffer, inBsize*4 is from potentially prepending // the control characters (M-^), and outBsize is // due to new tests for newlines. size := outBsize - 1 + inBsize*4 + 20 outBuf := bufio.NewWriterSize(os.Stdout, size) inBuf := make([]byte, inBsize+1) ok ^= cat(file, inBuf, outBuf) } file.Close() } os.Exit(ok) }
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) }