github.com/t-ham752/go-linux@v0.0.0-20230521064409-70f30d2872cc/pkg/grep/grep.go (about)

     1  package grep
     2  
     3  import (
     4  	"bufio"
     5  	"fmt"
     6  	"log"
     7  	"os"
     8  	"regexp"
     9  
    10  	"github.com/urfave/cli/v2"
    11  )
    12  
    13  type GrepFlags struct {
    14  	IgnoreCase bool
    15  }
    16  
    17  func run(args []string, flags *GrepFlags) error {
    18  	if len(args) < 2 {
    19  		return fmt.Errorf("not enough arguments")
    20  	}
    21  	target := args[0]
    22  	input := args[1]
    23  
    24  	if flags.IgnoreCase {
    25  		target = `(?i)` + target
    26  	}
    27  	re := regexp.MustCompile(target)
    28  
    29  	file, err := os.Open(input)
    30  	if err != nil {
    31  		log.Fatal(err)
    32  	}
    33  	defer file.Close()
    34  
    35  	scanner := bufio.NewScanner(file)
    36  	for scanner.Scan() {
    37  		line := scanner.Text()
    38  		if re.MatchString(line) {
    39  			fmt.Println(line)
    40  		}
    41  	}
    42  
    43  	return nil
    44  }
    45  
    46  func Grep() error {
    47  	var doesIgnore bool
    48  
    49  	app := &cli.App{
    50  		Name:  "go-grep",
    51  		Usage: "searches input files, selecting lines that match patterns.",
    52  		Flags: []cli.Flag{
    53  			&cli.BoolFlag{
    54  				Name:        "ignore-case",
    55  				Aliases:     []string{"i"},
    56  				Usage:       "ignore case distinctions",
    57  				Destination: &doesIgnore,
    58  			},
    59  		},
    60  		Action: func(c *cli.Context) error {
    61  			err := run(c.Args().Slice(), &GrepFlags{
    62  				IgnoreCase: doesIgnore,
    63  			})
    64  			if err != nil {
    65  				return err
    66  			}
    67  
    68  			return nil
    69  		},
    70  	}
    71  
    72  	if err := app.Run(os.Args); err != nil {
    73  		log.Fatal(err)
    74  	}
    75  
    76  	return nil
    77  }