コード例 #1
0
ファイル: sleep.go プロジェクト: rafkhan/coreutils
func main() {
	goopt.Suite = "XQZ coreutils"
	goopt.Author = "Aaron Muir Hamilton"
	goopt.Version = "Sleep v0.1"
	goopt.Summary = "Waits for a duration before continuing."
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage of %s:\n\t   %s STRING\n\tor %s OPTION\n", os.Args[0], os.Args[0], os.Args[0]) +
			goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless an option is passed to it."
	}
	goopt.NoArg([]string{"-v", "--version"}, "outputs version information and exits", version)
	goopt.Parse(nil)
	duration, err := time.ParseDuration(os.Args[1])
	if err != nil {
		number, interr := strconv.ParseFloat(os.Args[1], 64)
		if interr != nil {
			fmt.Println(err)
			os.Exit(0)
		}
		duration := time.Duration(number) * time.Second
		time.Sleep(duration)
		os.Exit(0)
	}
	time.Sleep(duration)
}
コード例 #2
0
ファイル: main.go プロジェクト: jorik041/buckler
func usage() string {
	u := `Usage: %s [-h HOST] [-p PORT]
       %s [-v VENDOR -s STATUS -c COLOR] <FILENAME>

%s`
	return fmt.Sprintf(u, os.Args[0], os.Args[0], goopt.Help())
}
コード例 #3
0
ファイル: main.go プロジェクト: uiri/coreutils
func main() {
	atime = time.Now()
	mtime = time.Now()
	goopt.Author = "William Pearson"
	goopt.Version = "Touch"
	goopt.Summary = "Change access or modification time of each FILE"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... FILE...\n", os.Args[0]) +
			goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	access := goopt.Flag([]string{"-a"}, nil, "Only change access time", "")
	modify := goopt.Flag([]string{"-m"}, nil, "Only change modification time", "")
	create := goopt.Flag([]string{"-c"}, nil, "Only change modification time", "")
	Nodereference = goopt.Flag([]string{"-h", "--no-dereference"}, []string{"--derference"}, "Affect symbolic links directly instead of dereferencing them", "Dereference symbolic links before operating on them (This is default)")
	goopt.OptArg([]string{"-r", "--reference"}, "RFILE", "Use RFILE's owner and group", fromReference)
	goopt.OptArg([]string{"-t"}, "STAMP", "Use [[CC]YY]MMDDhhmm[.ss] instead of now. Note hh is interpreted as from 00 to 23", fromStamp)
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	coreutils.Noderef = *Nodereference
	if len(goopt.Args) == 0 {
		coreutils.PrintUsage()
	}
	if !*access && !*modify {
		*access, *modify = true, true
	}
	for i := range goopt.Args {
		if !*access {
			atime, _ = GetAtimeMtime(goopt.Args[i], *Nodereference)
		}
		if !*modify {
			_, mtime = GetAtimeMtime(goopt.Args[i], *Nodereference)
		}
		if err := os.Chtimes(goopt.Args[i], atime, mtime); err != nil {
			if os.IsNotExist(err) {
				var err error
				if !*create {
					f, err := os.Create(goopt.Args[i])
					if err == nil {
						f.Close()
					}
				}
				if err == nil {
					continue
				}
			}
			fmt.Fprintf(os.Stderr, "Error touching file '%s': %v\n", goopt.Args[i], err)
		}
	}
	return
}
コード例 #4
0
ファイル: goreplace.go プロジェクト: vsolovyov/goreplace
func main() {
	goopt.Author = Author
	goopt.Version = Version
	goopt.Summary = Summary
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage of goreplace %s:\n\t", Version) +
			goopt.Summary + "\n" + goopt.Help()
	}

	var noIgnores bool
	for _, item := range os.Args[1:] {
		if item == "-I" || item == "--no-autoignore" {
			noIgnores = true
		}
	}

	cwd, _ := os.Getwd()
	ignorer := NewIgnorer(cwd, noIgnores)
	goopt.Summary += fmt.Sprintf("\n%s", ignorer)

	goopt.Parse(nil)


	if *showVersion {
		fmt.Printf("goreplace %s\n", goopt.Version)
		return
	}

	ignorer.Append(*ignoreFiles)

	if len(goopt.Args) == 0 {
		println(goopt.Usage())
		return
	}

	arg := goopt.Args[0]
	if *plaintext {
		arg = escapeRegex(arg)
	}
	if *ignoreCase {
		arg = "(?i:" + arg + ")"
	}

	pattern, err := regexp.Compile(arg)
	errhandle(err, true, "")

	if pattern.Match([]byte("")) {
		errhandle(errors.New("Your pattern matches empty string"), true, "")
	}

	searchFiles(pattern, ignorer)
}
コード例 #5
0
ファイル: main.go プロジェクト: uiri/coreutils
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Chmod"
	goopt.Summary = "Change file mode of each FILE to MODE\nWith reference, change file mode of each FILE to that of RFILE"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... [MODE] FILE...\n or:\t%s [OPTION]... --reference=RFILE FILE...\n", os.Args[0], os.Args[0]) +
			goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	silent := goopt.Flag([]string{"-f", "--silent", "--quiet"}, nil, "Suppress most error messages", "")
	/*changes := goopt.Flag([]string{"-c", "--changes"}, nil, "Like verbose but only report changes", "")
	verbose := goopt.Flag([]string{"-v", "--verbose"}, nil, "Output each file as it is processed", "")*/
	nodereference := goopt.Flag([]string{"-h", "--no-dereference"}, []string{"--derference"}, "Affect symbolic links directly instead of dereferencing them", "Dereference symbolic links before operating on them (This is default)")
	preserveroot := goopt.Flag([]string{"--preserve-root"}, []string{"--no-preserve-root"}, "Don't recurse on '/'", "Treat '/' normally (This is default)")
	goopt.OptArg([]string{"--reference"}, "RFILE", "Use RFILE's owner and group", fromReference)
	recurse := goopt.Flag([]string{"-R", "--recursive"}, nil, "Operate recursively on files and directories", "")
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	if len(goopt.Args) == 0 {
		coreutils.PrintUsage()
	}
	coreutils.Noderef = *nodereference
	coreutils.Preserveroot = *preserveroot
	if !usingreference {
		coreutils.ParseMode(goopt.Args[0])
	}
	var filestomod []string
	for i := range goopt.Args[1:] {
		filestomod = append(filestomod, goopt.Args[i+1])
		if *recurse && (!*preserveroot || goopt.Args[i+1] != "/") {
			if coreutils.Recurse(&filestomod) {
				defer os.Exit(1)
			}
		}
	}
	for i := range filestomod {
		err := os.Chmod(filestomod[i], coreutils.Mode)
		if err != nil && !*silent {
			fmt.Fprintf(os.Stderr, "Error changing mode for file '%s': %v\n", filestomod[i], err)
			defer os.Exit(1)
			continue
		}
	}
	return
}
コード例 #6
0
ファイル: main.go プロジェクト: uiri/coreutils
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Sync"
	goopt.Summary = "Flush filesystem buffers"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s OPTION\n", os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless an option is passed to it."
	}
	goopt.NoArg([]string{"-v", "--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	if len(goopt.Args) != 0 {
		coreutils.PrintUsage()
	}
	Sync()
	return
}
コード例 #7
0
ファイル: main.go プロジェクト: rdmo/devtodo2
func main() {
	goopt.Suite = "DevTodo2"
	goopt.Version = "2.1"
	goopt.Author = "Alec Thomas <*****@*****.**>"
	goopt.Description = func() string {
		return `DevTodo is a program aimed specifically at programmers (but usable by anybody
at the terminal) to aid in day-to-day development.

It maintains a list of items that have yet to be completed, one list for each
project directory. This allows the programmer to track outstanding bugs or
items that need to be completed with very little effort.

Items can be prioritised and are displayed in a hierarchy, so that one item may
depend on another.


todo2 [-A]
  Display (all) tasks.

todo2 [-p <priority>] -a <text>
  Create a new task.

todo2 -d <index>
  Mark a task as complete.

todo2 [-p <priority>] -e <task> [<text>]
  Edit an existing task.`
	}
	goopt.Summary = "DevTodo2 - a hierarchical command-line task manager"
	goopt.Usage = func() string {
		return fmt.Sprintf("usage: %s [<options>] ...\n\n%s\n\n%s",
			os.Args[0], goopt.Summary, goopt.Help())
	}
	goopt.Parse(nil)

	tasks, err := loadTaskList()
	if err != nil {
		fatal("%s", err)
	}
	if tasks == nil {
		tasks = NewTaskList()
	}
	processAction(tasks)
}
コード例 #8
0
ファイル: main.go プロジェクト: uiri/coreutils
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Whoami"
	goopt.Summary = "Prints username of current user"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage: %s OPTION\n", os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless an option is passed to it."
	}
	goopt.NoArg([]string{"-v", "--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	currentUser, err := user.Current()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error getting current user: %v\n", err)
		return
	}
	fmt.Println(currentUser.Username)
	return
}
コード例 #9
0
ファイル: main.go プロジェクト: uiri/coreutils
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Yes"
	goopt.Summary = "Loops forever printing out a string or 'y'"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage of %s:\n\t   %s STRING\n\tor %s OPTION\n", os.Args[0], os.Args[0], os.Args[0]) +
			goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless an option is passed to it."
	}
	goopt.NoArg([]string{"-v", "--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	repeat := strings.Join(goopt.Args, " ")
	if repeat == "" {
		repeat = "y"
	}
	for {
		fmt.Println(repeat)
	}
}
コード例 #10
0
ファイル: main.go プロジェクト: uiri/coreutils
func main() {
	goopt.Author = "Aaron Muir Hamilton"
	goopt.Version = "Sleep"
	goopt.Summary = "Pause for NUMBER seconds. SUFFIX may be 's' for seconds (the default), 'm' for minutes, 'h' for hours, or 'd' for days. NUMBER may be either an integer or a floating point number."
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage of %s:\n\t   %s NUMBER[SUFFIX]\n\tor %s OPTION\n", os.Args[0], os.Args[0], os.Args[0]) +
			goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string { return goopt.Summary + "\n\nUnless an option is passed to it." }
	goopt.NoArg([]string{"-v", "--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	if len(os.Args) == 1 {
		frown("missing operand")
	}
	var d time.Duration
	for i := range os.Args[1:] {
		d += parseDuration(os.Args[i+1])
	}
	time.Sleep(d)
	os.Exit(0)
}
コード例 #11
0
ファイル: vnx2graphite.go プロジェクト: koumdros/vnx2graphite
func main() {
	goopt.Version = version
	goopt.Summary = "send emc vnx performance data to graphite"
	goopt.Parse(nil)

	if f, _ := exists(*opt_conf); f == false {
		fmt.Print(goopt.Help())
		fmt.Println("ERROR: config file " + *opt_conf + " doesn't exist")
		return
	}
	c, _ := config.ReadDefault(*opt_conf)

	host, _ := c.String("graphite", "host")
	port, _ := c.Int("graphite", "port")
	timeout, _ := c.Int("graphite", "timeout")
	basename, _ := c.String("graphite", "basename")
	//todo: we also can parse this from the output...
	timestamp := time.Now().Unix()

	log(fmt.Sprintf("using graphite with host %s:%d", host, port))

	if f, _ := exists(*opt_data); f == false {
		fmt.Print(goopt.Help())
		fmt.Println("ERROR: data file " + *opt_data + " doesn't exist")
		return
	}
	lines, err := readLines(*opt_data)
	if err != nil {
		fmt.Println("ERROR:", err)
		return
	}
	//we only want to use the head and the first line of data
	head := strings.Split(lines[0], ",")
	data := strings.Split(lines[1], ",")

	if len(head) != len(data) {
		fmt.Println("ERROR: malformed csv (length of head != length of data")
		return
	}

	//create the graphite connection.
	// Todo: export this in a small pkg

	cstr := fmt.Sprintf("%s:%d", host, port)
	log("trying to connect to " + cstr)
	conn, err := net.DialTimeout("tcp", cstr, time.Duration(timeout)*time.Second)

	if err != nil {
		fmt.Println("ERROR:", err)
		return
	}

	for n, val := range head {
		key := stringify(val)
		value := stringify(data[n])
		if key != "Timestamp" {
			msg := fmt.Sprintf("%s.%s.%s.%s %s %d", basename, *opt_mover, *opt_statsname, key, value, timestamp)
			log("sending: " + msg)
			fmt.Fprint(conn, "\n"+msg+"\n")
		} else {
			log("Timestamp: ... next...")
		}
	}
	conn.Close()
}
コード例 #12
0
ファイル: main.go プロジェクト: uiri/coreutils
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Rm"
	goopt.Summary = "Remove each FILE"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... FILE...\n", os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	force = goopt.Flag([]string{"-f", "--force"}, nil, "Ignore nonexistent files, don't prompt user", "")
	prompteach = goopt.Flag([]string{"-i"}, nil, "Prompt before each removal", "")
	promptonce = goopt.Flag([]string{"-I"}, nil, "Prompt before removing multiple files at once", "")
	goopt.OptArg([]string{"--interactive"}, "WHEN", "Prompt according to WHEN", setPrompt)
	/*onefs := goopt.Flag([]string{"--one-file-system"}, nil, "When -r is specified, skip directories on different filesystems", "")*/
	nopreserveroot := goopt.Flag([]string{"--no-preserve-root"}, []string{"--preserve-root"}, "Do not treat '/' specially", "Do not remove '/' (This is default)")
	recurse := goopt.Flag([]string{"-r", "-R", "--recursive"}, nil, "Recursively remove directories and their contents", "")
	emptydir := goopt.Flag([]string{"-d", "--dir"}, nil, "Remove empty directories", "")
	verbose := goopt.Flag([]string{"-v", "--verbose"}, nil, "Output each file as it is processed", "")
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	promptno := true
	var filenames []string
	if len(goopt.Args) == 0 {
		coreutils.PrintUsage()
	}
	coreutils.Preserveroot = !*nopreserveroot
	coreutils.Silent = *force
	coreutils.Prompt = *prompteach || *promptonce
	coreutils.PromptFunc = func(filename string, remove bool) bool {
		var prompt string
		if remove {
			prompt = "Remove " + filename + "?"
		} else {
			prompt = "Recurse into " + filename + "?"
		}
		var response string
		trueresponse := "yes"
		falseresponse := "no"
		for {
			fmt.Print(prompt)
			fmt.Scanln(&response)
			response = strings.ToLower(response)
			if strings.Contains(trueresponse, response) {
				return true
			} else if strings.Contains(falseresponse, response) || response == "" {
				return false
			}
		}
	}
	for i := range goopt.Args {
		_, err := os.Lstat(goopt.Args[i])
		if *force && os.IsNotExist(err) {
			continue
		}
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error getting file info for '%s': %v\n", goopt.Args[i], err)
			defer os.Exit(1)
			continue
		}
		filenames = append(filenames, goopt.Args[i])
		if *recurse {
			if coreutils.Recurse(&filenames) {
				defer os.Exit(1)
			}
		}
	}
	sort.Strings(filenames)
	l := len(filenames) - 1
	for i := range filenames {
		fileinfo, err := os.Lstat(filenames[l-i])
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error getting file info for '%s': %v\n", filenames[l-i], err)
			defer os.Exit(1)
			continue
		}
		isadir := fileinfo.IsDir()
		if *prompteach || *promptonce && (l-i)%3 == 1 {
			promptno = coreutils.PromptFunc(filenames[l-i], true)
		}
		if !promptno {
			continue
		}
		if !*emptydir && !*recurse && isadir {
			fmt.Fprintf(os.Stderr, "Could not remove '%s': Is a directory\n", filenames[l-i])
			defer os.Exit(1)
			continue
		}
		if *verbose {
			fmt.Printf("Removing '%s'\n", filenames[l-i])
		}
		err = os.Remove(filenames[l-i])
		if err != nil && !(*force && os.IsNotExist(err)) {
			fmt.Fprintf(os.Stderr, "Could not remove '%s': %v\n", filenames[l-i], err)
			defer os.Exit(1)
		}
	}
	return
}
コード例 #13
0
ファイル: main.go プロジェクト: uiri/coreutils
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Link"
	goopt.Summary = "Creates a link to FILE1 called FILE2"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s FILE1 FILE2\n or:\t%s OPTION\n", os.Args[0], os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless an option is passed to it."
	}
	goopt.NoArg([]string{"-v", "--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	if len(goopt.Args) != 2 {
		coreutils.PrintUsage()
	}
	file1 := goopt.Args[0]
	file2 := goopt.Args[1]
	if err := os.Link(file1, file2); err != nil {
		fmt.Fprintf(os.Stderr, "Encountered an error during linking: %v\n", err)
		os.Exit(1)
	}
	return
}
コード例 #14
0
ファイル: main.go プロジェクト: uiri/coreutils
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Du"
	goopt.Summary = "Estimate file sizes"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... [FILE]...\n or:\t%s [OPTION]... --files0-from=F\n", os.Args[0], os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	null := goopt.Flag([]string{"-0", "--null"}, nil, "End output with \\0 instead of \\n", "")
	all := goopt.Flag([]string{"-a", "--all"}, nil, "Write counts for all files instead of only directories", "")
	goopt.OptArg([]string{"-B", "--block-size"}, "SIZE", "Set the block size that is used when printing.", setBlockSize)
	/*bytes := goopt.Flag([]string{"-b", "--bytes"}, nil, "Equivalent to --block-size=1", "")*/
	/*total := goopt.Flag([]string{"-c", "--total"}, nil, "Add up all the sizes to create a total", "")*/
	derefargs := goopt.Flag([]string{"-D", "--dereference-args", "-H"}, nil, "Dereference symlinks if they are a commandline argument", "")
	goopt.OptArg([]string{"-d", "--max-depth"}, "N", "Print total for directory that is N or fewer levels deep", setMaxDepth)
	goopt.OptArg([]string{"--files0-from"}, "F", "Use \\0 terminated file names from file F as commandline arguments", setFile0From)
	human = goopt.Flag([]string{"-h", "--human-readable"}, nil, "Output using human readable suffices", "")
	/*kilo := goopt.Flag([]string{"-k"}, nil, "Equivalent to --block-size=1K", "")*/
	dereference := goopt.Flag([]string{"-L", "--dereference"}, []string{"-P", "--no-dereference"}, "Dereference symbolic links", "Do not dereference any symbolic links (this is default)")
	separate := goopt.Flag([]string{"-S", "--separate-dirs"}, nil, "Do not add subdirectories to a directory's size", "")
	summarize := goopt.Flag([]string{"-s", "--summarize"}, nil, "Display totals only for each argument", "")
	goopt.OptArg([]string{"-t", "--threshold"}, "SIZE", "Only include entries whose size is greater than or equal to SIZE", setThreshold)
	/* Time and Exclude options go here */
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	if *null {
		lastchar = "\0000"
	}
	if len(goopt.Args) == 0 {
		goopt.Args = append([]string{}, ".")
	}
	if *all && *summarize {
		fmt.Fprintf(os.Stderr, "Cannot both summarize and display all. Pick ONE.\n")
		coreutils.PrintUsage()
	}
	sysblocksize := int64(1)
	kiloconst := int64(1)
	for i := range goopt.Args {
		fileinfo := Stat(goopt.Args[i], *dereference, *derefargs, true)
		if sysblocksize == 1 && fileinfo.Mode < 32768 {
			sizeperblock := int64(fileinfo.Size) / int64(fileinfo.Blocks)
			sysblocksize := int64(1)
			for sysblocksize < sizeperblock {
				sysblocksize *= 2
			}
			if sysblocksize < 1024 {
				kiloconst = 1024 / sysblocksize
			}
		}
		deeper := append([]string{}, goopt.Args[i])
		coreutils.Recurse(&deeper)
		orig := true
		startdepth := len(strings.Split(goopt.Args[i], string(os.PathSeparator)))
		foldertosize := make(map[string]int64)
		deepest := startdepth
		maxdepth += startdepth
		for j := range deeper {
			foldertosize[filepath.Dir(filepath.Clean(deeper[j]))] = 0
			if len(strings.Split(deeper[j], string(os.PathSeparator))) > deepest {
				deepest = len(strings.Split(deeper[j], string(os.PathSeparator)))
			}
		}
		for deepest >= startdepth {
			for j := range deeper {
				if len(strings.Split(deeper[j], string(os.PathSeparator))) != deepest {
					continue
				}
				fileinfo = Stat(deeper[j], *dereference, *derefargs, orig)
				if fileinfo.Mode > 32768 {
					foldertosize[filepath.Dir(filepath.Clean(deeper[j]))] += fileinfo.Blocks / kiloconst
					if maxdepth != startdepth && maxdepth < deepest {
						continue
					}
					if *all {
						fmt.Printf("%s\t%s%s", fmtSize(fileinfo.Blocks/2), deeper[j], lastchar)
					}
				} else {
					foldertosize[filepath.Clean(deeper[j])] += fileinfo.Blocks / kiloconst
					if !*separate && filepath.Dir(filepath.Clean(deeper[j])) != filepath.Clean(deeper[j]) {
						foldertosize[filepath.Dir(filepath.Clean(deeper[j]))] += foldertosize[filepath.Clean(deeper[j])]
					}
					if *summarize || (maxdepth < deepest && maxdepth != startdepth) {
						continue
					}
					fmt.Printf("%s\t%s%s", fmtSize(foldertosize[filepath.Clean(deeper[j])]), deeper[j], lastchar)
				}
			}
			deepest--
		}
		if *summarize {
			fmt.Printf("%s\t%s%s", fmtSize(foldertosize[filepath.Dir(filepath.Clean(goopt.Args[i]))]), goopt.Args[i], lastchar)
		}
	}
	return
}
コード例 #15
0
ファイル: main.go プロジェクト: uiri/coreutils
func main() {
	coreutils.Mode = 1<<31 | coreutils.Mode
	goopt.Author = "William Pearson"
	goopt.Version = "Mkdir"
	goopt.Summary = "Create each DIRECTORY, if it does not already exist."
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... DIRECTORY...\n", os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	goopt.OptArg([]string{"-m", "--mode"}, "MODE", "Set file mode permissions", coreutils.ParseMode)
	parents := goopt.Flag([]string{"-p", "--parents"}, nil, "Make parent directories as needed, no error if existing", "")
	verbose := goopt.Flag([]string{"-v", "--verbose"}, nil, "Output each directory as it is processed", "")
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	if len(goopt.Args) == 0 {
		coreutils.PrintUsage()
	}
	for i := range goopt.Args {
		if *parents {
			if createParents(goopt.Args[i], *verbose) {
				defer os.Exit(1)
			}
			continue
		}
		if *verbose {
			fmt.Printf("Creating directory %s\n", goopt.Args[i])
		}
		err := os.Mkdir(goopt.Args[i], coreutils.Mode)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error creating direction %s: %v\n", goopt.Args[i], err)
			defer os.Exit(1)
		}
	}
	return
}
コード例 #16
0
ファイル: main.go プロジェクト: uiri/coreutils
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Mv"
	goopt.Summary = "Move (rename) each SOURCE to DEST"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... SOURCE(...) DEST\n or:\t%s [OPTION]... -t DEST SOURCE\n", os.Args[0], os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	prompt := goopt.Flag([]string{"-i", "--interactive"}, nil, "Prompt before an overwrite. Override -f and -n.", "")
	noclobber := goopt.Flag([]string{"-n", "--no-clobber"}, []string{"-f", "--force"}, "Do not overwrite", "Never prompt before an overwrite")
	backup := goopt.Flag([]string{"-b", "--backup"}, nil, "Backup files before overwriting", "")
	goopt.OptArg([]string{"-S", "--suffix"}, "SUFFIX", "Override the usual backup suffix", coreutils.SetBackupSuffix)
	goopt.OptArg([]string{"-t", "--target"}, "TARGET", "Set the target with a flag instead of at the end", coreutils.SetTarget)
	update := goopt.Flag([]string{"-u", "--update"}, nil, "Move only when DEST is missing or older than SOURCE", "")
	verbose := goopt.Flag([]string{"-v", "--verbose"}, nil, "Output each file as it is processed", "")
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	if len(goopt.Args) < 2 {
		coreutils.PrintUsage()
	}
	if coreutils.Target == "" {
		coreutils.Target = goopt.Args[len(goopt.Args)-1]
	}
	destinfo, err := os.Lstat(coreutils.Target)
	if err != nil && !os.IsNotExist(err) {
		fmt.Fprintf(os.Stderr, "Error trying to get info to check if DEST is a directory: %v\n", err)
		os.Exit(1)
	}
	isadir := err == nil && destinfo.IsDir()
	if (len(goopt.Args) > 2 || (coreutils.Target != goopt.Args[len(goopt.Args)-1] && len(goopt.Args) > 1)) && !isadir {
		fmt.Fprintf(os.Stderr, "Too many arguments for non-directory destination")
		os.Exit(1)
	}
	for i := range goopt.Args[1:] {
		dest := coreutils.Target
		if isadir {
			dest = dest + string(os.PathSeparator) + filepath.Base(goopt.Args[i])
		}
		destinfo, err := os.Lstat(dest)
		exist := !os.IsNotExist(err)
		newer := true
		if err != nil && exist {
			fmt.Fprintf(os.Stderr, "Error trying to get info on target: %v\n", err)
			os.Exit(1)
		}
		if *update && exist {
			srcinfo, err := os.Lstat(goopt.Args[i])
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error trying to get mod time on SRC: %v\n", err)
				os.Exit(1)
			}
			newer = srcinfo.ModTime().After(destinfo.ModTime())
		}
		if !newer {
			continue
		}
		promptres := true
		if exist {
			promptres = !*noclobber
			if *prompt {
				promptres = coreutils.PromptFunc(dest, false)
			}
			if promptres && *backup {
				coreutils.Backup(dest)
			}
		}
		if promptres {
			err = os.Rename(goopt.Args[i], dest)
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error while moving '%s' to '%s': %v\n", goopt.Args[i], dest, err)
				defer os.Exit(1)
				continue
			}
			if *verbose {
				fmt.Printf("%s -> %s\n", goopt.Args[i], dest)
			}

		}
	}
	return
}
コード例 #17
0
ファイル: main.go プロジェクト: rhettg/ftl
func optFail(message string) {
	fmt.Println(message)
	fmt.Print(goopt.Help())
	os.Exit(1)
}
コード例 #18
0
ファイル: main.go プロジェクト: uiri/coreutils
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Cp"
	goopt.Summary = "Copy each SOURCE to DEST"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... SOURCE(...) DEST\n or:\t%s [OPTION]... -t DEST SOURCE\n", os.Args[0], os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	backup := goopt.Flag([]string{"-b", "--backup"}, nil, "Backup files before overwriting", "")
	prompt := goopt.Flag([]string{"-i", "--interactive"}, nil, "Prompt before an overwrite. Override -f and -n.", "")
	noclobber := goopt.Flag([]string{"-n", "--no-clobber"}, []string{"-f", "--force"}, "Do not overwrite", "Never prompt before an overwrite")
	hardlink := goopt.Flag([]string{"-l", "--link"}, nil, "Make hard links instead of copying", "")
	nodereference := goopt.Flag([]string{"-P", "--no-dereference"}, []string{"-L", "--dereference"}, "Never follow symlinks", "Always follow symlinks")
	/*preserve := goopt.Flag([]string{"-p", "--preserve"}, nil, "Preserve mode, ownership and timestamp attributes", "")*/
	recurse := goopt.Flag([]string{"-r", "-R", "--recurse"}, nil, "Recursively copy files from SOURCE to TARGET", "")
	goopt.OptArg([]string{"-S", "--suffix"}, "SUFFIX", "Override the usual backup suffix", setBackupSuffix)
	symlink := goopt.Flag([]string{"-s", "--symbolic-link"}, nil, "Make symlinks instead of copying", "")
	goopt.OptArg([]string{"-t", "--target"}, "TARGET", "Set the target with a flag instead of at the end", setTarget)
	update := goopt.Flag([]string{"-u", "--update"}, nil, "Move only when DEST is missing or older than SOURCE", "")
	verbose := goopt.Flag([]string{"-v", "--verbose"}, nil, "Output each file as it is processed", "")
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	if len(goopt.Args) < 2 {
		coreutils.PrintUsage()
	}
	coreutils.Noderef = *nodereference
	j := 0
	if target == "" {
		target = goopt.Args[len(goopt.Args)-1]
		j = 1
	}
	var sources []string
	for i := range goopt.Args[j:] {
		sources = append(sources, goopt.Args[i])
		if *recurse {
			if coreutils.Recurse(&sources) {
				defer os.Exit(1)
			}
		}
	}
	destinfo, err := coreutils.Stat(target)
	if err != nil && !os.IsNotExist(err) {
		fmt.Fprintf(os.Stderr, "Error trying to get info to check if DEST is a directory: %v\n", err)
		os.Exit(1)
	}
	isadir := err == nil && destinfo.IsDir()
	if (len(goopt.Args) > 2 || (target != goopt.Args[len(goopt.Args)-1] && len(goopt.Args) > 1)) && !isadir {
		fmt.Fprintf(os.Stderr, "Too many arguments for non-directory destination")
		os.Exit(1)
	}
	for i := range sources {
		dest := target
		if sources[i] == "" {
			continue
		}
		destinfo, err := coreutils.Stat(target)
		exist := !os.IsNotExist(err)
		if err != nil && exist {
			fmt.Fprintf(os.Stderr, "Error trying to get info on target: %v\n", err)
			os.Exit(1)
		}
		srcinfo, err := coreutils.Stat(sources[i])
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error trying to get mod time on SRC: %v\n", err)
			os.Exit(1)
		}
		mkdir := false
		if srcinfo.IsDir() {
			if isadir {
				dest = dest + string(os.PathSeparator) + sources[i]
			}
			if !*recurse {
				fmt.Printf("Skipping directory %s\n", sources[i])
				continue
			}
			mkdir = true
		} else if isadir {
			dest = dest + string(os.PathSeparator) + filepath.Base(sources[i])
		}
		newer := true
		if *update && exist {
			newer = srcinfo.ModTime().After(destinfo.ModTime())
		}
		if !newer {
			continue
		}
		promptres := true
		if exist {
			promptres = !*noclobber
			if *prompt {
				promptres = coreutils.PromptFunc(dest, false)
			}
			if promptres && *backup {
				if err = os.Rename(dest, dest+backupsuffix); err != nil {
					fmt.Fprintf(os.Stderr, "Error while backing up '%s' to '%s': %v\n", dest, dest+backupsuffix, err)
					defer os.Exit(1)
					continue
				}
			}
		}
		if !promptres {
			continue
		}
		switch {
		case mkdir:
			if err = os.Mkdir(dest, coreutils.Mode); err != nil {
				fmt.Fprintf(os.Stderr, "Error while making directory '%s': %v\n", dest, err)
				defer os.Exit(1)
				continue
			}
			if *verbose {
				fmt.Printf("Copying directory '%s' to '%s'\n", sources[i], dest)
			}
		case *hardlink:
			if err := os.Link(sources[i], dest); err != nil {
				fmt.Fprintf(os.Stderr, "Error while linking '%s' to '%s': %v\n", dest, sources[i], err)
				defer os.Exit(1)
				continue
			}
			if *verbose {
				fmt.Printf("Linked '%s' to '%s'\n", dest, sources[i])
			}
		case *symlink:
			if err := os.Symlink(sources[i], dest); err != nil {
				fmt.Fprintf(os.Stderr, "Error while linking '%s' to '%s': %v\n", dest, sources[i], err)
				defer os.Exit(1)
				continue
			}
			if *verbose {
				fmt.Printf("Symlinked '%s' to '%s'\n", dest, sources[i])
			}
		default:
			source, err := os.Open(sources[i])
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error while opening source file '%s': %v\n", sources[i], err)
				defer os.Exit(1)
				continue
			}
			filebuf, err := ioutil.ReadAll(source)
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error while reading source file, '%s', for copying: %v\n", sources[i], err)
				defer os.Exit(1)
				continue
			}
			destfile, err := os.Create(dest)
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error while creating destination file, '%s': %v\n", dest, err)
				defer os.Exit(1)
				continue
			}
			destfile.Write(filebuf)
			if *verbose {
				fmt.Printf("'%s' copied to '%s'\n", sources[i], dest)
			}
		}
	}
	return
}
コード例 #19
0
ファイル: unlink.go プロジェクト: rafkhan/coreutils
func main() {
	goopt.Suite = "XQZ coreutils"
	goopt.Author = "William Pearson"
	goopt.Version = "Unlink v0.1"
	goopt.Summary = "Uses unlink to remove FILE"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s FILE\n or:\t%s OPTION\n", os.Args[0], os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless an option is passed to it."
	}
	goopt.NoArg([]string{"-v", "--version"}, "outputs version information and exits", version)
	goopt.Parse(nil)
	switch {
	case len(os.Args) == 1:
		fmt.Println("Missing filenames")
	case len(os.Args) > 2:
		fmt.Println("Too many filenames")
	}
	if len(os.Args) != 2 {
		os.Exit(1)
	}
	file := os.Args[1]
	if err := syscall.Unlink(file); err != nil {
		fmt.Println("Encountered an error during unlinking: %v", err)
		os.Exit(1)
	}
	return
}
コード例 #20
0
ファイル: main.go プロジェクト: uiri/coreutils
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Echo"
	goopt.Summary = "Echo ARGs to stdout."
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [SHORT-OPTION] ARGS...\n or:\t%s LONG-OPTION\n", os.Args[0], os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nValid backslash escape sequences go here."
	}
	goopt.NoArg([]string{"-v", "--version"}, "outputs version information and exits", coreutils.Version)
	newline := goopt.Flag([]string{"-n"}, nil, "Don't print out a newline after ARGS", "")
	backslashescape := goopt.Flag([]string{"-e"}, []string{"-E"}, "Enable interpretation of backslash escapes", "Disable interpretation of backslash escapes")

	goopt.Parse(nil)
	argstring := strings.Join(goopt.Args, " ")
	if *backslashescape {
		argstring = fmt.Sprintf("%q", argstring)
		argstring = strings.Replace(argstring, "\\\\", "\\", -1)
		validEscapeSeqs := "\\abcefnrtv0x"
		for i := 0; i < len(argstring); i++ {
			if argstring[i] != '\\' {
				continue
			}
			if !strings.Contains(validEscapeSeqs, string(argstring[i+1])) {
				argstring = argstring[:i] + "\\" + argstring[i:]
			}
			i++
		}
		backslashstring, err := strconv.Unquote(argstring)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error encountered when interpreting escape sequences: %v\n", err)
			os.Exit(1)
		}
		argstring = backslashstring
	}
	nl := "\n"
	if *newline {
		nl = ""
	}
	fmt.Printf("%s%s", argstring, nl)
	return
}
コード例 #21
0
ファイル: link.go プロジェクト: rafkhan/coreutils
func main() {
	goopt.Suite = "XQZ coreutils"
	goopt.Author = "William Pearson"
	goopt.Version = "Link v0.1"
	goopt.Summary = "Creates a link to FILE1 called FILE2"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s FILE1 FILE2\n or:\t%s OPTION\n", os.Args[0], os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless an option is passed to it."
	}
	goopt.NoArg([]string{"-v", "--version"}, "outputs version information and exits", version)
	goopt.Parse(nil)
	switch {
	case len(os.Args) == 1:
		fmt.Println("Missing filenames")
	case len(os.Args) == 2:
		fmt.Println("Missing filename after '%s'", os.Args[1])
	case len(os.Args) > 3:
		fmt.Println("Too many filenames")
	}
	if len(os.Args) != 3 {
		os.Exit(1)
	}
	file1 := os.Args[1]
	file2 := os.Args[2]
	if err := os.Link(file1, file2); err != nil {
		fmt.Println("Encountered an error during linking: %v", err)
		os.Exit(1)
	}
	return
}
コード例 #22
0
ファイル: main.go プロジェクト: uiri/coreutils
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Rmdir"
	goopt.Summary = "Remove each DIRECTORY if it is empty"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... DIRECTORY...\n", os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	ignorefail := goopt.Flag([]string{"--ignore-fail-on-non-empty"}, nil,
		"Ignore each failure that is from a directory not being empty", "")
	parents := goopt.Flag([]string{"-p", "--parents"}, nil, "Remove DIRECTORY and ancestors if ancestors become empty", "")
	verbose := goopt.Flag([]string{"-v", "--verbose"}, nil, "Output each directory as it is processed", "")
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	if len(goopt.Args) == 0 {
		coreutils.PrintUsage()
	}
	for i := range goopt.Args {
		filelisting, err := ioutil.ReadDir(goopt.Args[i])
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to remove %s: %v\n", os.Args[i+1], err)
			defer os.Exit(1)
			continue
		}
		if !*ignorefail && len(filelisting) > 0 {
			fmt.Fprintf(os.Stderr, "Failed to remove '%s' directory is non-empty\n", goopt.Args[i])
			defer os.Exit(1)
			continue
		}
		if *verbose {
			fmt.Printf("Removing directory %s\n", goopt.Args[i])
		}
		err = os.Remove(goopt.Args[i])
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to remove %s: %v\n", goopt.Args[i], err)
			defer os.Exit(1)
			continue
		}
		if !*parents {
			continue
		}
		dir := goopt.Args[i]
		if dir[len(dir)-1] == '/' {
			dir = filepath.Dir(dir)
		}
		if removeEmptyParents(dir, *verbose, *ignorefail) {
			defer os.Exit(1)
		}
	}
	return
}
コード例 #23
0
ファイル: zmqc.go プロジェクト: jhawk28/zmqc
func main() {
	flag.Parse(nil)

	address_list := flag.Args
	if len(address_list) == 0 {
		fmt.Println("No Addresses submitted")
		fmt.Println(flag.Help())
		return
	}

	var send, recv bool
	skip := false

	var socket *zmq.Socket
	switch *socket_type {
	case "PUSH":
		socket, _ = zmq.NewSocket(zmq.PUSH)
		send = true
	case "PULL":
		socket, _ = zmq.NewSocket(zmq.PULL)
		recv = true
	case "PUB":
		socket, _ = zmq.NewSocket(zmq.PUB)
		send = true
	case "SUB":
		socket, _ = zmq.NewSocket(zmq.SUB)
		recv = true
		if len(*subscriptions) == 0 {
			socket.SetSubscribe("")
		}
		for _, subscription := range *subscriptions {
			socket.SetSubscribe(subscription)
		}
	case "REQ":
		socket, _ = zmq.NewSocket(zmq.REQ)
		send = true
		recv = true
	case "REP":
		socket, _ = zmq.NewSocket(zmq.REP)
		send = true
		recv = true
		skip = true
	}
	defer socket.Close()

	// connect or bind
	if *mode {
		for _, address := range address_list {
			socket.Connect(address)
		}
	} else {
		for _, address := range address_list {
			socket.Bind(address)
		}
	}

	delim := byte('\n')
	if *null {
		fmt.Println("Setting delim to null")
		delim = byte(0x00)
	}

	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)

	for i := 0; i < *number || *number == -1; i++ {
		if send && !skip {
			line, _ := reader.ReadBytes(delim)
			socket.SendBytes([]byte(line), 0)
		}
		if recv {
			data, _ := socket.RecvBytes(0)
			writer.Write(data)
			writer.Flush()
		}
		if skip {
			skip = false
		}
	}

	fmt.Println("finished", *number)
}
コード例 #24
0
ファイル: main.go プロジェクト: uiri/coreutils
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Chown"
	goopt.Summary = "Change owner or group of each FILE to OWNER or GROUP\nWith reference, change owner and group of each FILE to the owner and group of RFILE"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... [OWNER][:[GROUP]] FILE...\n or:\t%s [OPTION]... --reference=RFILE FILE...\n", os.Args[0], os.Args[0], os.Args[0]) +
			goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	changes := goopt.Flag([]string{"-c", "--changes"}, nil, "Like verbose but only report changes", "")
	silent := goopt.Flag([]string{"-f", "--silent", "--quiet"}, nil, "Suppress most error messages", "")
	verbose := goopt.Flag([]string{"-v", "--verbose"}, nil, "Output each file as it is processed", "")
	nodereference := goopt.Flag([]string{"-h", "--no-dereference"}, []string{"--derference"}, "Affect symbolic links directly instead of dereferencing them", "Dereference symbolic links before operating on them (This is default)")
	preserveroot := goopt.Flag([]string{"--preserve-root"}, []string{"--no-preserve-root"}, "Don't recurse on '/'", "Treat '/' normally (This is default)")
	goopt.OptArg([]string{"--reference"}, "RFILE", "Use RFILE's owner and group", fromReference)
	recurse := goopt.Flag([]string{"-R", "--recursive"}, nil, "Operate recursively on files and directories", "")
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	if len(goopt.Args) == 0 {
		coreutils.PrintUsage()
	}
	if !usingreference {
		usergroup := strings.Split(goopt.Args[0], ":")
		owner, err := user.Lookup(usergroup[0])
		if err != nil {
			uid = -1
		} else {
			uid, err = strconv.Atoi(owner.Uid)
			if err != nil && !*silent {

			}
			/* hack until Go matures */
			gid, err = strconv.Atoi(owner.Gid)
			if err != nil && !*silent {
				/* stuff */
			}
		}
	}
	for j := range goopt.Args[1:] {
		filenames := []string{goopt.Args[j+1]}
		for h := 0; h < len(filenames); h++ {
			/* Fix to only print when changes occur for *changes */
			if *changes || *verbose {
				fmt.Printf("Modifying ownership of %s\n", filenames[h])
			}
			if *nodereference {
				os.Lchown(filenames[h], uid, gid)
			} else {
				os.Chown(filenames[h], uid, gid)
			}
			if *recurse && (!*preserveroot || filenames[h] != "/") {
				filelisting, err := ioutil.ReadDir(filenames[h])
				if err != nil {
					fmt.Fprintf(os.Stderr, "Could not recurse into '%s'\n", filenames[h])
					defer os.Exit(1)
					continue
				}
				for g := range filelisting {
					filenames = append(filenames, filelisting[g].Name())
				}
			}
		}
	}
	return
}
コード例 #25
0
ファイル: main.go プロジェクト: uiri/coreutils
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Ln"
	goopt.Summary = "Make a LINK (whose name is optionally specified) to TARGET or make a link in DIRECTORY to each TARGET."
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... TARGET (LINK)\n or:\t%s [OPTION]... TARGET... DIRECTORY\n or:\t%s [OPTION]... -t DIRECTORY TARGET...\n", os.Args[0], os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	backup := goopt.Flag([]string{"-b", "--backup"}, nil, "Backup files before overwriting", "")
	prompt := goopt.Flag([]string{"-i", "--interactive"}, nil, "Prompt before removing any existing files.", "")
	force := goopt.Flag([]string{"-f", "--force"}, nil, "Remove existing files which match link names", "")
	directories := goopt.Flag([]string{"-d", "-F", "--directory"}, nil, "Allow attempts to hard link directories", "")
	nodereference := goopt.Flag([]string{"-n", "--no-dereference"}, nil, "treat LINK as a normal file if it is a symbolic link", "")
	logical := goopt.Flag([]string{"-L", "--logical"}, []string{"-P", "--physical"}, "Dereference TARGET if it is a symbolic link", "Make hard links directly to symbolic links. (this is default)")
	relative := goopt.Flag([]string{"-r", "--relative"}, nil, "Make symbolic links relative to link location", "")
	symbolic := goopt.Flag([]string{"-s", "--symbolic"}, nil, "Make symbolic links rather than hard links", "")
	goopt.OptArg([]string{"-S", "--suffix"}, "SUFFIX", "Override the usual backup suffix", coreutils.SetBackupSuffix)
	goopt.OptArg([]string{"-t", "--target"}, "TARGET", "Set the target with a flag instead of at the end", coreutils.SetTarget)
	verbose := goopt.Flag([]string{"-v", "--verbose"}, nil, "Output each file as it is processed", "")
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	if len(goopt.Args) < 2 {
		coreutils.PrintUsage()
	}
	coreutils.Noderef = *nodereference
	i := 0
	isadir := false
	exists := false
	if coreutils.Target == "" {
		if len(goopt.Args) > 1 {
			i = 1
			coreutils.Target = goopt.Args[len(goopt.Args)-1]
		} else {
			coreutils.Target = filepath.Base(goopt.Args[0])
		}
	} else {
		isadir = true
	}
	fileinfo, err := coreutils.Stat(coreutils.Target)
	if err != nil && !os.IsNotExist(err) {
		fmt.Fprintf(os.Stderr, "Error getting file info for '%s': %v\n", coreutils.Target, err)
		os.Exit(1)
	}
	if err == nil {
		exists = true
		if fileinfo.IsDir() {
			isadir = true
		}
	}
	for j := range goopt.Args[i:] {
		coreutils.Noderef = !*logical
		fileinfo, err = coreutils.Stat(goopt.Args[j])
		if err != nil && !os.IsNotExist(err) {
			fmt.Fprintf(os.Stderr, "Error getting file info for '%s': %v\n", goopt.Args[j], err)
			defer os.Exit(1)
			continue
		}
		if err == nil && !*symbolic && !*directories && fileinfo.IsDir() {
			fmt.Fprintf(os.Stderr, "Attempt to hard link a directory")
			defer os.Exit(1)
			continue
		}
		coreutils.Noderef = *nodereference
		dest := coreutils.Target
		if isadir {
			dest = dest + filepath.Base(goopt.Args[j])
			fileinfo, err = coreutils.Stat(dest)
			if err != nil && !os.IsNotExist(err) {
				fmt.Fprintf(os.Stderr, "Error getting file info for '%s': %v\n", dest, err)
				defer os.Exit(1)
				continue
			}
			if err == nil {
				exists = true
			}
		}
		promptno := true
		if exists {
			if *backup {
				coreutils.Backup(dest)
			}
			if *force {
				os.Remove(dest)
			} else if *prompt {
				promptno = coreutils.PromptFunc(dest, false)
				if promptno {
					os.Remove(dest)
				}
			}
			if !*relative {
				dest, err = filepath.Abs(dest)
				if err != nil {
					fmt.Fprintf(os.Stderr, "Error making absolute path from '%s'", dest, err)
				}
			}
		}
		if !promptno {
			exists = false
			continue
		}
		if *symbolic {
			os.Symlink(goopt.Args[j], dest)
		} else {
			os.Link(goopt.Args[j], dest)
		}
		if *verbose {
			fmt.Printf("'%s' -> '%s'\n", dest, goopt.Args[j])
		}
		exists = false
	}
	return
}