]> source.dussan.org Git - gitea.git/commitdiff
Add Close() method to gogitRepository (#8901)
authorzeripath <art27@cantab.net>
Wed, 13 Nov 2019 07:01:19 +0000 (07:01 +0000)
committerGitHub <noreply@github.com>
Wed, 13 Nov 2019 07:01:19 +0000 (07:01 +0000)
In investigating #7947 it has become clear that the storage component of go-git repositories needs closing.

This PR adds this Close function and adds the Close functions as necessary.

In TransferOwnership the ctx.Repo.GitRepo is closed if it is open to help prevent the risk of multiple open files.

Fixes #7947

75 files changed:
cmd/admin.go
docs/content/doc/advanced/migrations.en-us.md
integrations/api_releases_test.go
integrations/api_repo_file_create_test.go
integrations/api_repo_file_update_test.go
integrations/api_repo_get_contents_list_test.go
integrations/api_repo_get_contents_test.go
integrations/api_repo_git_tags_test.go
integrations/repofiles_delete_test.go
integrations/repofiles_update_test.go
models/graph_test.go
models/migrations/v39.go
models/migrations/v82.go
models/pull.go
models/repo.go
models/repo_activity.go
models/repo_branch.go
models/repo_sign.go
models/repo_tag.go [deleted file]
models/wiki.go
models/wiki_test.go
modules/context/api.go
modules/context/repo.go
modules/git/blame.go
modules/git/blob_test.go
modules/git/commit_info_test.go
modules/git/notes_test.go
modules/git/repo.go
modules/git/repo_blob_test.go
modules/git/repo_branch.go
modules/git/repo_branch_test.go
modules/git/repo_commit_test.go
modules/git/repo_compare_test.go
modules/git/repo_ref_test.go
modules/git/repo_stats_test.go
modules/git/repo_tag_test.go
modules/git/repo_test.go
modules/git/tree_entry_test.go
modules/migrations/base/uploader.go
modules/migrations/gitea.go
modules/migrations/migrate.go
modules/notification/webhook/webhook.go
modules/repofiles/action.go
modules/repofiles/blob.go
modules/repofiles/blob_test.go
modules/repofiles/commit_status.go
modules/repofiles/content.go
modules/repofiles/content_test.go
modules/repofiles/diff_test.go
modules/repofiles/file_test.go
modules/repofiles/temp_repo.go
modules/repofiles/tree.go
modules/repofiles/tree_test.go
modules/repofiles/update.go
modules/test/context_tests.go
routers/api/v1/api.go
routers/api/v1/repo/commits.go
routers/api/v1/repo/file.go
routers/api/v1/repo/git_ref.go
routers/api/v1/repo/pull.go
routers/api/v1/repo/tag.go
routers/repo/compare.go
routers/repo/editor_test.go
routers/repo/pull.go
routers/repo/release_test.go
routers/repo/setting.go
routers/repo/wiki.go
routers/repo/wiki_test.go
services/comments/comments.go
services/gitdiff/gitdiff.go
services/mirror/mirror.go
services/mirror/mirror_test.go
services/pull/commit_status.go
services/pull/pull.go
services/release/release_test.go

index 83ced76c966f83f68884e92d795144d1e13c4848..1e41a0af6cc9ae0bb9a4d745acb3151f03f3825c 100644 (file)
@@ -375,17 +375,20 @@ func runRepoSyncReleases(c *cli.Context) error {
 
                        if err = models.SyncReleasesWithTags(repo, gitRepo); err != nil {
                                log.Warn(" SyncReleasesWithTags: %v", err)
+                               gitRepo.Close()
                                continue
                        }
 
                        count, err = getReleaseCount(repo.ID)
                        if err != nil {
                                log.Warn(" GetReleaseCountByRepoID: %v", err)
+                               gitRepo.Close()
                                continue
                        }
 
                        log.Trace(" repo %s releases synchronized to tags: from %d to %d",
                                repo.FullName(), oldnum, count)
+                       gitRepo.Close()
                }
        }
 
index 2511f7af8985aca6e17047526ada7d97f170e989..0d9d8b49a77bcf6c12d31f87a6ce25f83b0d5bdb 100644 (file)
@@ -68,6 +68,7 @@ type Uploader interface {
        CreateComment(issueNumber int64, comment *Comment) error
        CreatePullRequest(pr *PullRequest) error
        Rollback() error
+       Close()
 }
 
