github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/git/repo_base_gogit.go (about) 1 // Copyright 2023 The GitBundle Inc. All rights reserved. 2 // Copyright 2017 The Gitea Authors. All rights reserved. 3 // Use of this source code is governed by a MIT-style 4 // license that can be found in the LICENSE file. 5 6 // Copyright 2015 The Gogs Authors. All rights reserved. 7 8 //go:build gogit 9 10 package git 11 12 import ( 13 "context" 14 "errors" 15 "path/filepath" 16 17 gitealog "github.com/gitbundle/modules/log" 18 "github.com/gitbundle/modules/setting" 19 20 "github.com/go-git/go-billy/v5/osfs" 21 gogit "github.com/go-git/go-git/v5" 22 "github.com/go-git/go-git/v5/plumbing/cache" 23 "github.com/go-git/go-git/v5/storage/filesystem" 24 ) 25 26 // Repository represents a Git repository. 27 type Repository struct { 28 Path string 29 30 tagCache *ObjectCache 31 32 gogitRepo *gogit.Repository 33 gogitStorage *filesystem.Storage 34 gpgSettings *GPGSettings 35 36 Ctx context.Context 37 } 38 39 // openRepositoryWithDefaultContext opens the repository at the given path with DefaultContext. 40 func openRepositoryWithDefaultContext(repoPath string) (*Repository, error) { 41 return OpenRepository(DefaultContext, repoPath) 42 } 43 44 // OpenRepository opens the repository at the given path within the context.Context 45 func OpenRepository(ctx context.Context, repoPath string) (*Repository, error) { 46 repoPath, err := filepath.Abs(repoPath) 47 if err != nil { 48 return nil, err 49 } else if !isDir(repoPath) { 50 return nil, errors.New("no such file or directory") 51 } 52 53 fs := osfs.New(repoPath) 54 _, err = fs.Stat(".git") 55 if err == nil { 56 fs, err = fs.Chroot(".git") 57 if err != nil { 58 return nil, err 59 } 60 } 61 storage := filesystem.NewStorageWithOptions(fs, cache.NewObjectLRUDefault(), filesystem.Options{KeepDescriptors: true, LargeObjectThreshold: setting.Git.LargeObjectThreshold}) 62 gogitRepo, err := gogit.Open(storage, fs) 63 if err != nil { 64 return nil, err 65 } 66 67 return &Repository{ 68 Path: repoPath, 69 gogitRepo: gogitRepo, 70 gogitStorage: storage, 71 tagCache: newObjectCache(), 72 Ctx: ctx, 73 }, nil 74 } 75 76 // Close this repository, in particular close the underlying gogitStorage if this is not nil 77 func (repo *Repository) Close() (err error) { 78 if repo == nil || repo.gogitStorage == nil { 79 return 80 } 81 if err := repo.gogitStorage.Close(); err != nil { 82 gitealog.Error("Error closing storage: %v", err) 83 } 84 return 85 } 86 87 // GoGitRepo gets the go-git repo representation 88 func (repo *Repository) GoGitRepo() *gogit.Repository { 89 return repo.gogitRepo 90 }