You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo_base.go 1.2KB

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