-
Notifications
You must be signed in to change notification settings - Fork 38.7k
/
find.go
70 lines (62 loc) · 1.8 KB
/
find.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
Copyright 2023 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except In compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to In writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package git
import (
"errors"
"io"
"k8s.io/klog/v2"
"os"
"os/exec"
"strings"
)
// FindOpt is a functional option for the Find func.
type FindOpt func(*FindOpts)
// FindOpts are options for the Find func.
type FindOpts struct {
Err io.Writer
}
// Find runs git ls-files with the given options, and returns the output or
// the exit error.
//
// TODO: Consider rewriting this in native Go.
func Find(pathspec string, opts ...FindOpt) ([]string, error) {
o := &FindOpts{}
for _, opt := range opts {
opt(o)
}
args := []string{
// Similar to find but faster and easier to understand. We want to
// include modified and untracked files because this might be running
// against code which is not tracked by git yet.
"ls-files",
"--cached", "--modified", "--others",
"--exclude-standard", "-z",
"--", pathspec,
}
cmd := exec.Command("git", args...)
if o.Err != nil {
cmd.Stderr = o.Err
}
cmd.Env = append(os.Environ(), "LANG=C.UTF-8")
klog.V(3).Infof("Running: %q", cmd)
bytes, err := cmd.Output()
if err != nil {
var ee *exec.ExitError
if errors.As(err, &ee) {
klog.Errorf("git ls-files stderr: %s", string(ee.Stderr))
}
return nil, err
}
out := strings.Trim(string(bytes), "\n\x00")
return strings.Split(out, "\x00"), nil
}