github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/git/repo_base.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  package git
     7  
     8  import (
     9  	"context"
    10  	"io"
    11  )
    12  
    13  // contextKey is a value for use with context.WithValue.
    14  type contextKey struct {
    15  	name string
    16  }
    17  
    18  // RepositoryContextKey is a context key. It is used with context.Value() to get the current Repository for the context
    19  var RepositoryContextKey = &contextKey{"repository"}
    20  
    21  // RepositoryFromContext attempts to get the repository from the context
    22  func RepositoryFromContext(ctx context.Context, path string) *Repository {
    23  	value := ctx.Value(RepositoryContextKey)
    24  	if value == nil {
    25  		return nil
    26  	}
    27  
    28  	if repo, ok := value.(*Repository); ok && repo != nil {
    29  		if repo.Path == path {
    30  			return repo
    31  		}
    32  	}
    33  
    34  	return nil
    35  }
    36  
    37  type nopCloser func()
    38  
    39  func (nopCloser) Close() error { return nil }
    40  
    41  // RepositoryFromContextOrOpen attempts to get the repository from the context or just opens it
    42  func RepositoryFromContextOrOpen(ctx context.Context, path string) (*Repository, io.Closer, error) {
    43  	gitRepo := RepositoryFromContext(ctx, path)
    44  	if gitRepo != nil {
    45  		return gitRepo, nopCloser(nil), nil
    46  	}
    47  
    48  	gitRepo, err := OpenRepository(ctx, path)
    49  	return gitRepo, gitRepo, err
    50  }