Add -L symlink follow option, default false

This commit is contained in:
Laurence Withers 2023-07-07 11:22:06 +01:00
parent 5694cc5194
commit eacffb4fe1
1 changed files with 34 additions and 15 deletions

49
main.go
View File

@ -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
}