Skip to content

Commit c735959

Browse files
committed
Refactor iterate git tree
1 parent ec771fd commit c735959

File tree

6 files changed

+105
-46
lines changed

6 files changed

+105
-46
lines changed

modules/actions/workflows.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ package actions
55

66
import (
77
"bytes"
8+
"context"
89
"io"
910
"strings"
1011

@@ -55,7 +56,7 @@ func ListWorkflows(commit *git.Commit) (git.Entries, error) {
5556
return nil, err
5657
}
5758

58-
entries, err := tree.ListEntriesRecursiveFast()
59+
entries, err := tree.ListEntriesRecursiveFast(context.Background())
5960
if err != nil {
6061
return nil, err
6162
}

modules/git/parse_nogogit.go

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,15 @@ func ParseTreeEntries(data []byte) ([]*TreeEntry, error) {
2424
var sepSpace = []byte{' '}
2525

2626
func parseTreeEntries(data []byte, ptree *Tree) ([]*TreeEntry, error) {
27-
var err error
2827
entries := make([]*TreeEntry, 0, bytes.Count(data, []byte{'\n'})+1)
28+
return entries, iterateTreeEntries(data, ptree, func(entry *TreeEntry) error {
29+
entries = append(entries, entry)
30+
return nil
31+
})
32+
}
33+
34+
func iterateTreeEntries(data []byte, ptree *Tree, f func(entry *TreeEntry) error) error {
35+
var err error
2936
for pos := 0; pos < len(data); {
3037
// expect line to be of the form:
3138
// <mode> <type> <sha> <space-padded-size>\t<filename>
@@ -39,7 +46,7 @@ func parseTreeEntries(data []byte, ptree *Tree) ([]*TreeEntry, error) {
3946
line := data[pos:posEnd]
4047
posTab := bytes.IndexByte(line, '\t')
4148
if posTab == -1 {
42-
return nil, fmt.Errorf("invalid ls-tree output (no tab): %q", line)
49+
return fmt.Errorf("invalid ls-tree output (no tab): %q", line)
4350
}
4451

4552
entry := new(TreeEntry)
@@ -69,27 +76,29 @@ func parseTreeEntries(data []byte, ptree *Tree) ([]*TreeEntry, error) {
6976
case "040000", "040755": // git uses 040000 for tree object, but some users may get 040755 for unknown reasons
7077
entry.entryMode = EntryModeTree
7178
default:
72-
return nil, fmt.Errorf("unknown type: %v", string(entryMode))
79+
return fmt.Errorf("unknown type: %v", string(entryMode))
7380
}
7481

7582
entry.ID, err = NewIDFromString(string(entryObjectID))
7683
if err != nil {
77-
return nil, fmt.Errorf("invalid ls-tree output (invalid object id): %q, err: %w", line, err)
84+
return fmt.Errorf("invalid ls-tree output (invalid object id): %q, err: %w", line, err)
7885
}
7986

8087
if len(entryName) > 0 && entryName[0] == '"' {
8188
entry.name, err = strconv.Unquote(string(entryName))
8289
if err != nil {
83-
return nil, fmt.Errorf("invalid ls-tree output (invalid name): %q, err: %w", line, err)
90+
return fmt.Errorf("invalid ls-tree output (invalid name): %q, err: %w", line, err)
8491
}
8592
} else {
8693
entry.name = string(entryName)
8794
}
8895

8996
pos = posEnd + 1
90-
entries = append(entries, entry)
97+
if err := f(entry); err != nil {
98+
return err
99+
}
91100
}
92-
return entries, nil
101+
return nil
93102
}
94103

95104
func catBatchParseTreeEntries(objectFormat ObjectFormat, ptree *Tree, rd *bufio.Reader, sz int64) ([]*TreeEntry, error) {

modules/git/repo_language_stats_nogogit.go

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,6 @@ func (repo *Repository) GetLanguageStats(commitID string) (map[string]int64, err
5454

5555
tree := commit.Tree
5656

57-
entries, err := tree.ListEntriesRecursiveWithSize()
58-
if err != nil {
59-
return nil, err
60-
}
61-
6257
checker, deferable := repo.CheckAttributeReader(commitID)
6358
defer deferable()
6459

@@ -74,18 +69,18 @@ func (repo *Repository) GetLanguageStats(commitID string) (map[string]int64, err
7469
firstExcludedLanguage := ""
7570
firstExcludedLanguageSize := int64(0)
7671

77-
for _, f := range entries {
72+
if err := tree.IterateEntriesWithSize(func(f *TreeEntry) error {
7873
select {
7974
case <-repo.Ctx.Done():
80-
return sizes, repo.Ctx.Err()
75+
return repo.Ctx.Err()
8176
default:
8277
}
8378

8479
contentBuf.Reset()
8580
content = contentBuf.Bytes()
8681

8782
if f.Size() == 0 {
88-
continue
83+
return nil
8984
}
9085

9186
isVendored := optional.None[bool]()
@@ -98,22 +93,22 @@ func (repo *Repository) GetLanguageStats(commitID string) (map[string]int64, err
9893
if err == nil {
9994
isVendored = AttributeToBool(attrs, AttributeLinguistVendored)
10095
if isVendored.ValueOrDefault(false) {
101-
continue
96+
return nil
10297
}
10398

10499
isGenerated = AttributeToBool(attrs, AttributeLinguistGenerated)
105100
if isGenerated.ValueOrDefault(false) {
106-
continue
101+
return nil
107102
}
108103

109104
isDocumentation = AttributeToBool(attrs, AttributeLinguistDocumentation)
110105
if isDocumentation.ValueOrDefault(false) {
111-
continue
106+
return nil
112107
}
113108

114109
isDetectable = AttributeToBool(attrs, AttributeLinguistDetectable)
115110
if !isDetectable.ValueOrDefault(true) {
116-
continue
111+
return nil
117112
}
118113

119114
hasLanguage := TryReadLanguageAttribute(attrs)
@@ -128,7 +123,7 @@ func (repo *Repository) GetLanguageStats(commitID string) (map[string]int64, err
128123

129124
// this language will always be added to the size
130125
sizes[language] += f.Size()
131-
continue
126+
return nil
132127
}
133128
}
134129
}
@@ -137,19 +132,19 @@ func (repo *Repository) GetLanguageStats(commitID string) (map[string]int64, err
137132
enry.IsDotFile(f.Name()) ||
138133
(!isDocumentation.Has() && enry.IsDocumentation(f.Name())) ||
139134
enry.IsConfiguration(f.Name()) {
140-
continue
135+
return nil
141136
}
142137

143138
// If content can not be read or file is too big just do detection by filename
144139

145140
if f.Size() <= bigFileSize {
146141
if err := writeID(f.ID.String()); err != nil {
147-
return nil, err
142+
return err
148143
}
149144
_, _, size, err := ReadBatchLine(batchReader)
150145
if err != nil {
151146
log.Debug("Error reading blob: %s Err: %v", f.ID.String(), err)
152-
return nil, err
147+
return err
153148
}
154149

155150
sizeToRead := size
@@ -161,22 +156,22 @@ func (repo *Repository) GetLanguageStats(commitID string) (map[string]int64, err
161156

162157
_, err = contentBuf.ReadFrom(io.LimitReader(batchReader, sizeToRead))
163158
if err != nil {
164-
return nil, err
159+
return err
165160
}
166161
content = contentBuf.Bytes()
167162
if err := DiscardFull(batchReader, discard); err != nil {
168-
return nil, err
163+
return err
169164
}
170165
}
171166
if !isGenerated.Has() && enry.IsGenerated(f.Name(), content) {
172-
continue
167+
return nil
173168
}
174169

175170
// FIXME: Why can't we split this and the IsGenerated tests to avoid reading the blob unless absolutely necessary?
176171
// - eg. do the all the detection tests using filename first before reading content.
177172
language := analyze.GetCodeLanguage(f.Name(), content)
178173
if language == "" {
179-
continue
174+
return nil
180175
}
181176

182177
// group languages, such as Pug -> HTML; SCSS -> CSS
@@ -197,6 +192,9 @@ func (repo *Repository) GetLanguageStats(commitID string) (map[string]int64, err
197192
firstExcludedLanguage = language
198193
firstExcludedLanguageSize += f.Size()
199194
}
195+
return nil
196+
}); err != nil {
197+
return sizes, err
200198
}
201199

202200
// If there are no included languages add the first excluded language

modules/git/tree_nogogit.go

Lines changed: 67 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
package git
77

88
import (
9+
"bufio"
10+
"context"
911
"io"
1012
"strings"
1113
)
@@ -88,34 +90,83 @@ func (t *Tree) ListEntries() (Entries, error) {
8890

8991
// listEntriesRecursive returns all entries of current tree recursively including all subtrees
9092
// extraArgs could be "-l" to get the size, which is slower
91-
func (t *Tree) listEntriesRecursive(extraArgs TrustedCmdArgs) (Entries, error) {
93+
func (t *Tree) listEntriesRecursive(ctx context.Context, extraArgs TrustedCmdArgs) (Entries, error) {
9294
if t.entriesRecursiveParsed {
9395
return t.entriesRecursive, nil
9496
}
9597

96-
stdout, _, runErr := NewCommand(t.repo.Ctx, "ls-tree", "-t", "-r").
97-
AddArguments(extraArgs...).
98-
AddDynamicArguments(t.ID.String()).
99-
RunStdBytes(&RunOpts{Dir: t.repo.Path})
100-
if runErr != nil {
101-
return nil, runErr
102-
}
103-
104-
var err error
105-
t.entriesRecursive, err = parseTreeEntries(stdout, t)
98+
t.entriesRecursive = make([]*TreeEntry, 0)
99+
err := t.iterateEntriesRecursive(func(entry *TreeEntry) error {
100+
select {
101+
case <-ctx.Done():
102+
return ctx.Err()
103+
default:
104+
}
105+
t.entriesRecursive = append(t.entriesRecursive, entry)
106+
return nil
107+
}, extraArgs)
106108
if err == nil {
107109
t.entriesRecursiveParsed = true
108110
}
109-
110111
return t.entriesRecursive, err
111112
}
112113

113114
// ListEntriesRecursiveFast returns all entries of current tree recursively including all subtrees, no size
114-
func (t *Tree) ListEntriesRecursiveFast() (Entries, error) {
115-
return t.listEntriesRecursive(nil)
115+
func (t *Tree) ListEntriesRecursiveFast(ctx context.Context) (Entries, error) {
116+
return t.listEntriesRecursive(ctx, nil)
116117
}
117118

118119
// ListEntriesRecursiveWithSize returns all entries of current tree recursively including all subtrees, with size
119-
func (t *Tree) ListEntriesRecursiveWithSize() (Entries, error) {
120-
return t.listEntriesRecursive(TrustedCmdArgs{"--long"})
120+
func (t *Tree) ListEntriesRecursiveWithSize(ctx context.Context) (Entries, error) {
121+
return t.listEntriesRecursive(ctx, TrustedCmdArgs{"--long"})
122+
}
123+
124+
// iterateEntriesRecursive returns iterate entries of current tree recursively including all subtrees
125+
// extraArgs could be "-l" to get the size, which is slower
126+
func (t *Tree) iterateEntriesRecursive(f func(entry *TreeEntry) error, extraArgs TrustedCmdArgs) error {
127+
if t.entriesRecursiveParsed {
128+
return nil
129+
}
130+
131+
reader, writer := io.Pipe()
132+
done := make(chan error)
133+
134+
go func(done chan error, writer *io.PipeWriter, reader *io.PipeReader) {
135+
runErr := NewCommand(t.repo.Ctx, "ls-tree", "-t", "-r").
136+
AddArguments(extraArgs...).
137+
AddDynamicArguments(t.ID.String()).
138+
Run(&RunOpts{
139+
Dir: t.repo.Path,
140+
Stdout: writer,
141+
})
142+
143+
_ = writer.Close()
144+
_ = reader.Close()
145+
146+
done <- runErr
147+
}(done, writer, reader)
148+
149+
scanner := bufio.NewScanner(reader)
150+
for scanner.Scan() {
151+
if err := scanner.Err(); err != nil {
152+
return err
153+
}
154+
data := scanner.Bytes()
155+
if err := iterateTreeEntries(data, t, func(entry *TreeEntry) error {
156+
select {
157+
case runErr := <-done:
158+
return runErr
159+
default:
160+
return f(entry)
161+
}
162+
}); err != nil {
163+
return err
164+
}
165+
}
166+
t.entriesRecursiveParsed = true
167+
return nil
168+
}
169+
170+
func (t *Tree) IterateEntriesWithSize(f func(*TreeEntry) error) error {
171+
return t.iterateEntriesRecursive(f, TrustedCmdArgs{"--long"})
121172
}

routers/web/repo/treelist.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ func TreeList(ctx *context.Context) {
2121
return
2222
}
2323

24-
entries, err := tree.ListEntriesRecursiveFast()
24+
entries, err := tree.ListEntriesRecursiveFast(ctx)
2525
if err != nil {
2626
ctx.ServerError("ListEntriesRecursiveFast", err)
2727
return

services/repository/files/tree.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ func GetTreeBySHA(ctx context.Context, repo *repo_model.Repository, gitRepo *git
2828
tree.URL = repo.APIURL() + "/git/trees/" + url.PathEscape(tree.SHA)
2929
var entries git.Entries
3030
if recursive {
31-
entries, err = gitTree.ListEntriesRecursiveWithSize()
31+
entries, err = gitTree.ListEntriesRecursiveWithSize(ctx)
3232
} else {
3333
entries, err = gitTree.ListEntries()
3434
}

0 commit comments

Comments
 (0)