Debian Codegraph @

cmd/fragment/fragment.go

raw
1 package main
2
3 import (
4 "bufio"
5 "flag"
6 "fmt"
7 "os"
8 "path/filepath"
9 "strconv"
10
11 "github.com/kisom/goutils/die"
12 )
13
14 func usage() {
15 progname := filepath.Base(os.Args[0])
16 fmt.Printf(`Usage: %s [-nl] file start [end]
17
18 Print a fragment of a file starting a line 'start' and ending
19 at line 'end', or EOF if no end is specified.
20
21 The -nl flag will suppress printing of line numbers.
22 `, progname)
23 }
24
25 func main() {
26 quiet := flag.Bool("nl", false, "No line-numbering.")
27 flag.Parse()
28
29 if flag.NArg() < 2 || flag.NArg() > 3 {
30 usage()
31 os.Exit(1)
32 }
33
34 start, err := strconv.Atoi(flag.Arg(1))
35 die.If(err)
36
37 var end int
38 var offset bool
39 if flag.NArg() == 3 {
40 endStr := flag.Arg(2)
41 if endStr[0] == '+' {
42 offset = true
43 endStr = endStr[1:]
44 }
45 end, err = strconv.Atoi(endStr)
46 die.If(err)
47 if offset {
48 end += start
49 }
50 }
51
52 file, err := os.Open(flag.Arg(0))
53 die.If(err)
54 defer file.Close()
55
56 scanner := bufio.NewScanner(file)
57
58 // initial empty line to start numbering at 1.
59 var lines = make([]string, 1)
60 for scanner.Scan() {
61 lines = append(lines, scanner.Text())
62 }
63
64 if end == 0 {
65 end = len(lines) - 1
66 }
67
68 if end < start {
69 fmt.Fprintln(os.Stderr, "[!] end < start, swapping values")
70 tmp := end
71 end = start
72 start = tmp
73 }
74
75 var fmtStr string
76
77 if !*quiet {
78 maxLine := fmt.Sprintf("%d", len(lines))
79 fmtStr = fmt.Sprintf("%%0%dd: %%s", len(maxLine))
80 }
81
82 endFunc := func(n int) bool {
83 if n == 0 {
84 return false
85 }
86
87 if n > end {
88 return true
89 }
90 return false
91 }
92
93 fmtStr += "\n"
94 for i := start; !endFunc(i); i++ {
95 if *quiet {
96 fmt.Println(lines[i])
97 } else {
98 fmt.Printf(fmtStr, i, lines[i])
99 }
100 }
101 }