Template
1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo synced 2024-11-25 19:26:09 +01:00

Fix clean tmp dir (#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>
(cherry picked from commit feca8802b85dd75090c533ebdb92835d3d529f17)
This commit is contained in:
Lunny Xiao 2024-10-29 09:27:03 -07:00 committed by Gergely Nagy
parent 643f476e35
commit 42724b09c1
No known key found for this signature in database

View file

@ -50,25 +50,35 @@ func (repo *Repository) readTreeToIndex(id ObjectID, indexFilename ...string) er
} }
// ReadTreeToTemporaryIndex reads a treeish to a temporary index file // 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) {
tmpDir, err = os.MkdirTemp("", "index") defer func() {
if err != nil { // if error happens and there is a cancel function, do clean up
return filename, tmpDir, cancel, err 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)
}
}
} }
filename = filepath.Join(tmpDir, ".tmp-index") tmpDir, err = os.MkdirTemp("", "index")
cancel = func() {
err := util.RemoveAll(tmpDir)
if err != nil { if err != nil {
log.Error("failed to remove tmp index file: %v", err) return "", "", nil, err
} }
}
err = repo.ReadTreeToIndex(treeish, filename) tmpIndexFilename = filepath.Join(tmpDir, ".tmp-index")
cancel = removeDirFn(tmpDir)
err = repo.ReadTreeToIndex(treeish, tmpIndexFilename)
if err != nil { if err != nil {
defer cancel() return "", "", cancel, err
return "", "", func() {}, err
} }
return filename, tmpDir, cancel, err return tmpIndexFilename, tmpDir, cancel, err
} }
// EmptyIndex empties the index // EmptyIndex empties the index