Exemplo n.º 1
0
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
}
Exemplo n.º 2
0
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
}
Exemplo n.º 3
0
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
}
Exemplo n.º 4
0
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
}