From 2bbfc3bc30e35af9a70edf0fc1ae8000759a89ae Mon Sep 17 00:00:00 2001 From: Laurence Withers Date: Thu, 11 May 2023 23:30:43 +0100 Subject: [PATCH] Very early work in progress --- .gitignore | 1 + LICENSE | 20 +++- go.mod | 14 +++ go.sum | 18 ++++ main.go | 300 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 349 insertions(+), 4 deletions(-) create mode 100644 .gitignore create mode 100644 go.mod create mode 100644 go.sum create mode 100644 main.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e3bc106 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/gg diff --git a/LICENSE b/LICENSE index 2071b23..1acd7a5 100644 --- a/LICENSE +++ b/LICENSE @@ -1,9 +1,21 @@ MIT License -Copyright (c) +Copyright (c) 2023 Laurence Withers -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..c5c8791 --- /dev/null +++ b/go.mod @@ -0,0 +1,14 @@ +module src.lwithers.me.uk/go/gg + +go 1.20 + +require ( + github.com/logrusorgru/aurora/v4 v4.0.0 + github.com/spf13/cobra v1.7.0 + golang.org/x/sys v0.8.0 +) + +require ( + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/spf13/pflag v1.0.5 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..6bd418b --- /dev/null +++ b/go.sum @@ -0,0 +1,18 @@ +github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/logrusorgru/aurora/v4 v4.0.0 h1:sRjfPpun/63iADiSvGGjgA1cAYegEWMPCJdUpJYn9JA= +github.com/logrusorgru/aurora/v4 v4.0.0/go.mod h1:lP0iIa2nrnT/qoFXcOZSrZQpJ1o6n2CUf/hyHi2Q4ZQ= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= +golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go new file mode 100644 index 0000000..cf23f1f --- /dev/null +++ b/main.go @@ -0,0 +1,300 @@ +/* +gg is a recursive grep written in Go, with some shortcuts for everyday use. +*/ +package main + +import ( + "bytes" + "errors" + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + "unicode" + "unicode/utf8" + + "github.com/logrusorgru/aurora/v4" + "github.com/spf13/cobra" + "golang.org/x/sys/unix" +) + +// TODO: +// - option to squelch aurora output +// - detect if terminal +// - binary file detection +// - long-line / minified-file detection +// - ignore files by extension (or glob?) + +func main() { + if err := rootCmd.Execute(); err != nil { + os.Exit(1) + } +} + +var rootCmd = &cobra.Command{ + Use: "gg pattern [path1 [path2 …]]", + Short: "gg is a recursive grep", + Long: `gg is a recursive grep. Given a regexp (or fixed pattern) it will search for +the pattern recursively in the current working directory. It will print a +coloured header per file along with the matching line and pattern. + +It is possible to scan specific files or directories, rather than the default +current working directory. To do this, simply specify the path(s) as arguments +following the pattern. + +It is possible to scan for multiple patterns using the -e (or -Q) argument, +which can be repeated multiple times. -e specifies a regular expression and +-Q a fixed pattern. When using either flag, any non-flag arguments are treated +as paths to scan. + +Search defaults to case-sensitive but the -I flag may be passed to make regular +expression searches case-insensitive. Alternatively, the "(?i)" construct may be +added to a regular expression to make that specific expression case insensitive. +Fixed pattern matches are always case-sensitive.`, + + RunE: run, +} + +var ( + searchRegexp []string + regexps []*regexp.Regexp + searchFixed []string + searchBytes [][]byte + searchPath []string + ignoreList []string + ignoreMap map[string]struct{} + ignoreCase bool +) + +func init() { + rootCmd.Flags().StringSliceVarP(&searchRegexp, "grep", "e", nil, "pattern to match (regular expression)") + rootCmd.Flags().StringSliceVarP(&searchFixed, "fixed", "Q", nil, "pattern to match (fixed string)") + rootCmd.Flags().StringSliceVarP(&ignoreList, "ignore", "i", []string{".git"}, "files/directories to ignore") + rootCmd.Flags().BoolVarP(&ignoreCase, "ignore-case", "I", false, "make all searches case insensitive") +} + +func run(c *cobra.Command, args []string) error { + if len(searchRegexp) == 0 && len(searchFixed) == 0 { + if len(args) == 0 { + return errors.New("no pattern specified") + } + searchRegexp = append(searchRegexp, args[0]) + args = args[1:] + } + + searchPath = args + if len(searchPath) == 0 { + searchPath = append(searchPath, ".") + } + + ignoreMap = make(map[string]struct{}, len(ignoreList)) + for _, i := range ignoreList { + ignoreMap[i] = struct{}{} + } + + for _, r := range searchRegexp { + if ignoreCase { + r = "(?i)" + r + } + re, err := regexp.Compile(r) + if err != nil { + return err + } + regexps = append(regexps, re) + } + + for _, s := range searchFixed { + searchBytes = append(searchBytes, []byte(s)) + } + + var errs []error + for _, path := range searchPath { + if err := search(path); err != nil { + errs = append(errs, err) + } + } + + return errors.Join(errs...) +} + +func recurse(path string) error { + d, err := os.ReadDir(path) + if err != nil { + return err + } + + var errs []error + for _, de := range d { + name := de.Name() + fullPath := filepath.Join(path, name) + + if _, ignored := ignoreMap[name]; ignored { + continue + } + + if err := search(fullPath); err != nil { + errs = append(errs, err) + } + } + return errors.Join(errs...) +} + +func search(path string) error { + st, err := os.Stat(path) + if err != nil { + return err + } + + switch { + case st.IsDir(): + return recurse(path) + + case !st.Mode().IsRegular(), + st.Size() == 0: + return nil + } + + f, err := os.Open(path) + if err != nil { + return err + } + defer f.Close() + fullData, err := unix.Mmap(int(f.Fd()), 0, int(st.Size()), unix.PROT_READ, unix.MAP_PRIVATE) + if err != nil { + return err + } + defer unix.Munmap(fullData) + + var printedHeader bool + + var ( + data = fullData + lineNum int + b, b2 strings.Builder + ) + for len(data) > 0 { + eol := bytes.IndexByte(data, '\n') + lineNum++ + var line []byte + if eol == -1 { + line = data + data = nil + } else { + line = data[:eol] + data = data[eol+1:] + } + + if len(line) == 0 { + continue + } + + loc := matches(line) + if loc == nil { + continue + } + + if !printedHeader { + printedHeader = true + fmt.Println(aurora.BgBlue(aurora.Bold(path))) + } + + b.Reset() + fmt.Fprintf(&b, "%4d: ", aurora.Gray(16, lineNum)) + + if loc[0] < 128 { + escape(&b, line[0:loc[0]]) + } else { + start := loc[0] - 128 + for i := 0; i < 5; i++ { + if utf8.RuneStart(line[start]) { + break + } + start++ + } + + fmt.Fprintf(&b, "(%d bytes)%s", start, aurora.Magenta("…")) + escape(&b, line[start:loc[0]]) + } + + if loc[1]-loc[0] < 128 { + b2.Reset() + escape(&b2, line[loc[0]:loc[1]]) + b.WriteString(aurora.Bold(b2.String()).String()) + + if loc[1]+128 > len(line) { + escape(&b, line[loc[1]:]) + } else { + end := loc[1] + 128 + for i := 0; i < 5; i++ { + if utf8.RuneStart(line[end]) { + break + } + end-- + } + escape(&b, line[loc[1]:end]) + fmt.Fprintf(&b, "(%d bytes)%s", len(line)-end, aurora.Magenta("…")) + } + + } else { + end := loc[1] + for i := 0; i < 5; i++ { + if utf8.RuneStart(line[end]) { + break + } + end-- + } + + b2.Reset() + escape(&b2, line[loc[0]:end]) + b.WriteString(aurora.Bold(b2.String()).String()) + fmt.Fprintf(&b, "%s(%d bytes)", aurora.Magenta("…"), len(line)-end) + + } + + b.WriteRune('\n') + fmt.Print(b.String()) + } + + return nil +} + +func matches(data []byte) (loc []int) { + for _, re := range regexps { + loc := re.FindIndex(data) + if loc != nil { + return loc + } + } + for _, s := range searchBytes { + pos := bytes.Index(data, s) + if pos != -1 { + return []int{pos, pos + len(s)} + } + } + return nil +} + +func escape(b *strings.Builder, s []byte) { + for len(s) > 0 { + r, size := utf8.DecodeRune(s) + s = s[size:] + + switch { + case r == utf8.RuneError && size == 1: + b.WriteString(aurora.Magenta("\uFFFD").String()) + + case r == '\r': + b.WriteString(aurora.Magenta(`\r`).String()) + + case r == '\t': + b.WriteString(aurora.Magenta(`\t`).String()) + + case unicode.IsPrint(r): + b.WriteRune(r) + + default: + b.WriteString(aurora.Magenta(".").String()) + } + } +}