code.gitea.io/gitea@v1.19.3/modules/git/repo_base.go (about)

     1  // Copyright 2021 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package git
     5  
     6  import (
     7  	"context"
     8  	"io"
     9  )
    10  
    11  // contextKey is a value for use with context.WithValue.
    12  type contextKey struct {
    13  	name string
    14  }
    15  
    16  // RepositoryContextKey is a context key. It is used with context.Value() to get the current Repository for the context
    17  var RepositoryContextKey = &contextKey{"repository"}
    18  
    19  // RepositoryFromContext attempts to get the repository from the context
    20  func RepositoryFromContext(ctx context.Context, path string) *Repository {
    21  	value := ctx.Value(RepositoryContextKey)
    22  	if value == nil {
    23  		return nil
    24  	}
    25  
    26  	if repo, ok := value.(*Repository); ok && repo != nil {
    27  		if repo.Path == path {
    28  			return repo
    29  		}
    30  	}
    31  
    32  	return nil
    33  }
    34  
    35  type nopCloser func()
    36  
    37  func (nopCloser) Close() error { return nil }
    38  
    39  // RepositoryFromContextOrOpen attempts to get the repository from the context or just opens it
    40  func RepositoryFromContextOrOpen(ctx context.Context, path string) (*Repository, io.Closer, error) {
    41  	gitRepo := RepositoryFromContext(ctx, path)
    42  	if gitRepo != nil {
    43  		return gitRepo, nopCloser(nil), nil
    44  	}
    45  
    46  	gitRepo, err := OpenRepository(ctx, path)
    47  	return gitRepo, gitRepo, err
    48  }