From f851eb004b173bae889c6a3f5ef0de76a64ffae1 Mon Sep 17 00:00:00 2001 From: "Zed A. Shaw" Date: Sun, 26 Oct 2025 23:17:13 -0400 Subject: [PATCH] Quick code review and clean up to make them all about the same in style. --- cat/main.go | 12 ++--- curl/main.go | 2 +- cut/main.go | 4 +- find/main.go | 69 +++++++++++++++------------- grep/main.go | 63 +++++++++++++------------- ls/main.go | 63 +++++++++++++++----------- nohup/main.go | 30 ++++++------- numfmt/main.go | 111 ++++++++++++++++++++++++---------------------- od/main.go | 12 ++--- sha512sum/main.go | 48 ++++++++++---------- sort/main.go | 12 ++--- stat/main.go | 8 ++-- tail/main.go | 28 ++++++++---- uniq/main.go | 10 ++--- wc/main.go | 8 ++-- 15 files changed, 251 insertions(+), 229 deletions(-) diff --git a/cat/main.go b/cat/main.go index b4a6b26..6519953 100644 --- a/cat/main.go +++ b/cat/main.go @@ -8,19 +8,13 @@ import ( "strings" ) -func Fail(err error, format string, v ...any) { - err_format := fmt.Sprintf("ERROR: %v; %s", err, format) - log.Printf(err_format, v...) - os.Exit(1) -} - type Opts struct { Number bool Squeeze bool Filenames []string } -func parse_opts() (Opts) { +func ParseOpts() (Opts) { var opts Opts flag.BoolVar(&opts.Number, "n", false, "Number all nonempty output lines, starting with 1") @@ -38,12 +32,12 @@ func parse_opts() (Opts) { } func main() { - opts := parse_opts() + opts := ParseOpts() for _, filename := range opts.Filenames { in_file, err := os.ReadFile(filename) - if err != nil { Fail(err, "cannot open %s:", filename) } + if err != nil { log.Fatalf("cannot open %s: %v", filename, err) } if(opts.Number) { count := 1 diff --git a/curl/main.go b/curl/main.go index a514c90..719ab45 100644 --- a/curl/main.go +++ b/curl/main.go @@ -38,7 +38,7 @@ func main() { if err != nil { log.Fatal(err) } io.Copy(out, resp.Body) - } else { + } else { io.Copy(os.Stdout, resp.Body) } } diff --git a/cut/main.go b/cut/main.go index 3f74c4e..280dc51 100644 --- a/cut/main.go +++ b/cut/main.go @@ -16,7 +16,7 @@ type Opts struct { Delim string } -func parse_opts() Opts { +func ParseOpts() Opts { var opts Opts opts.Fields = make([]int, 0, 10) @@ -38,7 +38,7 @@ func parse_opts() Opts { } func main() { - opts := parse_opts() + opts := ParseOpts() scan := bufio.NewScanner(os.Stdin) for scan.Scan() { diff --git a/find/main.go b/find/main.go index fa9a918..eaa0bd3 100644 --- a/find/main.go +++ b/find/main.go @@ -10,38 +10,45 @@ import ( ) type Opts struct { - Name string - Type string - Print bool + Name string + Type string +} + +func ParseOpts() Opts { + var opts Opts + + flag.StringVar(&opts.Name, "name", "", "regex of file") + flag.StringVar(&opts.Type, "type", "f", "type to find") + flag.Parse() + + if flag.NArg() == 0 { + log.Fatal("USAGE: find -name [-type d/f] [dir dir]") + } + + return opts } func main() { - var opts Opts - - flag.StringVar(&opts.Name, "name", "", "regex of file") - flag.StringVar(&opts.Type, "type", "f", "type to find") - flag.Parse() - - re, err := regexp.Compile(opts.Name) - if err != nil { log.Fatal(err) } - - if flag.NArg() == 0 { - log.Fatal("USAGE: find -name [-type d/f] [dir dir]") - } - - for _, start := range flag.Args() { - filepath.WalkDir(start, func (path string, d fs.DirEntry, err error) error { - if re.MatchString(path) && opts.Print { - if opts.Type == "" { - fmt.Println(path) - } else if d.IsDir() && opts.Type == "d" { - fmt.Println(path) - } else if !d.IsDir() && opts.Type == "f" { - fmt.Println(path) - } - } - - return nil - }) - } + opts := ParseOpts() + + re, err := regexp.Compile(opts.Name) + if err != nil { log.Fatal(err) } + + for _, start := range flag.Args() { + filepath.WalkDir(start, func (path string, d fs.DirEntry, err error) error { + if err != nil { log.Fatal(err) } + + if re.MatchString(path) { + if opts.Type == "" { + fmt.Println(path) + } else if d.IsDir() && opts.Type == "d" { + fmt.Println(path) + } else if !d.IsDir() && opts.Type == "f" { + fmt.Println(path) + } + } + + return nil + }) + } } diff --git a/grep/main.go b/grep/main.go index f1dc9e1..9f58eb6 100644 --- a/grep/main.go +++ b/grep/main.go @@ -11,42 +11,43 @@ import ( ) func ScanInput(input io.Reader, exp string, prefix string) { - scan := bufio.NewScanner(input) - re, err := regexp.Compile(exp) + scan := bufio.NewScanner(input) + re, err := regexp.Compile(exp) - if err != nil { log.Fatal(err) } + if err != nil { log.Fatal(err) } - for scan.Scan() { - line := scan.Text() + for scan.Scan() { + line := scan.Text() - if re.MatchString(line) { - if prefix != "" { - fmt.Print(prefix, ": ") - } + if re.MatchString(line) { + if prefix != "" { + fmt.Print(prefix, ": ") + } - fmt.Println(line) - } - } + fmt.Println(line) + } + } } func main() { - flag.Parse() - - args := flag.Args() - - if len(args) == 0 { - log.Fatal("USAGE: grep [files...]") - } else if len(args) == 1 { - ScanInput(os.Stdin, args[0], "") - } else { - exp := args[0] - files := args[1:] - - for _, file := range files { - input, err := os.Open(file) - if err != nil { log.Fatal(err) } - - ScanInput(input, exp, file) - } - } + // NOTE: can we avoid flag here since it's just raw args? + flag.Parse() + + args := flag.Args() + + if len(args) == 0 { + log.Fatal("USAGE: grep [files...]") + } else if len(args) == 1 { + ScanInput(os.Stdin, args[0], "") + } else { + exp := args[0] + files := args[1:] + + for _, file := range files { + input, err := os.Open(file) + if err != nil { log.Fatal(err) } + + ScanInput(input, exp, file) + } + } } diff --git a/ls/main.go b/ls/main.go index b2fee5c..5824844 100644 --- a/ls/main.go +++ b/ls/main.go @@ -7,36 +7,47 @@ import ( "flag" ) -func main() { - var recurse bool - - flag.BoolVar(&recurse, "R", false, "recursive listing") - flag.Parse() +type Opts struct { + Recurse bool + Paths []string +} - paths := flag.Args() +func ParseOpts() Opts { + var opts Opts - if len(paths) == 0 { - paths = append(paths, ".") - } + flag.BoolVar(&opts.Recurse, "R", false, "recursive listing") + flag.Parse() - for _, what := range paths { - if flag.NArg() > 1 { - fmt.Printf("\n%s:\n", what) - } + opts.Paths = flag.Args() - filepath.WalkDir(what, func (path string, d fs.DirEntry, err error) error { - if path == what { return nil } + if len(opts.Paths) == 0 { + opts.Paths = append(opts.Paths, ".") + } - if d.IsDir() && recurse { - fmt.Printf("\n%s:\n", path) - } else if d.IsDir() { - fmt.Printf("%s\n", filepath.Base(path)) - return fs.SkipDir - } else { - fmt.Printf("%s\n", filepath.Base(path)) - } + return opts +} - return nil - }) - } +func main() { + opts := ParseOpts() + + for _, what := range opts.Paths { + if flag.NArg() > 1 { + fmt.Printf("\n%s:\n", what) + } + + filepath.WalkDir(what, func (path string, d fs.DirEntry, err error) error { + if path == what { return nil } + + if d.IsDir() && opts.Recurse { + fmt.Printf("\n%s:\n", path) + } else if d.IsDir() { + fmt.Printf("%s\n", filepath.Base(path)) + return fs.SkipDir + } else { + fmt.Printf("%s\n", filepath.Base(path)) + } + + return nil + }) + } } diff --git a/nohup/main.go b/nohup/main.go index 6db12b0..ae963b0 100644 --- a/nohup/main.go +++ b/nohup/main.go @@ -12,26 +12,26 @@ import ( ) func Exec(prog string, args []string, target_out io.Writer) { - cmd := exec.Command(prog, args...) - if cmd.Err != nil { log.Fatal(cmd.Err) } + cmd := exec.Command(prog, args...) + if cmd.Err != nil { log.Fatal(cmd.Err) } - in, err := cmd.StdinPipe() - if err != nil { log.Fatal(err) } - in.Close() + in, err := cmd.StdinPipe() + if err != nil { log.Fatal(err) } + in.Close() - stdout, err := cmd.StdoutPipe() - if err != nil { log.Fatal(err) } + stdout, err := cmd.StdoutPipe() + if err != nil { log.Fatal(err) } - stderr, err := cmd.StderrPipe() - if err != nil { log.Fatal(err) } + stderr, err := cmd.StderrPipe() + if err != nil { log.Fatal(err) } - output := io.MultiReader(stdout, stderr) + output := io.MultiReader(stdout, stderr) - err = cmd.Start() - if err != nil { log.Fatal(err) } + err = cmd.Start() + if err != nil { log.Fatal(err) } - _, err = io.Copy(target_out, output) - if err != nil { log.Fatal(err) } + _, err = io.Copy(target_out, output) + if err != nil { log.Fatal(err) } } func OpenOutput() io.Writer { @@ -53,7 +53,7 @@ func main() { args := flag.Args() if flag.NArg() == 0 { - log.Fatal("USAGE: nohup cmd [args]") + log.Fatal("USAGE: nohup cmd [args]") } output := OpenOutput() diff --git a/numfmt/main.go b/numfmt/main.go index 99931e2..fb614be 100644 --- a/numfmt/main.go +++ b/numfmt/main.go @@ -1,75 +1,78 @@ package main import ( - "fmt" - "flag" - "strconv" - "log" - "math" - "bufio" - "os" + "fmt" + "flag" + "strconv" + "log" + "math" + "bufio" + "os" ) type Opts struct { - From string - To string + From string + To string + Numbers []string } -func parse_opts() (Opts, []string) { - var opts Opts +func ParseOpts() Opts { + var opts Opts - flag.StringVar(&opts.From, "from", "", "Convert from") - flag.StringVar(&opts.To, "to", "", "Convert to") - flag.Parse() + flag.StringVar(&opts.From, "from", "", "Convert from") + flag.StringVar(&opts.To, "to", "", "Convert to") + flag.Parse() - return opts, flag.Args() + opts.Numbers = flag.Args() + + return opts } func to_si(num string) string { - number, err := strconv.ParseFloat(num, 64) - if err != nil { log.Fatal("that's not a number") } - mag := math.Floor(math.Log10(number)) + number, err := strconv.ParseFloat(num, 64) + if err != nil { log.Fatal("that's not a number") } + mag := math.Floor(math.Log10(number)) - switch { - case mag < 3: - return num - case mag == 3: - // need to separate k from hundres - as_k := math.Floor(float64(number) / 1000.0) - mod := math.Ceil(float64(int(number) % 1000)) - return fmt.Sprintf("%d.%dk", int(as_k), int(mod)) - case mag > 3 && mag < 6: - as_m := math.Ceil(float64(number) / 1000.0) - return fmt.Sprintf("%dk", int(as_m)) - case mag == 6: - // need to separate mil from k - as_m := math.Floor(float64(number) / 1000000.0) - mod := math.Ceil(float64(int(number) % 1000000) / 1000.0) - return fmt.Sprintf("%d.%dM", int(as_m), int(mod)) - case mag > 6 && mag <= 9: - as_m := math.Ceil(float64(number) / 1000000.0) - return fmt.Sprintf("%dM", int(as_m)) - default: - return fmt.Sprintf("%sbesos", num) - } + switch { + case mag < 3: + return num + case mag == 3: + // need to separate k from hundres + as_k := math.Floor(float64(number) / 1000.0) + mod := math.Ceil(float64(int(number) % 1000)) + return fmt.Sprintf("%d.%dk", int(as_k), int(mod)) + case mag > 3 && mag < 6: + as_m := math.Ceil(float64(number) / 1000.0) + return fmt.Sprintf("%dk", int(as_m)) + case mag == 6: + // need to separate mil from k + as_m := math.Floor(float64(number) / 1000000.0) + mod := math.Ceil(float64(int(number) % 1000000) / 1000.0) + return fmt.Sprintf("%d.%dM", int(as_m), int(mod)) + case mag > 6 && mag <= 9: + as_m := math.Ceil(float64(number) / 1000000.0) + return fmt.Sprintf("%dM", int(as_m)) + default: + return fmt.Sprintf("%sbesos", num) + } } func main() { - opts, nums := parse_opts() + opts := ParseOpts() - if opts.From != "" { - log.Fatal("you should implement this") - } + if opts.From != "" { + log.Fatal("you should implement this") + } - if len(nums) == 0 { - scanner := bufio.NewScanner(os.Stdin) - for scanner.Scan() { - num := scanner.Text() - fmt.Println(to_si(num)) - } - } else { - for _, num := range nums { - fmt.Println(to_si(num)) - } + if len(opts.Numbers) == 0 { + scanner := bufio.NewScanner(os.Stdin) + for scanner.Scan() { + num := scanner.Text() + fmt.Println(to_si(num)) + } + } else { + for _, num := range opts.Numbers { + fmt.Println(to_si(num)) } + } } diff --git a/od/main.go b/od/main.go index 8439c8d..7db903b 100644 --- a/od/main.go +++ b/od/main.go @@ -8,12 +8,6 @@ import ( "bufio" ) -func Fail(err error, format string, v ...any) { - err_format := fmt.Sprintf("ERROR: %v; %s", err, format) - log.Printf(err_format, v...) - os.Exit(1) -} - type Opts struct { Width int Filenames []string @@ -22,7 +16,7 @@ type Opts struct { Format string } -func parse_opts() (Opts) { +func ParseOpts() (Opts) { var opts Opts flag.IntVar(&opts.Width, "w", 16, "Width of output grid") @@ -46,12 +40,12 @@ func parse_opts() (Opts) { } func main() { - opts := parse_opts() + opts := ParseOpts() for _, filename := range opts.Filenames { reader, err := os.Open(filename) defer reader.Close() - if err != nil { Fail(err, "can't open: %s", filename) } + if err != nil { log.Fatalf("can't open: %s: %v", filename, err) } buf := bufio.NewReader(reader) count := buf.Size() diff --git a/sha512sum/main.go b/sha512sum/main.go index a6a10a3..1060325 100644 --- a/sha512sum/main.go +++ b/sha512sum/main.go @@ -1,45 +1,45 @@ package main import ( - "fmt" - "flag" - "os" - "log" - "crypto/sha512" + "fmt" + "flag" + "os" + "log" + "crypto/sha512" ) type Opts struct { - Inputs []string + Inputs []string } -func parse_opts() Opts { - var opts Opts +func ParseOpts() Opts { + var opts Opts - flag.Parse() - opts.Inputs = flag.Args() + flag.Parse() + opts.Inputs = flag.Args() - return opts + return opts } -func to_hex(hash [sha512.Size]byte) string { - result := "" +func ToHex(hash [sha512.Size]byte) string { + result := "" - for _, b := range hash { - result += fmt.Sprintf("%x", b) - } + for _, b := range hash { + result += fmt.Sprintf("%x", b) + } - return result + return result } func main() { - opts := parse_opts() + opts := ParseOpts() - for _, fname := range opts.Inputs { - in_data, err := os.ReadFile(fname) - if err != nil { log.Fatal(err) } + for _, fname := range opts.Inputs { + in_data, err := os.ReadFile(fname) + if err != nil { log.Fatal(err) } - hash := sha512.Sum512(in_data) + hash := sha512.Sum512(in_data) - fmt.Println(to_hex(hash), fname) - } + fmt.Println(ToHex(hash), fname) + } } diff --git a/sort/main.go b/sort/main.go index d832321..2f41e76 100644 --- a/sort/main.go +++ b/sort/main.go @@ -15,7 +15,7 @@ type Opts struct { Numeric bool } -func parse_opts() Opts { +func ParseOpts() Opts { var opts Opts flag.BoolVar(&opts.IgnoreCase, "f", false, "ignore case") @@ -26,7 +26,7 @@ func parse_opts() Opts { return opts } -func numeric_sort(a string, b string) int { +func NumericSort(a string, b string) int { a_int, a_err := strconv.Atoi(a) b_int, b_err := strconv.Atoi(b) @@ -37,13 +37,13 @@ func numeric_sort(a string, b string) int { } } -func ignore_case_sort(a string, b string) int { +func IgnoreCase(a string, b string) int { return strings.Compare(strings.ToLower(a), strings.ToLower(b)) } func main() { lines := make([]string, 0, 100) - opts := parse_opts() + opts := ParseOpts() scan := bufio.NewScanner(os.Stdin) @@ -53,9 +53,9 @@ func main() { } if opts.Numeric { - slices.SortFunc(lines, numeric_sort) + slices.SortFunc(lines, NumericSort) } else if opts.IgnoreCase{ - slices.SortFunc(lines, ignore_case_sort) + slices.SortFunc(lines, IgnoreCase) } else { slices.Sort(lines) } diff --git a/stat/main.go b/stat/main.go index e4d0b31..7cd691e 100644 --- a/stat/main.go +++ b/stat/main.go @@ -10,10 +10,10 @@ import ( func PrintStat(stat fs.FileInfo) { fmt.Printf("File: %s\nSize: %d\nAccess: %v\nModify: %v", - stat.Name(), - stat.Size(), - stat.Mode(), - stat.ModTime()) + stat.Name(), + stat.Size(), + stat.Mode(), + stat.ModTime()) } func main() { diff --git a/tail/main.go b/tail/main.go index 9367906..6b4af23 100644 --- a/tail/main.go +++ b/tail/main.go @@ -27,21 +27,33 @@ func TailFile(file io.Reader, count int) { } } -func main() { - var count int +type Opts struct { + Count int + Files []string +} - flag.IntVar(&count, "n", 10, "number of lines") +func ParseOpts() Opts { + var opts Opts + + flag.IntVar(&opts.Count, "n", 10, "number of lines") flag.Parse() - if flag.NArg() > 0 { - files := flag.Args() - for _, fname := range files { + opts.Files = flag.Args() + + return opts +} + +func main() { + opts := ParseOpts() + + if len(opts.Files) > 0 { + for _, fname := range opts.Files { file, err := os.Open(fname) if err != nil { log.Fatal(err) } - TailFile(file, count) + TailFile(file, opts.Count) } } else { - TailFile(os.Stdin, count) + TailFile(os.Stdin, opts.Count) } } diff --git a/uniq/main.go b/uniq/main.go index 76144c1..1b887ec 100644 --- a/uniq/main.go +++ b/uniq/main.go @@ -7,13 +7,13 @@ import ( "strings" "flag" ) + type Opts struct { IgnoreCase bool Count bool } - -func parse_opts() Opts { +func ParseOpts() Opts { var opts Opts flag.BoolVar(&opts.IgnoreCase, "i", false, "ignore case") @@ -23,7 +23,7 @@ func parse_opts() Opts { return opts } -func string_equal(a string, b string, ignore_case bool) bool { +func StringEqual(a string, b string, ignore_case bool) bool { if ignore_case { a = strings.ToLower(a) b = strings.ToLower(b) @@ -36,12 +36,12 @@ func main() { scan := bufio.NewScanner(os.Stdin) seen_line := "" seen_count := 0 - opts := parse_opts() + opts := ParseOpts() for scan.Scan() { line := scan.Text() - if !string_equal(line, seen_line, opts.IgnoreCase) { + if !StringEqual(line, seen_line, opts.IgnoreCase) { if opts.Count { fmt.Print(seen_count, " ") } diff --git a/wc/main.go b/wc/main.go index 732a01b..7c61e03 100644 --- a/wc/main.go +++ b/wc/main.go @@ -26,7 +26,7 @@ type Counts struct { } -func parse_opts() (Opts, []string) { +func ParseOpts() (Opts, []string) { var opts Opts flag.BoolVar(&opts.Bytes, "c", false, "Count bytes") @@ -48,7 +48,7 @@ func parse_opts() (Opts, []string) { } -func count_file(opts *Opts, filename string) Counts { +func CountFile(opts *Opts, filename string) Counts { var counts Counts in_file, err := os.Open(filename) @@ -104,10 +104,10 @@ func print_count(opts *Opts, count *Counts, file string) { } func main() { - opts, files := parse_opts() + opts, files := ParseOpts() for _, file := range files { - count := count_file(&opts, file) + count := CountFile(&opts, file) print_count(&opts, &count, file) } }