Skip to content

Commit 2b730a1

Browse files
committed
fix cancel
1 parent 812f8bb commit 2b730a1

File tree

1 file changed

+18
-18
lines changed

1 file changed

+18
-18
lines changed

modules/git/repo_index.go

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -50,35 +50,35 @@ func (repo *Repository) readTreeToIndex(id ObjectID, indexFilename ...string) er
5050
}
5151

5252
// ReadTreeToTemporaryIndex reads a treeish to a temporary index file
53-
func (repo *Repository) ReadTreeToTemporaryIndex(treeish string) (filename, tmpDir string, cancel context.CancelFunc, err error) {
54-
cancel = func() {
55-
if tmpDir == "" {
56-
return
57-
}
58-
if removeErr := util.RemoveAll(tmpDir); removeErr != nil {
59-
log.Error("failed to remove tmp index file: %v", removeErr)
60-
}
61-
}
62-
63-
// Defer the cancel function to ensure cleanup in case of an error
53+
func (repo *Repository) ReadTreeToTemporaryIndex(treeish string) (tmpIndexFilename, tmpDir string, cancel context.CancelFunc, err error) {
6454
defer func() {
65-
if err != nil {
55+
// if error happens and there is a cancel function, do clean up
56+
if err != nil && cancel != nil {
6657
cancel()
58+
cancel = nil
6759
}
6860
}()
6961

62+
removeDirFn := func(dir string) func() { // it can't use the return value "tmpDir" directly because it is empty when error occurs
63+
return func() {
64+
if err := util.RemoveAll(dir); err != nil {
65+
log.Error("failed to remove tmp index dir: %v", err)
66+
}
67+
}
68+
}
69+
7070
tmpDir, err = os.MkdirTemp("", "index")
7171
if err != nil {
72-
return filename, tmpDir, cancel, err
72+
return "", "", nil, err
7373
}
7474

75-
filename = filepath.Join(tmpDir, ".tmp-index")
76-
77-
err = repo.ReadTreeToIndex(treeish, filename)
75+
tmpIndexFilename = filepath.Join(tmpDir, ".tmp-index")
76+
cancel = removeDirFn(tmpDir)
77+
err = repo.ReadTreeToIndex(treeish, tmpIndexFilename)
7878
if err != nil {
79-
return "", "", func() {}, err
79+
return "", "", cancel, err
8080
}
81-
return filename, tmpDir, cancel, err
81+
return tmpIndexFilename, tmpDir, cancel, err
8282
}
8383

8484
// EmptyIndex empties the index

0 commit comments

Comments
 (0)