@@ -5,10 +5,10 @@ package git
55
66import (
77 "bufio"
8+ "bytes"
89 "context"
910 "errors"
1011 "fmt"
11- "io"
1212 "os"
1313 "strconv"
1414 "strings"
@@ -33,15 +33,9 @@ func GrepSearch(ctx context.Context, repo *Repository, search string, opts GrepO
3333 if err != nil {
3434 return nil , fmt .Errorf ("unable to create os pipe to grep: %w" , err )
3535 }
36- stderrReader , stderrWriter , err := os .Pipe ()
37- if err != nil {
38- return nil , fmt .Errorf ("unable to create os pipe to grep: %w" , err )
39- }
4036 defer func () {
4137 _ = stdoutReader .Close ()
4238 _ = stdoutWriter .Close ()
43- _ = stderrReader .Close ()
44- _ = stderrWriter .Close ()
4539 }()
4640
4741 /*
@@ -53,28 +47,26 @@ func GrepSearch(ctx context.Context, repo *Repository, search string, opts GrepO
5347 HEAD:.changelog.yml
5448 2^@repo: go-gitea/gitea
5549 */
56- var stderr []byte
5750 var results []* GrepResult
5851 cmd := NewCommand (ctx , "grep" , "--null" , "--break" , "--heading" , "--fixed-strings" , "--line-number" , "--ignore-case" , "--full-name" )
5952 cmd .AddOptionValues ("--context" , fmt .Sprint (opts .ContextLineNumber ))
6053 if opts .IsFuzzy {
6154 words := strings .Fields (search )
6255 for _ , word := range words {
63- cmd .AddOptionValues ("-e" , word )
56+ cmd .AddOptionValues ("-e" , strings . TrimLeft ( word , "-" ) )
6457 }
6558 } else {
66- cmd .AddOptionValues ("-e" , search )
59+ cmd .AddOptionValues ("-e" , strings . TrimLeft ( search , "-" ) )
6760 }
6861 cmd .AddDynamicArguments (util .IfZero (opts .RefName , "HEAD" ))
62+ stderr := bytes.Buffer {}
6963 err = cmd .Run (& RunOpts {
7064 Dir : repo .Path ,
7165 Stdout : stdoutWriter ,
72- Stderr : stderrWriter ,
66+ Stderr : & stderr ,
7367 PipelineFunc : func (ctx context.Context , cancel context.CancelFunc ) error {
7468 _ = stdoutWriter .Close ()
75- _ = stderrWriter .Close ()
7669 defer stdoutReader .Close ()
77- defer stderrReader .Close ()
7870
7971 isInBlock := false
8072 scanner := bufio .NewScanner (stdoutReader )
@@ -106,12 +98,15 @@ func GrepSearch(ctx context.Context, repo *Repository, search string, opts GrepO
10698 res .LineCodes = append (res .LineCodes , lineCode )
10799 }
108100 }
109- stderr , _ = io .ReadAll (stderrReader )
110101 return scanner .Err ()
111102 },
112103 })
113- if err != nil && ! errors .Is (err , context .Canceled ) && len (stderr ) != 0 {
114- return nil , fmt .Errorf ("unable to run git grep: %w, stderr: %s" , err , string (stderr ))
104+ // git grep exits with 1 if no results are found
105+ if IsErrorExitCode (err , 1 ) && stderr .Len () == 0 {
106+ return nil , nil
107+ }
108+ if err != nil && ! errors .Is (err , context .Canceled ) {
109+ return nil , fmt .Errorf ("unable to run git grep: %w, stderr: %s" , err , stderr .String ())
115110 }
116111 return results , nil
117112}
0 commit comments