github.com/rck/u-root@v0.0.0-20180106144920-7eb602e381bb/cmds/rm/rm.go (about) 1 // Copyright 2013-2017 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Delete files. 6 // 7 // Synopsis: 8 // rm [-Rrvif] FILE... 9 // 10 // Options: 11 // -i: interactive mode 12 // -v: verbose mode 13 // -R: remove file hierarchies 14 // -r: equivalent to -R 15 // -f: ignore nonexistent files and never prompt 16 package main 17 18 import ( 19 "bufio" 20 "flag" 21 "fmt" 22 "io" 23 "os" 24 "path" 25 "path/filepath" 26 "strings" 27 ) 28 29 var ( 30 flags struct { 31 r bool 32 v bool 33 i bool 34 f bool 35 } 36 cmd = "rm [-Rrvif] file..." 37 ) 38 39 func init() { 40 defUsage := flag.Usage 41 flag.Usage = func() { 42 os.Args[0] = cmd 43 defUsage() 44 } 45 flag.BoolVar(&flags.i, "i", false, "Interactive mode.") 46 flag.BoolVar(&flags.v, "v", false, "Verbose mode.") 47 flag.BoolVar(&flags.r, "R", false, "Remove file hierarchies") 48 flag.BoolVar(&flags.r, "r", false, "Equivalent to -R.") 49 flag.BoolVar(&flags.f, "f", false, "Ignore nonexistent files and never prompt") 50 } 51 52 func rm(stdin io.Reader, files []string) error { 53 f := os.Remove 54 if flags.r { 55 f = os.RemoveAll 56 } 57 58 if flags.f { 59 flags.i = false 60 } 61 62 workingPath, err := os.Getwd() 63 if err != nil { 64 return err 65 } 66 67 input := bufio.NewReader(stdin) 68 for _, file := range files { 69 if flags.i { 70 fmt.Printf("rm: remove '%v'? ", file) 71 answer, err := input.ReadString('\n') 72 if err != nil || strings.ToLower(answer)[0] != 'y' { 73 continue 74 } 75 } 76 77 if err := f(file); err != nil { 78 if flags.f && os.IsNotExist(err) { 79 continue 80 } 81 return err 82 } 83 84 if flags.v { 85 toRemove := file 86 if !path.IsAbs(file) { 87 toRemove = filepath.Join(workingPath, file) 88 } 89 fmt.Printf("removed '%v'\n", toRemove) 90 } 91 } 92 return nil 93 } 94 95 func main() { 96 flag.Parse() 97 if flag.NArg() < 1 { 98 flag.Usage() 99 os.Exit(1) 100 } 101 102 if err := rm(os.Stdin, flag.Args()); err != nil { 103 fmt.Fprintf(os.Stderr, "%v\n", err) 104 os.Exit(1) 105 } 106 }