From eacffb4fe1511f2ffc9f703416e8cff9c5ae995c Mon Sep 17 00:00:00 2001 From: Laurence Withers Date: Fri, 7 Jul 2023 11:22:06 +0100 Subject: [PATCH] Add -L symlink follow option, default false --- main.go | 49 ++++++++++++++++++++++++++++++++++--------------- 1 file changed, 34 insertions(+), 15 deletions(-) diff --git a/main.go b/main.go index 7534413..1d360b5 100644 --- a/main.go +++ b/main.go @@ -47,22 +47,31 @@ to a regular expression to make that specific expression case insensitive. Files and directories can be excluded with the -x option. This supports bash-style globs with '*', '?', '[a-z]', '{this,that}', or '/**/' to match zero or more -directories. By default, .git and vim swap files are ignored.`, +directories. By default, .git and vim swap files are ignored. Symlinks named on +the command line are followed, but by default symlinks are not followed when +recursing into directories. -L allows them to be dereferenced.`, RunE: run, } var ( - searchRegexp []string - regexps []*regexp.Regexp - searchFixed []string - searchPath []string - excludeList []string - binaryFile notPlainTextFlag - minifiedFile notPlainTextFlag - ignoreCase bool - noColour bool - display *Display + // flags + searchRegexp []string + searchFixed []string + searchPath []string + excludeList []string + ignoreCase bool + noColour bool + binaryFile notPlainTextFlag + minifiedFile notPlainTextFlag + followSymlinks bool + + // computed from searchRegexp, searchFixed. Each regexp here will be + // matched against each line of each input file. + regexps []*regexp.Regexp + + // formats output + display *Display ) func init() { @@ -73,6 +82,7 @@ func init() { rootCmd.Flags().BoolVarP(&noColour, "no-colour", "C", false, "disable colour output") rootCmd.Flags().Var(&binaryFile, "binary", "what to do with binary files") rootCmd.Flags().Var(&minifiedFile, "minified", "what to do with minified text files") + rootCmd.Flags().BoolVarP(&followSymlinks, "dereference", "L", false, "follow symlinks when recursing") } func run(c *cobra.Command, args []string) error { @@ -129,7 +139,7 @@ func run(c *cobra.Command, args []string) error { var errs []error for _, path := range searchPath { - if err := search(path); err != nil { + if err := search(path, true); err != nil { errs = append(errs, err) } } @@ -155,15 +165,24 @@ NextFile: } } - if err := search(fullPath); err != nil { + if err := search(fullPath, followSymlinks); err != nil { errs = append(errs, err) } } return errors.Join(errs...) } -func search(path string) error { - st, err := os.Stat(path) +func search(path string, deref bool) error { + var ( + st os.FileInfo + err error + ) + + if deref { + st, err = os.Stat(path) + } else { + st, err = os.Lstat(path) + } if err != nil { return err }