diff options
author | Lunny Xiao <xiaolunwen@gmail.com> | 2024-11-22 00:50:35 -0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-11-22 08:50:35 +0000 |
commit | 073ba977fc7c2f58aa3c2faebcdadda49e6e2aac (patch) | |
tree | a699c0105f079d7af2294dc78800a4af17a4df05 | |
parent | 2b8b2772fd2859f6816a5641988da62598cadef4 (diff) | |
download | gitea-073ba977fc7c2f58aa3c2faebcdadda49e6e2aac.tar.gz gitea-073ba977fc7c2f58aa3c2faebcdadda49e6e2aac.zip |
Fix clean tmp dir (#32360) (#32593)
Backport #32360
Try to fix #31792
Credit to @jeroenlaylo
Copied from
https://github.com/go-gitea/gitea/issues/31792#issuecomment-2311920520
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
-rw-r--r-- | modules/git/repo_index.go | 36 |
1 files changed, 23 insertions, 13 deletions
diff --git a/modules/git/repo_index.go b/modules/git/repo_index.go index 8390570098..f45b6e6191 100644 --- a/modules/git/repo_index.go +++ b/modules/git/repo_index.go @@ -50,25 +50,35 @@ func (repo *Repository) readTreeToIndex(id ObjectID, indexFilename ...string) er } // ReadTreeToTemporaryIndex reads a treeish to a temporary index file -func (repo *Repository) ReadTreeToTemporaryIndex(treeish string) (filename, tmpDir string, cancel context.CancelFunc, err error) { +func (repo *Repository) ReadTreeToTemporaryIndex(treeish string) (tmpIndexFilename, tmpDir string, cancel context.CancelFunc, err error) { + defer func() { + // if error happens and there is a cancel function, do clean up + if err != nil && cancel != nil { + cancel() + cancel = nil + } + }() + + removeDirFn := func(dir string) func() { // it can't use the return value "tmpDir" directly because it is empty when error occurs + return func() { + if err := util.RemoveAll(dir); err != nil { + log.Error("failed to remove tmp index dir: %v", err) + } + } + } + tmpDir, err = os.MkdirTemp("", "index") if err != nil { - return filename, tmpDir, cancel, err + return "", "", nil, err } - filename = filepath.Join(tmpDir, ".tmp-index") - cancel = func() { - err := util.RemoveAll(tmpDir) - if err != nil { - log.Error("failed to remove tmp index file: %v", err) - } - } - err = repo.ReadTreeToIndex(treeish, filename) + tmpIndexFilename = filepath.Join(tmpDir, ".tmp-index") + cancel = removeDirFn(tmpDir) + err = repo.ReadTreeToIndex(treeish, tmpIndexFilename) if err != nil { - defer cancel() - return "", "", func() {}, err + return "", "", cancel, err } - return filename, tmpDir, cancel, err + return tmpIndexFilename, tmpDir, cancel, err } // EmptyIndex empties the index |