-```
\ No newline at end of file
+```
index 897f863eb3e03a12fb6ce688e43277b1cb1daaa7..8025f1de5d59bb5742fe734efb1b7b8f5d473e97 100644 (file)
@@ -51,6 +51,7 @@ func TestAPICreateAndUpdateRelease(t *testing.T) {
 
        gitRepo, err := git.OpenRepository(repo.RepoPath())
        assert.NoError(t, err)
+       defer gitRepo.Close()
 
        err = gitRepo.CreateTag("v0.0.1", "master")
        assert.NoError(t, err)
@@ -112,6 +113,7 @@ func TestAPICreateReleaseToDefaultBranchOnExistingTag(t *testing.T) {
 
        gitRepo, err := git.OpenRepository(repo.RepoPath())
        assert.NoError(t, err)
+       defer gitRepo.Close()
 
        err = gitRepo.CreateTag("v0.0.1", "master")
        assert.NoError(t, err)
index 4d76ff00ceb694c38f5429487ca1f0a6489de236..eb437edf03f9a87f0c88f58f4a1fc5308cff60c7 100644 (file)
@@ -139,6 +139,7 @@ func TestAPICreateFile(t *testing.T) {
                        assert.EqualValues(t, expectedFileResponse.Commit.HTMLURL, fileResponse.Commit.HTMLURL)
                        assert.EqualValues(t, expectedFileResponse.Commit.Author.Email, fileResponse.Commit.Author.Email)
                        assert.EqualValues(t, expectedFileResponse.Commit.Author.Name, fileResponse.Commit.Author.Name)
+                       gitRepo.Close()
                }
 
                // Test creating a file in a new branch
index bf695d4344c3ff3b16f8722ce2436813d4228eac..236cb8eb30884ff3790d1a2c16e149ba21aeee5f 100644 (file)
@@ -143,6 +143,7 @@ func TestAPIUpdateFile(t *testing.T) {
                        assert.EqualValues(t, expectedFileResponse.Commit.HTMLURL, fileResponse.Commit.HTMLURL)
                        assert.EqualValues(t, expectedFileResponse.Commit.Author.Email, fileResponse.Commit.Author.Email)
                        assert.EqualValues(t, expectedFileResponse.Commit.Author.Name, fileResponse.Commit.Author.Name)
+                       gitRepo.Close()
                }
 
                // Test updating a file in a new branch
index f74ceb514a0bc788d5012cb15ed2da0c2b686e57..4605ccf4d933bc1a13ac02eb8a68136dcf5ed5bd 100644 (file)
@@ -74,6 +74,8 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) {
        repo1.CreateNewBranch(user2, repo1.DefaultBranch, newBranch)
        // Get the commit ID of the default branch
        gitRepo, _ := git.OpenRepository(repo1.RepoPath())
+       defer gitRepo.Close()
+
        commitID, _ := gitRepo.GetBranchCommitID(repo1.DefaultBranch)
        // Make a new tag in repo1
        newTag := "test_tag"
index f6a43bc5c63f2a4f4a53ca21c5cda89d67dc1945..77a827ec6125b863dad5cf933ded188ed541713a 100644 (file)
@@ -75,6 +75,8 @@ func testAPIGetContents(t *testing.T, u *url.URL) {
        repo1.CreateNewBranch(user2, repo1.DefaultBranch, newBranch)
        // Get the commit ID of the default branch
        gitRepo, _ := git.OpenRepository(repo1.RepoPath())
+       defer gitRepo.Close()
+
        commitID, _ := gitRepo.GetBranchCommitID(repo1.DefaultBranch)
        // Make a new tag in repo1
        newTag := "test_tag"
index ae519249e03b0cc82a35da6eb74db1deeed0584e..d6ff08990a37a5cc1cb7ed4c8f86d5890ec4be8f 100644 (file)
@@ -29,6 +29,8 @@ func TestAPIGitTags(t *testing.T) {
        git.NewCommand("config", "user.email", user.Email).RunInDir(repo.RepoPath())
 
        gitRepo, _ := git.OpenRepository(repo.RepoPath())
+       defer gitRepo.Close()
+
        commit, _ := gitRepo.GetBranchCommit("master")
        lTagName := "lightweightTag"
        gitRepo.CreateTag(lTagName, commit.ID.String())
index b4c535188bc66d4c666ff0607b17c319bfc734ba..754f64023ff6e03ad73ac497040f0473281363d1 100644 (file)
@@ -73,6 +73,7 @@ func testDeleteRepoFile(t *testing.T, u *url.URL) {
        test.LoadRepoCommit(t, ctx)
        test.LoadUser(t, ctx, 2)
        test.LoadGitRepo(t, ctx)
+       defer ctx.Repo.GitRepo.Close()
        repo := ctx.Repo.Repository
        doer := ctx.User
        opts := getDeleteRepoFileOptions(repo)
@@ -111,6 +112,8 @@ func testDeleteRepoFileWithoutBranchNames(t *testing.T, u *url.URL) {
        test.LoadRepoCommit(t, ctx)
        test.LoadUser(t, ctx, 2)
        test.LoadGitRepo(t, ctx)
+       defer ctx.Repo.GitRepo.Close()
+
        repo := ctx.Repo.Repository
        doer := ctx.User
        opts := getDeleteRepoFileOptions(repo)
@@ -139,6 +142,8 @@ func TestDeleteRepoFileErrors(t *testing.T) {
        test.LoadRepoCommit(t, ctx)
        test.LoadUser(t, ctx, 2)
        test.LoadGitRepo(t, ctx)
+       defer ctx.Repo.GitRepo.Close()
+
        repo := ctx.Repo.Repository
        doer := ctx.User
 
index c475c70008ff1c59a4e7dbb400ee8ad4abab1982..35cb5e8b0cb1875c353a9b1b8a1e3536954173cd 100644 (file)
@@ -191,6 +191,8 @@ func TestCreateOrUpdateRepoFileForCreate(t *testing.T) {
                test.LoadRepoCommit(t, ctx)
                test.LoadUser(t, ctx, 2)
                test.LoadGitRepo(t, ctx)
+               defer ctx.Repo.GitRepo.Close()
+
                repo := ctx.Repo.Repository
                doer := ctx.User
                opts := getCreateRepoFileOptions(repo)
@@ -201,6 +203,8 @@ func TestCreateOrUpdateRepoFileForCreate(t *testing.T) {
                // asserts
                assert.Nil(t, err)
                gitRepo, _ := git.OpenRepository(repo.RepoPath())
+               defer gitRepo.Close()
+
                commitID, _ := gitRepo.GetBranchCommitID(opts.NewBranch)
                expectedFileResponse := getExpectedFileResponseForRepofilesCreate(commitID)
                assert.EqualValues(t, expectedFileResponse.Content, fileResponse.Content)
@@ -220,6 +224,8 @@ func TestCreateOrUpdateRepoFileForUpdate(t *testing.T) {
                test.LoadRepoCommit(t, ctx)
                test.LoadUser(t, ctx, 2)
                test.LoadGitRepo(t, ctx)
+               defer ctx.Repo.GitRepo.Close()
+
                repo := ctx.Repo.Repository
                doer := ctx.User
                opts := getUpdateRepoFileOptions(repo)
@@ -230,6 +236,8 @@ func TestCreateOrUpdateRepoFileForUpdate(t *testing.T) {
                // asserts
                assert.Nil(t, err)
                gitRepo, _ := git.OpenRepository(repo.RepoPath())
+               defer gitRepo.Close()
+
                commitID, _ := gitRepo.GetBranchCommitID(opts.NewBranch)
                expectedFileResponse := getExpectedFileResponseForRepofilesUpdate(commitID, opts.TreePath)
                assert.EqualValues(t, expectedFileResponse.Content, fileResponse.Content)
@@ -249,6 +257,8 @@ func TestCreateOrUpdateRepoFileForUpdateWithFileMove(t *testing.T) {
                test.LoadRepoCommit(t, ctx)
                test.LoadUser(t, ctx, 2)
                test.LoadGitRepo(t, ctx)
+               defer ctx.Repo.GitRepo.Close()
+
                repo := ctx.Repo.Repository
                doer := ctx.User
                opts := getUpdateRepoFileOptions(repo)
@@ -261,6 +271,8 @@ func TestCreateOrUpdateRepoFileForUpdateWithFileMove(t *testing.T) {
                // asserts
                assert.Nil(t, err)
                gitRepo, _ := git.OpenRepository(repo.RepoPath())
+               defer gitRepo.Close()
+
                commit, _ := gitRepo.GetBranchCommit(opts.NewBranch)
                expectedFileResponse := getExpectedFileResponseForRepofilesUpdate(commit.ID.String(), opts.TreePath)
                // assert that the old file no longer exists in the last commit of the branch
@@ -288,6 +300,8 @@ func TestCreateOrUpdateRepoFileWithoutBranchNames(t *testing.T) {
                test.LoadRepoCommit(t, ctx)
                test.LoadUser(t, ctx, 2)
                test.LoadGitRepo(t, ctx)
+               defer ctx.Repo.GitRepo.Close()
+
                repo := ctx.Repo.Repository
                doer := ctx.User
                opts := getUpdateRepoFileOptions(repo)
@@ -300,6 +314,8 @@ func TestCreateOrUpdateRepoFileWithoutBranchNames(t *testing.T) {
                // asserts
                assert.Nil(t, err)
                gitRepo, _ := git.OpenRepository(repo.RepoPath())
+               defer gitRepo.Close()
+
                commitID, _ := gitRepo.GetBranchCommitID(repo.DefaultBranch)
                expectedFileResponse := getExpectedFileResponseForRepofilesUpdate(commitID, opts.TreePath)
                assert.EqualValues(t, expectedFileResponse.Content, fileResponse.Content)
@@ -315,6 +331,8 @@ func TestCreateOrUpdateRepoFileErrors(t *testing.T) {
                test.LoadRepoCommit(t, ctx)
                test.LoadUser(t, ctx, 2)
                test.LoadGitRepo(t, ctx)
+               defer ctx.Repo.GitRepo.Close()
+
                repo := ctx.Repo.Repository
                doer := ctx.User
 
index c1f0bc90d954d73285f7fd731fca4a42f56ca984..78bfcb27ec6e01785abc88d73a60b945f8cc03c9 100644 (file)
@@ -17,6 +17,7 @@ func BenchmarkGetCommitGraph(b *testing.B) {
        if err != nil {
                b.Error("Could not open repository")
        }
+       defer currentRepo.Close()
 
        for i := 0; i < b.N; i++ {
                graph, err := GetCommitGraph(currentRepo, 1)
index f3b32ea873d204358f8c7018474692675e221331..dc5f6ee091f318ed88e826665c411db1393997b1 100644 (file)
@@ -47,6 +47,7 @@ func releaseAddColumnIsTagAndSyncTags(x *xorm.Engine) error {
                        if err = models.SyncReleasesWithTags(repo, gitRepo); err != nil {
                                log.Warn("SyncReleasesWithTags: %v", err)
                        }
+                       gitRepo.Close()
                }
                if len(repos) < pageSize {
                        break
index 3fb4b6c59e6b8118474313750206e6ad81559dec..2daa86ab07338f0805aa327c5e399569a18ff08e 100644 (file)
@@ -91,6 +91,7 @@ func fixReleaseSha1OnReleaseTable(x *xorm.Engine) error {
                                if err != nil {
                                        return err
                                }
+                               defer gitRepo.Close()
                                gitRepoCache[release.RepoID] = gitRepo
                        }
 
index 45a1daac467f9216f3b827951cb102c7e91e1ed5..b25c52571d77e9b55559381ee7404ca11b92be4b 100644 (file)
@@ -380,6 +380,7 @@ func (pr *PullRequest) GetLastCommitStatus() (status *CommitStatus, err error) {
        if err != nil {
                return nil, err
        }
+       defer headGitRepo.Close()
 
        lastCommitID, err := headGitRepo.GetBranchCommitID(pr.HeadBranch)
        if err != nil {
@@ -569,6 +570,7 @@ func (pr *PullRequest) getMergeCommit() (*git.Commit, error) {
        if err != nil {
                return nil, fmt.Errorf("OpenRepository: %v", err)
        }
+       defer gitRepo.Close()
 
        commit, err := gitRepo.GetCommit(mergeCommit[:40])
        if err != nil {
@@ -870,6 +872,7 @@ func (pr *PullRequest) UpdatePatch() (err error) {
        if err != nil {
                return fmt.Errorf("OpenRepository: %v", err)
        }
+       defer headGitRepo.Close()
 
        // Add a temporary remote.
        tmpRemote := com.ToStr(time.Now().UnixNano())
@@ -911,6 +914,7 @@ func (pr *PullRequest) PushToBaseRepo() (err error) {
        if err != nil {
                return fmt.Errorf("OpenRepository: %v", err)
        }
+       defer headGitRepo.Close()
 
        tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
        if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
index ccecfe2fdf0ae014150eb75ce1d9ca0d899f5436..a340a391a1310fd31cc4e637c9f27fe8f2437c71 100644 (file)
@@ -1047,6 +1047,7 @@ func MigrateRepositoryGitData(doer, u *User, repo *Repository, opts api.MigrateR
        if err != nil {
                return repo, fmt.Errorf("OpenRepository: %v", err)
        }
+       defer gitRepo.Close()
 
        repo.IsEmpty, err = gitRepo.IsEmpty()
        if err != nil {
index aa5c2217e03e62b92680cb46c29a2e50251f1910..d25524c0578260c3c6178559eede7a4d0da2ae8f 100644 (file)
@@ -64,6 +64,8 @@ func GetActivityStats(repo *Repository, timeFrom time.Time, releases, issues, pr
                if err != nil {
                        return nil, fmt.Errorf("OpenRepository: %v", err)
                }
+               defer gitRepo.Close()
+
                code, err := gitRepo.GetCodeActivityStats(timeFrom, repo.DefaultBranch)
                if err != nil {
                        return nil, fmt.Errorf("FillFromGit: %v", err)
@@ -79,6 +81,8 @@ func GetActivityStatsTopAuthors(repo *Repository, timeFrom time.Time, count int)
        if err != nil {
                return nil, fmt.Errorf("OpenRepository: %v", err)
        }
+       defer gitRepo.Close()
+
        code, err := gitRepo.GetCodeActivityStats(timeFrom, "")
        if err != nil {
                return nil, fmt.Errorf("FillFromGit: %v", err)
index dee6ef3d7e2675f2e21c0bb33d0b4305bb5c8db8..c51323183688d82bcf6acd4b724e4e0d1986fcc3 100644 (file)
@@ -23,6 +23,7 @@ func (repo *Repository) GetBranch(branch string) (*git.Branch, error) {
        if err != nil {
                return nil, err
        }
+       defer gitRepo.Close()
 
        return gitRepo.GetBranch(branch)
 }
@@ -38,6 +39,7 @@ func (repo *Repository) CheckBranchName(name string) error {
        if err != nil {
                return err
        }
+       defer gitRepo.Close()
 
        branches, err := repo.GetBranches()
        if err != nil {
@@ -94,6 +96,7 @@ func (repo *Repository) CreateNewBranch(doer *User, oldBranchName, branchName st
                log.Error("Unable to open temporary repository: %s (%v)", basePath, err)
                return fmt.Errorf("Failed to open new temporary repository in: %s %v", basePath, err)
        }
+       defer gitRepo.Close()
 
        if err = gitRepo.CreateBranch(branchName, oldBranchName); err != nil {
                log.Error("Unable to create branch: %s from %s. (%v)", branchName, oldBranchName, err)
@@ -140,6 +143,7 @@ func (repo *Repository) CreateNewBranchFromCommit(doer *User, commit, branchName
                log.Error("Unable to open temporary repository: %s (%v)", basePath, err)
                return fmt.Errorf("Failed to open new temporary repository in: %s %v", basePath, err)
        }
+       defer gitRepo.Close()
 
        if err = gitRepo.CreateBranch(branchName, commit); err != nil {
                log.Error("Unable to create branch: %s from %s. (%v)", branchName, commit, err)
index bac69f76a894b69c324469cbb75151fcf4e2ae8a..a02b027f89f8929f597ab114d89c8655e90bdfce 100644 (file)
@@ -149,6 +149,7 @@ func (repo *Repository) SignWikiCommit(u *User) (bool, string) {
                        if err != nil {
                                return false, ""
                        }
+                       defer gitRepo.Close()
                        commit, err := gitRepo.GetCommit("HEAD")
                        if err != nil {
                                return false, ""
@@ -194,6 +195,7 @@ func (repo *Repository) SignCRUDAction(u *User, tmpBasePath, parentCommit string
                        if err != nil {
                                return false, ""
                        }
+                       defer gitRepo.Close()
                        commit, err := gitRepo.GetCommit(parentCommit)
                        if err != nil {
                                return false, ""
@@ -242,6 +244,7 @@ func (repo *Repository) SignMerge(u *User, tmpBasePath, baseCommit, headCommit s
                                if err != nil {
                                        return false, ""
                                }
+                               defer gitRepo.Close()
                        }
                        commit, err := gitRepo.GetCommit(baseCommit)
                        if err != nil {
@@ -257,6 +260,7 @@ func (repo *Repository) SignMerge(u *User, tmpBasePath, baseCommit, headCommit s
                                if err != nil {
                                        return false, ""
                                }
+                               defer gitRepo.Close()
                        }
                        commit, err := gitRepo.GetCommit(headCommit)
                        if err != nil {
@@ -272,6 +276,7 @@ func (repo *Repository) SignMerge(u *User, tmpBasePath, baseCommit, headCommit s
                                if err != nil {
                                        return false, ""
                                }
+                               defer gitRepo.Close()
                        }
                        commit, err := gitRepo.GetCommit(headCommit)
                        if err != nil {
diff --git a/models/repo_tag.go b/models/repo_tag.go
deleted file mode 100644 (file)
index 3864b7a..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright 2019 The Gitea Authors. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package models
-
-import (
-       "code.gitea.io/gitea/modules/git"
-)
-
-// GetTagsByPath returns repo tags by its path
-func GetTagsByPath(path string) ([]*git.Tag, error) {
-       gitRepo, err := git.OpenRepository(path)
-       if err != nil {
-               return nil, err
-       }
-
-       return gitRepo.GetTagInfos()
-}
-
-// GetTags return repo's tags
-func (repo *Repository) GetTags() ([]*git.Tag, error) {
-       return GetTagsByPath(repo.RepoPath())
-}
index 858fe1d6d04a9f17c4c26ebe008e68fa9d0338e1..8b63716afa1f0d8b8f092239bfabf544d8e4ef43 100644 (file)
@@ -140,6 +140,7 @@ func (repo *Repository) updateWikiPage(doer *User, oldWikiName, newWikiName, con
                log.Error("Unable to open temporary repository: %s (%v)", basePath, err)
                return fmt.Errorf("Failed to open new temporary repository in: %s %v", basePath, err)
        }
+       defer gitRepo.Close()
 
        if hasMasterBranch {
                if err := gitRepo.ReadTreeToIndex("HEAD"); err != nil {
@@ -283,6 +284,7 @@ func (repo *Repository) DeleteWikiPage(doer *User, wikiName string) (err error)
                log.Error("Unable to open temporary repository: %s (%v)", basePath, err)
                return fmt.Errorf("Failed to open new temporary repository in: %s %v", basePath, err)
        }
+       defer gitRepo.Close()
 
        if err := gitRepo.ReadTreeToIndex("HEAD"); err != nil {
                log.Error("Unable to read HEAD tree to index in: %s %v", basePath, err)
index 991a3d95b9036e28f9bcdf0ad256369c6b9d0cb8..37c0a86635ea7c44b6ee4e6f74433ffc397f8a1c 100644 (file)
@@ -161,6 +161,7 @@ func TestRepository_AddWikiPage(t *testing.T) {
                        // Now need to show that the page has been added:
                        gitRepo, err := git.OpenRepository(repo.WikiPath())
                        assert.NoError(t, err)
+                       defer gitRepo.Close()
                        masterTree, err := gitRepo.GetTree("master")
                        assert.NoError(t, err)
                        wikiPath := WikiNameToFilename(wikiName)
@@ -214,6 +215,7 @@ func TestRepository_EditWikiPage(t *testing.T) {
                        _, err := masterTree.GetTreeEntryByPath("Home.md")
                        assert.Error(t, err)
                }
+               gitRepo.Close()
        }
 }
 
@@ -226,6 +228,7 @@ func TestRepository_DeleteWikiPage(t *testing.T) {
        // Now need to show that the page has been added:
        gitRepo, err := git.OpenRepository(repo.WikiPath())
        assert.NoError(t, err)
+       defer gitRepo.Close()
        masterTree, err := gitRepo.GetTree("master")
        assert.NoError(t, err)
        wikiPath := WikiNameToFilename("Home")
index 024ae487f115627391e81dde628e385046af6b2f..c1de37dd21a09f3f4c0ca472e7f59ba68aedccc8 100644 (file)
@@ -186,7 +186,16 @@ func ReferencesGitRepo(allowEmpty bool) macaron.Handler {
                                return
                        }
                        ctx.Repo.GitRepo = gitRepo
+                       // We opened it, we should close it
+                       defer func() {
+                               // If it's been set to nil then assume someone else has closed it.
+                               if ctx.Repo.GitRepo != nil {
+                                       ctx.Repo.GitRepo.Close()
+                               }
+                       }()
                }
+
+               ctx.Next()
        }
 }
 
index bd3456773fa1aa194843e3a7e1d02eee2605f271..f41505e7acf755431a0f6110debd401ce2e8e1ad 100644 (file)
@@ -454,9 +454,18 @@ func RepoAssignment() macaron.Handler {
                }
                ctx.Repo.GitRepo = gitRepo
 
+               // We opened it, we should close it
+               defer func() {
+                       // If it's been set to nil then assume someone else has closed it.
+                       if ctx.Repo.GitRepo != nil {
+                               ctx.Repo.GitRepo.Close()
+                       }
+               }()
+
                // Stop at this point when the repo is empty.
                if ctx.Repo.Repository.IsEmpty {
                        ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
+                       ctx.Next()
                        return
                }
 
@@ -515,6 +524,7 @@ func RepoAssignment() macaron.Handler {
                        ctx.Data["GoDocDirectory"] = prefix + "{/dir}"
                        ctx.Data["GoDocFile"] = prefix + "{/dir}/{file}#L{line}"
                }
+               ctx.Next()
        }
 }
 
@@ -636,6 +646,13 @@ func RepoRefByType(refType RepoRefType) macaron.Handler {
                                ctx.ServerError("RepoRef Invalid repo "+repoPath, err)
                                return
                        }
+                       // We opened it, we should close it
+                       defer func() {
+                               // If it's been set to nil then assume someone else has closed it.
+                               if ctx.Repo.GitRepo != nil {
+                                       ctx.Repo.GitRepo.Close()
+                               }
+                       }()
                }
 
                // Get default branch.
@@ -724,6 +741,8 @@ func RepoRefByType(refType RepoRefType) macaron.Handler {
                        return
                }
                ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
+
+               ctx.Next()
        }
 }
 
index 548236b65702a1ebeca8bd1ecbcc203324b0c945..4f4343fe964269423436538cfb8877ea21c6358b 100644 (file)
@@ -87,10 +87,11 @@ func (r *BlameReader) Close() error {
 
 // CreateBlameReader creates reader for given repository, commit and file
 func CreateBlameReader(repoPath, commitID, file string) (*BlameReader, error) {
-       _, err := OpenRepository(repoPath)
+       gitRepo, err := OpenRepository(repoPath)
        if err != nil {
                return nil, err
        }
+       gitRepo.Close()
 
        return createBlameReader(repoPath, GitExecutable, "blame", commitID, "--porcelain", "--", file)
 }
index 66c046ecc8d0885760c3623e38a0eee9e44bba47..9043de5955f497af9f50558505351c476cab0e8e 100644 (file)
@@ -37,6 +37,8 @@ THE SOFTWARE.
 `
        repo, err := OpenRepository("../../.git")
        assert.NoError(t, err)
+       defer repo.Close()
+
        testBlob, err := repo.GetBlob("a8d4b49dd073a4a38a7e58385eeff7cc52568697")
        assert.NoError(t, err)
 
@@ -55,6 +57,8 @@ func Benchmark_Blob_Data(b *testing.B) {
        if err != nil {
                b.Fatal(err)
        }
+       defer repo.Close()
+
        testBlob, err := repo.GetBlob("a8d4b49dd073a4a38a7e58385eeff7cc52568697")
        if err != nil {
                b.Fatal(err)
index 71637d188aaa148e5f28a71e7241b9f8bae4e900..ac7bc43c4e214e3966e0a45f692d0675b7aa19bf 100644 (file)
@@ -77,6 +77,8 @@ func TestEntries_GetCommitsInfo(t *testing.T) {
        bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
        bareRepo1, err := OpenRepository(bareRepo1Path)
        assert.NoError(t, err)
+       defer bareRepo1.Close()
+
        testGetCommitsInfo(t, bareRepo1)
 
        clonedPath, err := cloneRepo(bareRepo1Path, testReposDir, "repo1_TestEntries_GetCommitsInfo")
@@ -84,6 +86,8 @@ func TestEntries_GetCommitsInfo(t *testing.T) {
        defer os.RemoveAll(clonedPath)
        clonedRepo1, err := OpenRepository(clonedPath)
        assert.NoError(t, err)
+       defer clonedRepo1.Close()
+
        testGetCommitsInfo(t, clonedRepo1)
 }
 
@@ -101,13 +105,16 @@ func BenchmarkEntries_GetCommitsInfo(b *testing.B) {
        for _, benchmark := range benchmarks {
                var commit *Commit
                var entries Entries
+               var repo *Repository
                if repoPath, err := cloneRepo(benchmark.url, benchmarkReposDir, benchmark.name); err != nil {
                        b.Fatal(err)
-               } else if repo, err := OpenRepository(repoPath); err != nil {
+               } else if repo, err = OpenRepository(repoPath); err != nil {
                        b.Fatal(err)
                } else if commit, err = repo.GetBranchCommit("master"); err != nil {
+                       repo.Close()
                        b.Fatal(err)
                } else if entries, err = commit.Tree.ListEntries(); err != nil {
+                       repo.Close()
                        b.Fatal(err)
                }
                entries.Sort()
@@ -120,5 +127,6 @@ func BenchmarkEntries_GetCommitsInfo(b *testing.B) {
                                }
                        }
                })
+               repo.Close()
        }
 }
index bf010b9a712aad6896522d385ae847b990a68471..b7939e691355af76428c62d4261494a6a87bc43e 100644 (file)
@@ -15,6 +15,7 @@ func TestGetNotes(t *testing.T) {
        bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
        bareRepo1, err := OpenRepository(bareRepo1Path)
        assert.NoError(t, err)
+       defer bareRepo1.Close()
 
        note := Note{}
        err = GetNote(bareRepo1, "95bb4d39648ee7e325106df01a621c530863a653", &note)
@@ -27,6 +28,7 @@ func TestGetNestedNotes(t *testing.T) {
        repoPath := filepath.Join(testReposDir, "repo3_notes")
        repo, err := OpenRepository(repoPath)
        assert.NoError(t, err)
+       defer repo.Close()
 
        note := Note{}
        err = GetNote(repo, "3e668dbfac39cbc80a9ff9c61eb565d944453ba4", &note)
index 80f61097724e63bdffc03f716759297a61d8db90..ffca2524be1feea9d7bebd4ff5df5e11cf213597 100644 (file)
@@ -17,6 +17,7 @@ import (
        "strings"
        "time"
 
+       gitealog "code.gitea.io/gitea/modules/log"
        "github.com/unknwon/com"
        "gopkg.in/src-d/go-billy.v4/osfs"
        gogit "gopkg.in/src-d/go-git.v4"
@@ -122,6 +123,16 @@ func OpenRepository(repoPath string) (*Repository, error) {
        }, nil
 }
 
+// Close this repository, in particular close the underlying gogitStorage if this is not nil
+func (repo *Repository) Close() {
+       if repo == nil || repo.gogitStorage == nil {
+               return
+       }
+       if err := repo.gogitStorage.Close(); err != nil {
+               gitealog.Error("Error closing storage: %v", err)
+       }
+}
+
 // GoGitRepo gets the go-git repo representation
 func (repo *Repository) GoGitRepo() *gogit.Repository {
        return repo.gogitRepo
index 128a227829c1cbff73b14a7a9adc00c1e0fa191d..52a124db2a75002ce164ab891d688564554d1465 100644 (file)
@@ -17,6 +17,7 @@ func TestRepository_GetBlob_Found(t *testing.T) {
        repoPath := filepath.Join(testReposDir, "repo1_bare")
        r, err := OpenRepository(repoPath)
        assert.NoError(t, err)
+       defer r.Close()
 
        testCases := []struct {
                OID  string
@@ -44,6 +45,7 @@ func TestRepository_GetBlob_NotExist(t *testing.T) {
        repoPath := filepath.Join(testReposDir, "repo1_bare")
        r, err := OpenRepository(repoPath)
        assert.NoError(t, err)
+       defer r.Close()
 
        testCase := "0000000000000000000000000000000000000000"
        testError := ErrNotExist{testCase, ""}
@@ -57,6 +59,7 @@ func TestRepository_GetBlob_NoId(t *testing.T) {
        repoPath := filepath.Join(testReposDir, "repo1_bare")
        r, err := OpenRepository(repoPath)
        assert.NoError(t, err)
+       defer r.Close()
 
        testCase := ""
        testError := fmt.Errorf("Length must be 40: %s", testCase)
index a2bf9ac973e49d03679c9758fe781700799f99b3..e79bab76a6f30a7a25cffb31dc206a6bf47d493b 100644 (file)
@@ -108,6 +108,7 @@ func GetBranchesByPath(path string) ([]*Branch, error) {
        if err != nil {
                return nil, err
        }
+       defer gitRepo.Close()
 
        brs, err := gitRepo.GetBranches()
        if err != nil {
index 08736d702e21169a1859d2c1e253c8f6fec717b9..33d31aef686de12ca20a6ea1c8db7f060d37c197 100644 (file)
@@ -15,6 +15,7 @@ func TestRepository_GetBranches(t *testing.T) {
        bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
        bareRepo1, err := OpenRepository(bareRepo1Path)
        assert.NoError(t, err)
+       defer bareRepo1.Close()
 
        branches, err := bareRepo1.GetBranches()
 
@@ -29,6 +30,7 @@ func BenchmarkRepository_GetBranches(b *testing.B) {
        if err != nil {
                b.Fatal(err)
        }
+       defer bareRepo1.Close()
 
        for i := 0; i < b.N; i++ {
                _, err := bareRepo1.GetBranches()
index 6d8ee6453f5a115a0315d0b933e9dead3f292a76..87dd6763b3944d08255de153e7a2b5c06ff2abd3 100644 (file)
@@ -15,6 +15,7 @@ func TestRepository_GetCommitBranches(t *testing.T) {
        bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
        bareRepo1, err := OpenRepository(bareRepo1Path)
        assert.NoError(t, err)
+       defer bareRepo1.Close()
 
        // these test case are specific to the repo1_bare test repo
        testCases := []struct {
@@ -41,6 +42,7 @@ func TestGetTagCommitWithSignature(t *testing.T) {
        bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
        bareRepo1, err := OpenRepository(bareRepo1Path)
        assert.NoError(t, err)
+       defer bareRepo1.Close()
 
        commit, err := bareRepo1.GetCommit("3ad28a9149a2864384548f3d17ed7f38014c9e8a")
        assert.NoError(t, err)
@@ -54,6 +56,7 @@ func TestGetCommitWithBadCommitID(t *testing.T) {
        bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
        bareRepo1, err := OpenRepository(bareRepo1Path)
        assert.NoError(t, err)
+       defer bareRepo1.Close()
 
        commit, err := bareRepo1.GetCommit("bad_branch")
        assert.Nil(t, commit)
index e19478877341f353a43e90878a2c44144c0c7553..def67fa87b7f3e1312628b73dfef4048f9c2fffa 100644 (file)
@@ -20,6 +20,7 @@ func TestGetFormatPatch(t *testing.T) {
        defer os.RemoveAll(clonedPath)
        repo, err := OpenRepository(clonedPath)
        assert.NoError(t, err)
+       defer repo.Close()
        rd, err := repo.GetFormatPatch("8d92fc95^", "8d92fc95")
        assert.NoError(t, err)
        patchb, err := ioutil.ReadAll(rd)
index d32b34994c3916ab3ca6a3128bbf21ec88fc4b55..303c496c1ddfa900ef0bb2c38aca9b3f2860cf3b 100644 (file)
@@ -15,6 +15,7 @@ func TestRepository_GetRefs(t *testing.T) {
        bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
        bareRepo1, err := OpenRepository(bareRepo1Path)
        assert.NoError(t, err)
+       defer bareRepo1.Close()
 
        refs, err := bareRepo1.GetRefs()
 
@@ -38,6 +39,7 @@ func TestRepository_GetRefsFiltered(t *testing.T) {
        bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
        bareRepo1, err := OpenRepository(bareRepo1Path)
        assert.NoError(t, err)
+       defer bareRepo1.Close()
 
        refs, err := bareRepo1.GetRefsFiltered(TagPrefix)
 
index 6fbcb7ac13c0f2a6fbc852a362eb4c6bac22c80d..bc1f6a566262b2fe45fb392086484c1456f2cb33 100644 (file)
@@ -16,6 +16,7 @@ func TestRepository_GetCodeActivityStats(t *testing.T) {
        bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
        bareRepo1, err := OpenRepository(bareRepo1Path)
        assert.NoError(t, err)
+       defer bareRepo1.Close()
 
        timeFrom, err := time.Parse(time.RFC3339, "2016-01-01T00:00:00+00:00")
        assert.NoError(t, err)
index ab9742afc5963128911d43f091915cc6ac88abe7..90f2b37358d774e8fd82a960d958306639e1e4f7 100644 (file)
@@ -16,6 +16,7 @@ func TestRepository_GetTags(t *testing.T) {
        bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
        bareRepo1, err := OpenRepository(bareRepo1Path)
        assert.NoError(t, err)
+       defer bareRepo1.Close()
 
        tags, err := bareRepo1.GetTagInfos()
        assert.NoError(t, err)
@@ -34,6 +35,7 @@ func TestRepository_GetTag(t *testing.T) {
 
        bareRepo1, err := OpenRepository(clonedPath)
        assert.NoError(t, err)
+       defer bareRepo1.Close()
 
        lTagCommitID := "6fbd69e9823458e6c4a2fc5c0f6bc022b2f2acd1"
        lTagName := "lightweightTag"
@@ -83,6 +85,7 @@ func TestRepository_GetAnnotatedTag(t *testing.T) {
 
        bareRepo1, err := OpenRepository(clonedPath)
        assert.NoError(t, err)
+       defer bareRepo1.Close()
 
        lTagCommitID := "6fbd69e9823458e6c4a2fc5c0f6bc022b2f2acd1"
        lTagName := "lightweightTag"
index 15f5e3781c0507fa80ad5df3cd769b5c18aaec33..0b6986764c05d2c7e50e80f3696b68310e09cc87 100644 (file)
@@ -30,6 +30,7 @@ func TestRepoIsEmpty(t *testing.T) {
        emptyRepo2Path := filepath.Join(testReposDir, "repo2_empty")
        repo, err := OpenRepository(emptyRepo2Path)
        assert.NoError(t, err)
+       defer repo.Close()
        isEmpty, err := repo.IsEmpty()
        assert.NoError(t, err)
        assert.True(t, isEmpty)
index c65a691ecf20327ad2f736d30d4701f633dbb4e8..e8729003703e1fee1a88fb117304383a08fdddea 100644 (file)
@@ -56,6 +56,7 @@ func TestEntriesCustomSort(t *testing.T) {
 func TestFollowLink(t *testing.T) {
        r, err := OpenRepository("tests/repos/repo1_bare")
        assert.NoError(t, err)
+       defer r.Close()
 
        commit, err := r.GetCommit("37991dec2c8e592043f47155ce4808d4580f9123")
        assert.NoError(t, err)
index a3a9c9fac619b9ab119269cee9d1302dbce405ab..ae1be84b88a9742f90174ba5102915c913548e85 100644 (file)
@@ -17,4 +17,5 @@ type Uploader interface {
        CreateComments(comments ...*Comment) error
        CreatePullRequests(prs ...*PullRequest) error
        Rollback() error
+       Close()
 }
index 676667b426aad518d4df3fcce2fd303fc4abbd9e..81a6116a237d12e726dc037739773891d081ca62 100644 (file)
@@ -131,6 +131,13 @@ func (g *GiteaLocalUploader) CreateRepo(repo *base.Repository, opts base.Migrate
        return err
 }
 
+// Close closes this uploader
+func (g *GiteaLocalUploader) Close() {
+       if g.gitRepo != nil {
+               g.gitRepo.Close()
+       }
+}
+
 // CreateTopics creates topics
 func (g *GiteaLocalUploader) CreateTopics(topics ...string) error {
        return models.SaveTopics(g.repo.ID, topics...)
index bbc1dc2d56107f2baa61a3a00f4f98ec4c6b02fc..7a5071e1258dd7b0684786aa2ebddecbf09b9f85 100644 (file)
@@ -94,6 +94,7 @@ func migrateRepository(downloader base.Downloader, uploader base.Uploader, opts
        if err := uploader.CreateRepo(repo, opts); err != nil {
                return err
        }
+       defer uploader.Close()
 
        log.Trace("migrating topics")
        topics, err := downloader.GetTopics()
index 27afbba7ab81e962829789a3cda7e6de3afb9367..43be0d2e1cb400254e7fb4732442227a4efc0569 100644 (file)
@@ -575,9 +575,11 @@ func (m *webhookNotifier) NotifyCreateRef(pusher *models.User, repo *models.Repo
 
        shaSum, err := gitRepo.GetRefCommitID(refFullName)
        if err != nil {
+               gitRepo.Close()
                log.Error("GetRefCommitID[%s]: %v", refFullName, err)
                return
        }
+       gitRepo.Close()
 
        if err = webhook_module.PrepareWebhooks(repo, models.HookEventCreate, &api.CreatePayload{
                Ref:     refName,
index 996363863d9a41b23e6f8efde9bc2290271c532b..8b35cba7260ee6ddb539bf0e87a2f4fb5c5f0eef 100644 (file)
@@ -53,9 +53,11 @@ func CommitRepoAction(opts CommitRepoActionOptions) error {
                        }
                        if err := gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
                                if !git.IsErrUnsupportedVersion(err) {
+                                       gitRepo.Close()
                                        return err
                                }
                        }
+                       gitRepo.Close()
                }
        }
 
index e9d85a0dcf25dc86b12798aa5b863f810f493842..60a05e280e8641d6efd866c67f9abe0cf3b6a248 100644 (file)
@@ -17,6 +17,7 @@ func GetBlobBySHA(repo *models.Repository, sha string) (*api.GitBlobResponse, er
        if err != nil {
                return nil, err
        }
+       defer gitRepo.Close()
        gitBlob, err := gitRepo.GetBlob(sha)
        if err != nil {
                return nil, err
index 1dc183a8afb30a6d525ee406b32b1bb09bfbe804..ddc23aeac3518ff6f2f96a1f5be7ff5938c0c078 100644 (file)
@@ -21,6 +21,8 @@ func TestGetBlobBySHA(t *testing.T) {
        test.LoadRepoCommit(t, ctx)
        test.LoadUser(t, ctx, 2)
        test.LoadGitRepo(t, ctx)
+       defer ctx.Repo.GitRepo.Close()
+
        sha := "65f1bf27bc3bf70f64657658635e66094edbcb4d"
        ctx.SetParams(":id", "1")
        ctx.SetParams(":sha", sha)
index f3dfbf209f7ddd6345bf6178b0b0258fea91b42f..3d93c58d8582c76f002f9fbc1a01552fc767e616 100644 (file)
@@ -23,8 +23,10 @@ func CreateCommitStatus(repo *models.Repository, creator *models.User, sha strin
                return fmt.Errorf("OpenRepository[%s]: %v", repoPath, err)
        }
        if _, err := gitRepo.GetCommit(sha); err != nil {
+               gitRepo.Close()
                return fmt.Errorf("GetCommit[%s]: %v", sha, err)
        }
+       gitRepo.Close()
 
        if err := models.NewCommitStatus(models.NewCommitStatusOptions{
                Repo:         repo,
index d7d43ef9d1661b8ed870dcb71276f77f1660f013..aed98c33a8c4a66c392670cf370a451935c68239 100644 (file)
@@ -59,6 +59,7 @@ func GetContentsOrList(repo *models.Repository, treePath, ref string) (interface
        if err != nil {
                return nil, err
        }
+       defer gitRepo.Close()
 
        // Get the commit object for the ref
        commit, err := gitRepo.GetCommit(ref)
@@ -117,6 +118,7 @@ func GetContents(repo *models.Repository, treePath, ref string, forList bool) (*
        if err != nil {
                return nil, err
        }
+       defer gitRepo.Close()
 
        // Get the commit object for the ref
        commit, err := gitRepo.GetCommit(ref)
index cd98c54ea69f653fc5d8ea963538b1ee4001254b..d024cfd54982f2238fd68dd111e5f611502f50e0 100644 (file)
@@ -56,6 +56,8 @@ func TestGetContents(t *testing.T) {
        test.LoadRepoCommit(t, ctx)
        test.LoadUser(t, ctx, 2)
        test.LoadGitRepo(t, ctx)
+       defer ctx.Repo.GitRepo.Close()
+
        treePath := "README.md"
        ref := ctx.Repo.Repository.DefaultBranch
 
@@ -82,6 +84,8 @@ func TestGetContentsOrListForDir(t *testing.T) {
        test.LoadRepoCommit(t, ctx)
        test.LoadUser(t, ctx, 2)
        test.LoadGitRepo(t, ctx)
+       defer ctx.Repo.GitRepo.Close()
+
        treePath := "" // root dir
        ref := ctx.Repo.Repository.DefaultBranch
 
@@ -115,6 +119,8 @@ func TestGetContentsOrListForFile(t *testing.T) {
        test.LoadRepoCommit(t, ctx)
        test.LoadUser(t, ctx, 2)
        test.LoadGitRepo(t, ctx)
+       defer ctx.Repo.GitRepo.Close()
+
        treePath := "README.md"
        ref := ctx.Repo.Repository.DefaultBranch
 
@@ -141,6 +147,8 @@ func TestGetContentsErrors(t *testing.T) {
        test.LoadRepoCommit(t, ctx)
        test.LoadUser(t, ctx, 2)
        test.LoadGitRepo(t, ctx)
+       defer ctx.Repo.GitRepo.Close()
+
        repo := ctx.Repo.Repository
        treePath := "README.md"
        ref := repo.DefaultBranch
@@ -170,6 +178,8 @@ func TestGetContentsOrListErrors(t *testing.T) {
        test.LoadRepoCommit(t, ctx)
        test.LoadUser(t, ctx, 2)
        test.LoadGitRepo(t, ctx)
+       defer ctx.Repo.GitRepo.Close()
+
        repo := ctx.Repo.Repository
        treePath := "README.md"
        ref := repo.DefaultBranch
@@ -198,6 +208,8 @@ func TestGetContentsOrListOfEmptyRepos(t *testing.T) {
        test.LoadRepo(t, ctx, 15)
        test.LoadUser(t, ctx, 2)
        test.LoadGitRepo(t, ctx)
+       defer ctx.Repo.GitRepo.Close()
+
        repo := ctx.Repo.Repository
 
        t.Run("empty repo", func(t *testing.T) {
index de5ed1d7548533287383dd231c4ca6102786b67e..db2c7552c4ffe58aa05e5ae1d932a4377c6806da 100644 (file)
@@ -22,6 +22,8 @@ func TestGetDiffPreview(t *testing.T) {
        test.LoadRepoCommit(t, ctx)
        test.LoadUser(t, ctx, 2)
        test.LoadGitRepo(t, ctx)
+       defer ctx.Repo.GitRepo.Close()
+
        branch := ctx.Repo.Repository.DefaultBranch
        treePath := "README.md"
        content := "# repo1\n\nDescription for repo1\nthis is a new line"
@@ -119,6 +121,8 @@ func TestGetDiffPreviewErrors(t *testing.T) {
        test.LoadRepoCommit(t, ctx)
        test.LoadUser(t, ctx, 2)
        test.LoadGitRepo(t, ctx)
+       defer ctx.Repo.GitRepo.Close()
+
        branch := ctx.Repo.Repository.DefaultBranch
        treePath := "README.md"
        content := "# repo1\n\nDescription for repo1\nthis is a new line"
index 95ec175ed47fd8a2be44e8369c10c719d3faed32..3cb4eb472bf0ff341fa6696303e6e14139c1efdc 100644 (file)
@@ -88,10 +88,13 @@ func TestGetFileResponseFromCommit(t *testing.T) {
        test.LoadRepoCommit(t, ctx)
        test.LoadUser(t, ctx, 2)
        test.LoadGitRepo(t, ctx)
+       defer ctx.Repo.GitRepo.Close()
+
        repo := ctx.Repo.Repository
        branch := repo.DefaultBranch
        treePath := "README.md"
        gitRepo, _ := git.OpenRepository(repo.RepoPath())
+       defer gitRepo.Close()
        commit, _ := gitRepo.GetBranchCommit(branch)
        expectedFileResponse := getExpectedFileResponse()
 
index abc224c2c295b5b67ec63dfad538c8cef580b432..6bd775d9d22f842ca3d7e76721b2c252295a0d58 100644 (file)
@@ -42,6 +42,7 @@ func NewTemporaryUploadRepository(repo *models.Repository) (*TemporaryUploadRepo
 
 // Close the repository cleaning up all files
 func (t *TemporaryUploadRepository) Close() {
+       defer t.gitRepo.Close()
        if err := models.RemoveTemporaryPath(t.basePath); err != nil {
                log.Error("Failed to remove temporary path %s: %v", t.basePath, err)
        }
index 318a5d152d839e1644eee7acdfb66d09c26c8bd2..cf0534563fc37fe5dfdc2b67be555412d72653dc 100644 (file)
@@ -19,6 +19,7 @@ func GetTreeBySHA(repo *models.Repository, sha string, page, perPage int, recurs
        if err != nil {
                return nil, err
        }
+       defer gitRepo.Close()
        gitTree, err := gitRepo.GetTree(sha)
        if err != nil || gitTree == nil {
                return nil, models.ErrSHANotFound{
index ecff8b90717e8b32786eea58b44792d648bb89cc..e1bb812ec156bc6d5c7fef826a7d2a5d7dd4b24a 100644 (file)
@@ -21,6 +21,8 @@ func TestGetTreeBySHA(t *testing.T) {
        test.LoadRepoCommit(t, ctx)
        test.LoadUser(t, ctx, 2)
        test.LoadGitRepo(t, ctx)
+       defer ctx.Repo.GitRepo.Close()
+
        sha := ctx.Repo.Repository.DefaultBranch
        page := 1
        perPage := 10
index 5479616c4b81429edb3b8882ad2ac1f766879903..ef56609f4d05a32686bc2781179d316060cfa38b 100644 (file)
@@ -430,6 +430,7 @@ func PushUpdate(repo *models.Repository, branch string, opts models.PushUpdateOp
        if err != nil {
                return fmt.Errorf("OpenRepository: %v", err)
        }
+       defer gitRepo.Close()
 
        if err = repo.UpdateSize(); err != nil {
                log.Error("Failed to update size for repository: %v", err)
index 92df1c576252b20bcab1ca384e4401a87536a767..cf9c5fbc548adc7e8f3772815fe14a9017206925 100644 (file)
@@ -55,6 +55,7 @@ func LoadRepo(t *testing.T, ctx *context.Context, repoID int64) {
 func LoadRepoCommit(t *testing.T, ctx *context.Context) {
        gitRepo, err := git.OpenRepository(ctx.Repo.Repository.RepoPath())
        assert.NoError(t, err)
+       defer gitRepo.Close()
        branch, err := gitRepo.GetHEADBranch()
        assert.NoError(t, err)
        ctx.Repo.Commit, err = gitRepo.GetBranchCommit(branch.Name)
index b68717f7c8751f42283dc853c11f5dc33f947a0a..6fdd0d074c90295561ad3cad441ed4cad9d8c1de 100644 (file)
@@ -641,7 +641,7 @@ func RegisterRoutes(m *macaron.Macaron) {
                                }, reqRepoReader(models.UnitTypeCode))
                                m.Group("/tags", func() {
                                        m.Get("", repo.ListTags)
-                               }, reqRepoReader(models.UnitTypeCode))
+                               }, reqRepoReader(models.UnitTypeCode), context.ReferencesGitRepo(true))
                                m.Group("/keys", func() {
                                        m.Combo("").Get(repo.ListDeployKeys).
                                                Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey)
index 0156aaaa05cd3b1dda6f0841196d5317cc3d191e..163a06a95e8e12e41d2a3bd1a2180462171376aa 100644 (file)
@@ -51,6 +51,7 @@ func GetSingleCommit(ctx *context.APIContext) {
                ctx.ServerError("OpenRepository", err)
                return
        }
+       defer gitRepo.Close()
        commit, err := gitRepo.GetCommit(ctx.Params(":sha"))
        if err != nil {
                ctx.NotFoundOrServerError("GetCommit", git.IsErrNotExist, err)
@@ -113,6 +114,7 @@ func GetAllCommits(ctx *context.APIContext) {
                ctx.ServerError("OpenRepository", err)
                return
        }
+       defer gitRepo.Close()
 
        page := ctx.QueryInt("page")
        if page <= 0 {
index f1a61bb0be04d6818b82aab5c4e0ad8630e92850..175235c5ef374f38eea724c6d016d2c8981a9222 100644 (file)
@@ -95,6 +95,7 @@ func GetArchive(ctx *context.APIContext) {
                return
        }
        ctx.Repo.GitRepo = gitRepo
+       defer gitRepo.Close()
 
        repo.Download(ctx.Context)
 }
index d7acc139f0d570f0c41befe08f7bad122d7ba3b5..c2bcbb36038641e72f84a127ac56eb3dfee2c157 100644 (file)
@@ -76,6 +76,8 @@ func getGitRefs(ctx *context.APIContext, filter string) ([]*git.Reference, strin
        if err != nil {
                return nil, "OpenRepository", err
        }
+       defer gitRepo.Close()
+
        if len(filter) > 0 {
                filter = "refs/" + filter
        }
index 6af1ba1b04b0c1a3e57ee536cb27fbbf843cd747..9abcaa0496a1506def2bb8059898cc84221558ff 100644 (file)
@@ -195,6 +195,7 @@ func CreatePullRequest(ctx *context.APIContext, form api.CreatePullRequestOption
        if ctx.Written() {
                return
        }
+       defer headGitRepo.Close()
 
        // Check if another PR exists with the same targets
        existingPr, err := models.GetUnmergedPullRequest(headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch)
@@ -722,6 +723,7 @@ func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption)
        // user should have permission to read baseRepo's codes and pulls, NOT headRepo's
        permBase, err := models.GetUserRepoPermission(baseRepo, ctx.User)
        if err != nil {
+               headGitRepo.Close()
                ctx.ServerError("GetUserRepoPermission", err)
                return nil, nil, nil, nil, "", ""
        }
@@ -732,6 +734,7 @@ func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption)
                                baseRepo,
                                permBase)
                }
+               headGitRepo.Close()
                ctx.NotFound("Can't read pulls or can't read UnitTypeCode")
                return nil, nil, nil, nil, "", ""
        }
@@ -739,6 +742,7 @@ func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption)
        // user should have permission to read headrepo's codes
        permHead, err := models.GetUserRepoPermission(headRepo, ctx.User)
        if err != nil {
+               headGitRepo.Close()
                ctx.ServerError("GetUserRepoPermission", err)
                return nil, nil, nil, nil, "", ""
        }
@@ -749,18 +753,21 @@ func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption)
                                headRepo,
                                permHead)
                }
+               headGitRepo.Close()
                ctx.NotFound("Can't read headRepo UnitTypeCode")
                return nil, nil, nil, nil, "", ""
        }
 
        // Check if head branch is valid.
        if !headGitRepo.IsBranchExist(headBranch) {
+               headGitRepo.Close()
                ctx.NotFound()
                return nil, nil, nil, nil, "", ""
        }
 
        compareInfo, err := headGitRepo.GetCompareInfo(models.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch)
        if err != nil {
+               headGitRepo.Close()
                ctx.Error(500, "GetCompareInfo", err)
                return nil, nil, nil, nil, "", ""
        }
index 6cfdb461ee261e40f56b6e6bb148da1f77aa8224..0a764113ab805139c5a6cce65098eacbb08d987d 100644 (file)
@@ -33,7 +33,7 @@ func ListTags(ctx *context.APIContext) {
        // responses:
        //   "200":
        //     "$ref": "#/responses/TagList"
-       tags, err := ctx.Repo.Repository.GetTags()
+       tags, err := ctx.Repo.GitRepo.GetTagInfos()
        if err != nil {
                ctx.Error(500, "GetTags", err)
                return
index b9e14abfb87bb352f10d940f996c44e4cfc0ef43..e45f0464353c84aafab61fec31c6c6ee3a882855 100644 (file)
@@ -157,6 +157,7 @@ func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *
        // user should have permission to read baseRepo's codes and pulls, NOT headRepo's
        permBase, err := models.GetUserRepoPermission(baseRepo, ctx.User)
        if err != nil {
+               headGitRepo.Close()
                ctx.ServerError("GetUserRepoPermission", err)
                return nil, nil, nil, nil, "", ""
        }
@@ -167,6 +168,7 @@ func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *
                                baseRepo,
                                permBase)
                }
+               headGitRepo.Close()
                ctx.NotFound("ParseCompareInfo", nil)
                return nil, nil, nil, nil, "", ""
        }
@@ -174,6 +176,7 @@ func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *
        // user should have permission to read headrepo's codes
        permHead, err := models.GetUserRepoPermission(headRepo, ctx.User)
        if err != nil {
+               headGitRepo.Close()
                ctx.ServerError("GetUserRepoPermission", err)
                return nil, nil, nil, nil, "", ""
        }
@@ -184,6 +187,7 @@ func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *
                                headRepo,
                                permHead)
                }
+               headGitRepo.Close()
                ctx.NotFound("ParseCompareInfo", nil)
                return nil, nil, nil, nil, "", ""
        }
@@ -199,6 +203,7 @@ func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *
                        ctx.Data["HeadBranch"] = headBranch
                        headIsCommit = true
                } else {
+                       headGitRepo.Close()
                        ctx.NotFound("IsRefExist", nil)
                        return nil, nil, nil, nil, "", ""
                }
@@ -219,12 +224,14 @@ func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *
                                baseRepo,
                                permBase)
                }
+               headGitRepo.Close()
                ctx.NotFound("ParseCompareInfo", nil)
                return nil, nil, nil, nil, "", ""
        }
 
        compareInfo, err := headGitRepo.GetCompareInfo(models.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch)
        if err != nil {
+               headGitRepo.Close()
                ctx.ServerError("GetCompareInfo", err)
                return nil, nil, nil, nil, "", ""
        }
@@ -356,6 +363,8 @@ func parseBaseRepoInfo(ctx *context.Context, repo *models.Repository) error {
        if err != nil {
                return err
        }
+       defer baseGitRepo.Close()
+
        ctx.Data["BaseRepoBranches"], err = baseGitRepo.GetBranches()
        if err != nil {
                return err
@@ -369,6 +378,8 @@ func CompareDiff(ctx *context.Context) {
        if ctx.Written() {
                return
        }
+       defer headGitRepo.Close()
+
        if err := parseBaseRepoInfo(ctx, headRepo); err != nil {
                ctx.ServerError("parseBaseRepoInfo", err)
                return
index ca00be74b7fec59f81c096af374581689d3256a0..ec7aee1e77ff9297663a2939214f6ebc351b9731 100644 (file)
@@ -48,6 +48,8 @@ func TestGetUniquePatchBranchName(t *testing.T) {
        test.LoadRepoCommit(t, ctx)
        test.LoadUser(t, ctx, 2)
        test.LoadGitRepo(t, ctx)
+       defer ctx.Repo.GitRepo.Close()
+
        expectedBranchName := "user2-patch-1"
        branchName := GetUniquePatchBranchName(ctx)
        assert.Equal(t, expectedBranchName, branchName)
@@ -61,9 +63,12 @@ func TestGetClosestParentWithFiles(t *testing.T) {
        test.LoadRepoCommit(t, ctx)
        test.LoadUser(t, ctx, 2)
        test.LoadGitRepo(t, ctx)
+       defer ctx.Repo.GitRepo.Close()
+
        repo := ctx.Repo.Repository
        branch := repo.DefaultBranch
        gitRepo, _ := git.OpenRepository(repo.RepoPath())
+       defer gitRepo.Close()
        commit, _ := gitRepo.GetBranchCommit(branch)
        expectedTreePath := ""
 
index 8269717e573740aefde72b71faadcef007f70590..67849f33e12f4bb0387a052297cef90784b86e4c 100644 (file)
@@ -352,6 +352,7 @@ func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.Compare
                        ctx.ServerError("OpenRepository", err)
                        return nil
                }
+               defer headGitRepo.Close()
 
                headBranchExist = headGitRepo.IsBranchExist(pull.HeadBranch)
 
@@ -534,6 +535,7 @@ func ViewPullFiles(ctx *context.Context) {
                        ctx.ServerError("OpenRepository", err)
                        return
                }
+               defer headGitRepo.Close()
 
                headCommitID, err := headGitRepo.GetBranchCommitID(pull.HeadBranch)
                if err != nil {
@@ -748,6 +750,7 @@ func CompareAndPullRequestPost(ctx *context.Context, form auth.CreateIssueForm)
        if ctx.Written() {
                return
        }
+       defer headGitRepo.Close()
 
        labelIDs, assigneeIDs, milestoneID := ValidateRepoMetas(ctx, form, true)
        if ctx.Written() {
@@ -913,12 +916,14 @@ func CleanUpPullRequest(ctx *context.Context) {
                ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.RepoPath()), err)
                return
        }
+       defer gitRepo.Close()
 
        gitBaseRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
        if err != nil {
                ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.BaseRepo.RepoPath()), err)
                return
        }
+       defer gitBaseRepo.Close()
 
        defer func() {
                ctx.JSON(200, map[string]interface{}{
@@ -1047,6 +1052,7 @@ func DownloadPullPatch(ctx *context.Context) {
                ctx.ServerError("OpenRepository", err)
                return
        }
+       defer headGitRepo.Close()
 
        patch, err := headGitRepo.GetFormatPatch(pr.MergeBase, pr.HeadBranch)
        if err != nil {
index 524c1c7346bc2366773396f0100be7aaf860a3ab..47d1a89b54a06dffdb9f17a06f7824b0856ae11a 100644 (file)
@@ -57,5 +57,6 @@ func TestNewReleasePost(t *testing.T) {
                        Title:       testCase.Form.Title,
                        Note:        testCase.Form.Content,
                }, models.Cond("is_draft=?", len(testCase.Form.Draft) > 0))
+               ctx.Repo.GitRepo.Close()
        }
 }
index f699c1d6856418bdb1880b6a5ac7faa05c6e37af..fa215357d2d70b9c66e02bbbc7859032809a6355 100644 (file)
@@ -73,6 +73,11 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) {
                // Check if repository name has been changed.
                if repo.LowerName != strings.ToLower(newRepoName) {
                        isNameChanged = true
+                       // Close the GitRepo if open
+                       if ctx.Repo.GitRepo != nil {
+                               ctx.Repo.GitRepo.Close()
+                               ctx.Repo.GitRepo = nil
+                       }
                        if err := models.ChangeRepositoryName(ctx.Repo.Owner, repo.Name, newRepoName); err != nil {
                                ctx.Data["Err_RepoName"] = true
                                switch {
@@ -379,6 +384,11 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) {
                }
 
                oldOwnerID := ctx.Repo.Owner.ID
+               // Close the GitRepo if open
+               if ctx.Repo.GitRepo != nil {
+                       ctx.Repo.GitRepo.Close()
+                       ctx.Repo.GitRepo = nil
+               }
                if err = models.TransferOwnership(ctx.User, newOwner, repo); err != nil {
                        if models.IsErrRepoAlreadyExist(err) {
                                ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplSettingsOptions, nil)
index 02fbe4a1ddad668b18e414db015de01d8c2a8295..6cf194365891fe38d3c13cf22a547aeeae8fb9e2 100644 (file)
@@ -146,6 +146,9 @@ func renderViewPage(ctx *context.Context) (*git.Repository, *git.TreeEntry) {
        // Get page list.
        entries, err := commit.ListEntries()
        if err != nil {
+               if wikiRepo != nil {
+                       wikiRepo.Close()
+               }
                ctx.ServerError("ListEntries", err)
                return nil, nil
        }
@@ -159,6 +162,9 @@ func renderViewPage(ctx *context.Context) (*git.Repository, *git.TreeEntry) {
                        if models.IsErrWikiInvalidFileName(err) {
                                continue
                        }
+                       if wikiRepo != nil {
+                               wikiRepo.Close()
+                       }
                        ctx.ServerError("WikiFilenameToName", err)
                        return nil, nil
                } else if wikiName == "_Sidebar" || wikiName == "_Footer" {
@@ -188,16 +194,25 @@ func renderViewPage(ctx *context.Context) (*git.Repository, *git.TreeEntry) {
                ctx.Redirect(ctx.Repo.RepoLink + "/wiki/_pages")
        }
        if entry == nil || ctx.Written() {
+               if wikiRepo != nil {
+                       wikiRepo.Close()
+               }
                return nil, nil
        }
 
        sidebarContent, _, _, _ := wikiContentsByName(ctx, commit, "_Sidebar")
        if ctx.Written() {
+               if wikiRepo != nil {
+                       wikiRepo.Close()
+               }
                return nil, nil
        }
 
        footerContent, _, _, _ := wikiContentsByName(ctx, commit, "_Footer")
        if ctx.Written() {
+               if wikiRepo != nil {
+                       wikiRepo.Close()
+               }
                return nil, nil
        }
 
@@ -218,6 +233,9 @@ func renderViewPage(ctx *context.Context) (*git.Repository, *git.TreeEntry) {
 func renderRevisionPage(ctx *context.Context) (*git.Repository, *git.TreeEntry) {
        wikiRepo, commit, err := findWikiRepoCommit(ctx)
        if err != nil {
+               if wikiRepo != nil {
+                       wikiRepo.Close()
+               }
                if !git.IsErrNotExist(err) {
                        ctx.ServerError("GetBranchCommit", err)
                }
@@ -241,6 +259,9 @@ func renderRevisionPage(ctx *context.Context) (*git.Repository, *git.TreeEntry)
                ctx.Redirect(ctx.Repo.RepoLink + "/wiki/_pages")
        }
        if entry == nil || ctx.Written() {
+               if wikiRepo != nil {
+                       wikiRepo.Close()
+               }
                return nil, nil
        }
 
@@ -263,6 +284,9 @@ func renderRevisionPage(ctx *context.Context) (*git.Repository, *git.TreeEntry)
        // get Commit Count
        commitsHistory, err := wikiRepo.CommitsByFileAndRangeNoFollow("master", pageFilename, page)
        if err != nil {
+               if wikiRepo != nil {
+                       wikiRepo.Close()
+               }
                ctx.ServerError("CommitsByFileAndRangeNoFollow", err)
                return nil, nil
        }
@@ -279,13 +303,21 @@ func renderRevisionPage(ctx *context.Context) (*git.Repository, *git.TreeEntry)
 }
 
 func renderEditPage(ctx *context.Context) {
-       _, commit, err := findWikiRepoCommit(ctx)
+       wikiRepo, commit, err := findWikiRepoCommit(ctx)
        if err != nil {
+               if wikiRepo != nil {
+                       wikiRepo.Close()
+               }
                if !git.IsErrNotExist(err) {
                        ctx.ServerError("GetBranchCommit", err)
                }
                return
        }
+       defer func() {
+               if wikiRepo != nil {
+                       wikiRepo.Close()
+               }
+       }()
 
        // get requested pagename
        pageName := models.NormalizeWikiName(ctx.Params(":page"))
@@ -327,8 +359,16 @@ func Wiki(ctx *context.Context) {
 
        wikiRepo, entry := renderViewPage(ctx)
        if ctx.Written() {
+               if wikiRepo != nil {
+                       wikiRepo.Close()
+               }
                return
        }
+       defer func() {
+               if wikiRepo != nil {
+                       wikiRepo.Close()
+               }
+       }()
        if entry == nil {
                ctx.Data["Title"] = ctx.Tr("repo.wiki")
                ctx.HTML(200, tplWikiStart)
@@ -364,8 +404,16 @@ func WikiRevision(ctx *context.Context) {
 
        wikiRepo, entry := renderRevisionPage(ctx)
        if ctx.Written() {
+               if wikiRepo != nil {
+                       wikiRepo.Close()
+               }
                return
        }
+       defer func() {
+               if wikiRepo != nil {
+                       wikiRepo.Close()
+               }
+       }()
        if entry == nil {
                ctx.Data["Title"] = ctx.Tr("repo.wiki")
                ctx.HTML(200, tplWikiStart)
@@ -397,11 +445,18 @@ func WikiPages(ctx *context.Context) {
 
        wikiRepo, commit, err := findWikiRepoCommit(ctx)
        if err != nil {
+               if wikiRepo != nil {
+                       wikiRepo.Close()
+               }
                return
        }
 
        entries, err := commit.ListEntries()
        if err != nil {
+               if wikiRepo != nil {
+                       wikiRepo.Close()
+               }
+
                ctx.ServerError("ListEntries", err)
                return
        }
@@ -412,6 +467,10 @@ func WikiPages(ctx *context.Context) {
                }
                c, err := wikiRepo.GetCommitByPath(entry.Name())
                if err != nil {
+                       if wikiRepo != nil {
+                               wikiRepo.Close()
+                       }
+
                        ctx.ServerError("GetCommit", err)
                        return
                }
@@ -420,6 +479,10 @@ func WikiPages(ctx *context.Context) {
                        if models.IsErrWikiInvalidFileName(err) {
                                continue
                        }
+                       if wikiRepo != nil {
+                               wikiRepo.Close()
+                       }
+
                        ctx.ServerError("WikiFilenameToName", err)
                        return
                }
@@ -431,6 +494,11 @@ func WikiPages(ctx *context.Context) {
        }
        ctx.Data["Pages"] = pages
 
+       defer func() {
+               if wikiRepo != nil {
+                       wikiRepo.Close()
+               }
+       }()
        ctx.HTML(200, tplWikiPages)
 }
 
index 4687d24f6b28d64344362857c0693b344abbed3b..44fcd02035fe39b47c72caffcc01b94424c1d12f 100644 (file)
@@ -23,6 +23,7 @@ const message = "Wiki commit message for unit tests"
 func wikiEntry(t *testing.T, repo *models.Repository, wikiName string) *git.TreeEntry {
        wikiRepo, err := git.OpenRepository(repo.WikiPath())
        assert.NoError(t, err)
+       defer wikiRepo.Close()
        commit, err := wikiRepo.GetBranchCommit("master")
        assert.NoError(t, err)
        entries, err := commit.ListEntries()
index 1ae5e2743fe7fbfdb48f92767168aeb19d26da0e..ba40bf582d30b5d8c5200cd2c158ea220550f043 100644 (file)
@@ -49,6 +49,7 @@ func CreateCodeComment(doer *models.User, repo *models.Repository, issue *models
        if err != nil {
                return nil, fmt.Errorf("OpenRepository: %v", err)
        }
+       defer gitRepo.Close()
 
        // FIXME validate treePath
        // Get latest commit referencing the commented line
index c2c5675d9fd212b3860c382e7bd6365717a72bae..9c2aef5c97ce1a6d6b6ba44fcc5a14c0d9d4ad73 100644 (file)
@@ -678,6 +678,7 @@ func GetDiffRangeWithWhitespaceBehavior(repoPath, beforeCommitID, afterCommitID
        if err != nil {
                return nil, err
        }
+       defer gitRepo.Close()
 
        commit, err := gitRepo.GetCommit(afterCommitID)
        if err != nil {
@@ -750,6 +751,7 @@ func GetRawDiffForFile(repoPath, startCommit, endCommit string, diffType RawDiff
        if err != nil {
                return fmt.Errorf("OpenRepository: %v", err)
        }
+       defer repo.Close()
 
        commit, err := repo.GetCommit(endCommit)
        if err != nil {
index 11430c20700deb93a46e4e2685c5d3a710c84ac1..8c8131b5c2b28417f2bafa3cbbf4eea40ea0b620 100644 (file)
@@ -197,8 +197,10 @@ func runSync(m *models.Mirror) ([]*mirrorSyncResult, bool) {
                return nil, false
        }
        if err = models.SyncReleasesWithTags(m.Repo, gitRepo); err != nil {
+               gitRepo.Close()
                log.Error("Failed to synchronize tags to releases for repository: %v", err)
        }
+       gitRepo.Close()
 
        if err := m.Repo.UpdateSize(); err != nil {
                log.Error("Failed to update size for mirror repository: %v", err)
@@ -290,97 +292,103 @@ func Update() {
 func SyncMirrors() {
        // Start listening on new sync requests.
        for repoID := range mirrorQueue.Queue() {
-               log.Trace("SyncMirrors [repo_id: %v]", repoID)
-               mirrorQueue.Remove(repoID)
+               syncMirror(repoID)
+       }
+}
+
+func syncMirror(repoID string) {
+       log.Trace("SyncMirrors [repo_id: %v]", repoID)
+       mirrorQueue.Remove(repoID)
+
+       m, err := models.GetMirrorByRepoID(com.StrTo(repoID).MustInt64())
+       if err != nil {
+               log.Error("GetMirrorByRepoID [%s]: %v", repoID, err)
+               return
+
+       }
+
+       results, ok := runSync(m)
+       if !ok {
+               return
+       }
+
+       m.ScheduleNextUpdate()
+       if err = models.UpdateMirror(m); err != nil {
+               log.Error("UpdateMirror [%s]: %v", repoID, err)
+               return
+       }
 
-               m, err := models.GetMirrorByRepoID(com.StrTo(repoID).MustInt64())
+       var gitRepo *git.Repository
+       if len(results) == 0 {
+               log.Trace("SyncMirrors [repo_id: %d]: no commits fetched", m.RepoID)
+       } else {
+               gitRepo, err = git.OpenRepository(m.Repo.RepoPath())
                if err != nil {
-                       log.Error("GetMirrorByRepoID [%s]: %v", repoID, err)
-                       continue
+                       log.Error("OpenRepository [%d]: %v", m.RepoID, err)
+                       return
                }
+               defer gitRepo.Close()
+       }
 
-               results, ok := runSync(m)
-               if !ok {
+       for _, result := range results {
+               // Discard GitHub pull requests, i.e. refs/pull/*
+               if strings.HasPrefix(result.refName, "refs/pull/") {
                        continue
                }
 
-               m.ScheduleNextUpdate()
-               if err = models.UpdateMirror(m); err != nil {
-                       log.Error("UpdateMirror [%s]: %v", repoID, err)
+               // Create reference
+               if result.oldCommitID == gitShortEmptySha {
+                       if err = SyncCreateAction(m.Repo, result.refName); err != nil {
+                               log.Error("SyncCreateAction [repo_id: %d]: %v", m.RepoID, err)
+                       }
                        continue
                }
 
-               var gitRepo *git.Repository
-               if len(results) == 0 {
-                       log.Trace("SyncMirrors [repo_id: %d]: no commits fetched", m.RepoID)
-               } else {
-                       gitRepo, err = git.OpenRepository(m.Repo.RepoPath())
-                       if err != nil {
-                               log.Error("OpenRepository [%d]: %v", m.RepoID, err)
-                               continue
+               // Delete reference
+               if result.newCommitID == gitShortEmptySha {
+                       if err = SyncDeleteAction(m.Repo, result.refName); err != nil {
+                               log.Error("SyncDeleteAction [repo_id: %d]: %v", m.RepoID, err)
                        }
+                       continue
                }
 
-               for _, result := range results {
-                       // Discard GitHub pull requests, i.e. refs/pull/*
-                       if strings.HasPrefix(result.refName, "refs/pull/") {
-                               continue
-                       }
-
-                       // Create reference
-                       if result.oldCommitID == gitShortEmptySha {
-                               if err = SyncCreateAction(m.Repo, result.refName); err != nil {
-                                       log.Error("SyncCreateAction [repo_id: %d]: %v", m.RepoID, err)
-                               }
-                               continue
-                       }
-
-                       // Delete reference
-                       if result.newCommitID == gitShortEmptySha {
-                               if err = SyncDeleteAction(m.Repo, result.refName); err != nil {
-                                       log.Error("SyncDeleteAction [repo_id: %d]: %v", m.RepoID, err)
-                               }
-                               continue
-                       }
-
-                       // Push commits
-                       oldCommitID, err := git.GetFullCommitID(gitRepo.Path, result.oldCommitID)
-                       if err != nil {
-                               log.Error("GetFullCommitID [%d]: %v", m.RepoID, err)
-                               continue
-                       }
-                       newCommitID, err := git.GetFullCommitID(gitRepo.Path, result.newCommitID)
-                       if err != nil {
-                               log.Error("GetFullCommitID [%d]: %v", m.RepoID, err)
-                               continue
-                       }
-                       commits, err := gitRepo.CommitsBetweenIDs(newCommitID, oldCommitID)
-                       if err != nil {
-                               log.Error("CommitsBetweenIDs [repo_id: %d, new_commit_id: %s, old_commit_id: %s]: %v", m.RepoID, newCommitID, oldCommitID, err)
-                               continue
-                       }
-                       if err = SyncPushAction(m.Repo, SyncPushActionOptions{
-                               RefName:     result.refName,
-                               OldCommitID: oldCommitID,
-                               NewCommitID: newCommitID,
-                               Commits:     models.ListToPushCommits(commits),
-                       }); err != nil {
-                               log.Error("SyncPushAction [repo_id: %d]: %v", m.RepoID, err)
-                               continue
-                       }
+               // Push commits
+               oldCommitID, err := git.GetFullCommitID(gitRepo.Path, result.oldCommitID)
+               if err != nil {
+                       log.Error("GetFullCommitID [%d]: %v", m.RepoID, err)
+                       continue
                }
-
-               // Get latest commit date and update to current repository updated time
-               commitDate, err := git.GetLatestCommitTime(m.Repo.RepoPath())
+               newCommitID, err := git.GetFullCommitID(gitRepo.Path, result.newCommitID)
                if err != nil {
-                       log.Error("GetLatestCommitDate [%d]: %v", m.RepoID, err)
+                       log.Error("GetFullCommitID [%d]: %v", m.RepoID, err)
                        continue
                }
-
-               if err = models.UpdateRepositoryUpdatedTime(m.RepoID, commitDate); err != nil {
-                       log.Error("Update repository 'updated_unix' [%d]: %v", m.RepoID, err)
+               commits, err := gitRepo.CommitsBetweenIDs(newCommitID, oldCommitID)
+               if err != nil {
+                       log.Error("CommitsBetweenIDs [repo_id: %d, new_commit_id: %s, old_commit_id: %s]: %v", m.RepoID, newCommitID, oldCommitID, err)
                        continue
                }
+               if err = SyncPushAction(m.Repo, SyncPushActionOptions{
+                       RefName:     result.refName,
+                       OldCommitID: oldCommitID,
+                       NewCommitID: newCommitID,
+                       Commits:     models.ListToPushCommits(commits),
+               }); err != nil {
+                       log.Error("SyncPushAction [repo_id: %d]: %v", m.RepoID, err)
+                       continue
+               }
+       }
+
+       // Get latest commit date and update to current repository updated time
+       commitDate, err := git.GetLatestCommitTime(m.Repo.RepoPath())
+       if err != nil {
+               log.Error("GetLatestCommitDate [%d]: %v", m.RepoID, err)
+               return
+       }
+
+       if err = models.UpdateRepositoryUpdatedTime(m.RepoID, commitDate); err != nil {
+               log.Error("Update repository 'updated_unix' [%d]: %v", m.RepoID, err)
+               return
        }
 }
 
index 9ad11b726563c6bb987fd2ff453587a96bb4371c..37e8a7be573760078dcbc98f38d473e78008205c 100644 (file)
@@ -51,6 +51,7 @@ func TestRelease_MirrorDelete(t *testing.T) {
 
        gitRepo, err := git.OpenRepository(repoPath)
        assert.NoError(t, err)
+       defer gitRepo.Close()
 
        findOptions := models.FindReleasesOptions{IncludeDrafts: true, IncludeTags: true}
        initCount, err := models.GetReleaseCountByRepoID(mirror.ID, findOptions)
index 2872db7bd28966558502991f1e042bb0dfe5f2e1..ca00cdaad9bc467dda1a9626bed0ee0f2daebf3d 100644 (file)
@@ -55,6 +55,7 @@ func IsPullCommitStatusPass(pr *models.PullRequest) (bool, error) {
        if err != nil {
                return false, errors.Wrap(err, "OpenRepository")
        }
+       defer headGitRepo.Close()
 
        if !headGitRepo.IsBranchExist(pr.HeadBranch) {
                return false, errors.New("Head branch does not exist, can not merge")
index 4e981b2b260c9286c004d2890dc24bc41475fec3..7a9c2ef9ad03d1fb527c0522213470bf6760ac35 100644 (file)
@@ -48,6 +48,7 @@ func checkForInvalidation(requests models.PullRequestList, repoID int64, doer *m
                if err != nil {
                        log.Error("PullRequestList.InvalidateCodeComments: %v", err)
                }
+               gitRepo.Close()
        }()
        return nil
 }
index d30dfee2865cd52850d7b5e29f737f5a73de04c3..effab212510629bee7d5256e2a9337f13d9b478a 100644 (file)
@@ -27,6 +27,7 @@ func TestRelease_Create(t *testing.T) {
 
        gitRepo, err := git.OpenRepository(repoPath)
        assert.NoError(t, err)
+       defer gitRepo.Close()
 
        assert.NoError(t, CreateRelease(gitRepo, &models.Release{
                RepoID:       repo.ID,