remote

package
v0.36.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 8, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Overview

Package remote provides functionality for fetching and caching templates from remote sources.

Index

Constants

View Source
const DefaultCacheDir = ".tag/cache"

DefaultCacheDir is the default cache directory relative to user home.

View Source
const DefaultCacheTTL = 24 * time.Hour

DefaultCacheTTL is the default TTL for non-pinned cache entries.

Variables

View Source
var (
	// ErrNotCached indicates the template is not in the cache.
	ErrNotCached = errors.New("template not cached")

	// ErrAuthRequired indicates authentication is required but not provided.
	ErrAuthRequired = errors.New("authentication required")

	// ErrNotFound indicates the remote resource was not found.
	ErrNotFound = errors.New("resource not found")

	// ErrVersionNotFound indicates the specified version was not found.
	ErrVersionNotFound = errors.New("version not found")

	// ErrSubPathNotFound indicates the subpath doesn't exist in the template.
	ErrSubPathNotFound = errors.New("subpath not found")
)

Sentinel errors for remote operations.

Functions

func CleanupTempDir

func CleanupTempDir(path string) error

CleanupTempDir removes a temporary directory created by Fetch. This should be called after the template has been cached.

func DeriveName

func DeriveName(ref string) string

DeriveName extracts a library-compatible template name from a remote reference. For example, "bb:whalar/go-ms-service-template" becomes "go-ms-service-template", and "gh:user/cookiecutter-django" becomes "django".

func IsLocal

func IsLocal(input string) bool

IsLocal checks if a reference string points to a local resource.

Types

type AuthError

type AuthError struct {
	Provider Provider
	Message  string
	Err      error
}

AuthError represents an authentication error.

func (*AuthError) Error

func (e *AuthError) Error() string

func (*AuthError) Is

func (e *AuthError) Is(target error) bool

Is implements error matching for AuthError.

func (*AuthError) Unwrap

func (e *AuthError) Unwrap() error

type AuthProvider

type AuthProvider interface {
	// TokenFor returns the auth token for a provider, if available.
	TokenFor(provider Provider) (token string, ok bool)

	// GitAuth returns the appropriate go-git auth method for a reference.
	GitAuth(ref *Reference) (transport.AuthMethod, error)
}

AuthProvider provides authentication credentials for remote operations.

type Cache

type Cache interface {
	// Get returns the cached template path if it exists and is valid.
	// Returns the path, whether it was found, and any error.
	Get(key string) (path string, found bool, err error)

	// Set stores a template in the cache, copying from sourcePath.
	// Returns the cached path.
	Set(key string, sourcePath string, meta *CacheMeta) (cachedPath string, err error)

	// Invalidate removes a cache entry.
	Invalidate(key string) error

	// Path returns the full path for a cache key (without checking existence).
	Path(key string) string
}

Cache defines the interface for template caching.

type CacheEntry

type CacheEntry struct {
	Key  string
	Meta *CacheMeta // nil if metadata is missing/corrupt
}

CacheEntry contains a cache key and its metadata.

type CacheError

type CacheError struct {
	Key     string
	Op      string // "get", "set", "invalidate"
	Message string
	Err     error
}

CacheError represents an error with the cache.

func (*CacheError) Error

func (e *CacheError) Error() string

func (*CacheError) Unwrap

func (e *CacheError) Unwrap() error

type CacheMeta

type CacheMeta struct {
	OriginalRef string     `json:"original_ref"`
	ResolvedURL string     `json:"resolved_url"`
	Version     string     `json:"version,omitempty"`
	CommitSHA   string     `json:"commit_sha,omitempty"` // Resolved git commit SHA
	FetchedAt   time.Time  `json:"fetched_at"`
	ExpiresAt   *time.Time `json:"expires_at,omitempty"` // nil = never expires (pinned)
}

CacheMeta contains metadata about a cached template.

type EnvAuthProvider

type EnvAuthProvider struct{}

EnvAuthProvider implements AuthProvider using environment variables.

func NewEnvAuthProvider

func NewEnvAuthProvider() *EnvAuthProvider

NewEnvAuthProvider creates a new environment-based auth provider.

func (*EnvAuthProvider) GitAuth

func (p *EnvAuthProvider) GitAuth(ref *Reference) (transport.AuthMethod, error)

GitAuth returns the appropriate go-git auth method for a reference.

func (*EnvAuthProvider) TokenFor

func (p *EnvAuthProvider) TokenFor(provider Provider) (string, bool)

TokenFor returns the auth token from environment variables.

type FSCache

type FSCache struct {
	// contains filtered or unexported fields
}

FSCache implements Cache using the filesystem.

func NewFSCache

func NewFSCache(baseDir string) (*FSCache, error)

NewFSCache creates a new filesystem-based cache. If baseDir is empty, uses ~/.tag/cache/

func (*FSCache) Cleanup

func (c *FSCache) Cleanup() (int, error)

Cleanup removes expired cache entries and returns the count of removed entries.

func (*FSCache) ClearAll

func (c *FSCache) ClearAll() (int, error)

ClearAll removes all cache entries.

func (*FSCache) ClearExpired

func (c *FSCache) ClearExpired() (int, error)

ClearExpired removes only expired cache entries.

func (*FSCache) Get

func (c *FSCache) Get(key string) (string, bool, error)

Get returns the cached template path if it exists and is valid.

func (*FSCache) Invalidate

func (c *FSCache) Invalidate(key string) error

Invalidate removes a cache entry.

func (*FSCache) List

func (c *FSCache) List() ([]CacheEntry, error)

List returns all cache entries with their metadata.

func (*FSCache) Path

func (c *FSCache) Path(key string) string

Path returns the full path for a cache key.

func (*FSCache) Set

func (c *FSCache) Set(key, sourcePath string, meta *CacheMeta) (string, error)

Set stores a template in the cache by copying from sourcePath.

func (*FSCache) SetTTL

func (c *FSCache) SetTTL(ttl time.Duration)

SetTTL sets the TTL for non-pinned cache entries.

type FetchError

type FetchError struct {
	Ref     *Reference
	Message string
	Err     error
}

FetchError represents an error fetching a remote template.

func (*FetchError) Error

func (e *FetchError) Error() string

func (*FetchError) Unwrap

func (e *FetchError) Unwrap() error

type FetchResult

type FetchResult struct {
	Path      string // Local filesystem path to template
	CommitSHA string // Resolved git commit SHA (empty for zip/local)
	Version   string // Tag/branch/commit ref used
}

FetchResult contains the result of a fetch operation.

type Fetcher

type Fetcher interface {
	Fetch(ctx context.Context, ref *Reference) (*FetchResult, error)
}

Fetcher is the interface for all fetchers.

type GitFetcher

type GitFetcher struct {
	// contains filtered or unexported fields
}

GitFetcher fetches templates from Git repositories.

func NewGitFetcher

func NewGitFetcher(auth AuthProvider) *GitFetcher

NewGitFetcher creates a new Git fetcher with the given auth provider.

func (*GitFetcher) Fetch

func (f *GitFetcher) Fetch(ctx context.Context, ref *Reference) (*FetchResult, error)

Fetch clones the repository and returns the path to the template along with the resolved commit SHA.

func (*GitFetcher) FetchAtCommit

func (f *GitFetcher) FetchAtCommit(ctx context.Context, url, commitSHA, destDir string) (string, error)

FetchAtCommit clones a repository and checks out a specific commit SHA. Unlike Fetch, this performs a full clone (not shallow) since the target commit may not be reachable from advertised refs in a shallow clone.

func (*GitFetcher) ResolveLatestCommit

func (f *GitFetcher) ResolveLatestCommit(ctx context.Context, ref *Reference) (string, error)

ResolveLatestCommit resolves the latest commit SHA for the given reference using git ls-remote. It does not clone the repository.

Resolution precedence: exact tag match > exact branch match > HEAD (when ref has no version). Annotated tags are peeled to their target commit.

type LatestCommitResolver

type LatestCommitResolver interface {
	ResolveLatestCommit(ctx context.Context, ref *Reference) (string, error)
}

LatestCommitResolver can resolve the latest commit SHA for a template reference without performing a full clone.

type ParseError

type ParseError struct {
	Input   string
	Message string
}

ParseError represents an error parsing a template reference.

func (*ParseError) Error

func (e *ParseError) Error() string

type Provider

type Provider string

Provider indicates the Git hosting provider.

const (
	// ProviderGitHub represents GitHub.
	ProviderGitHub Provider = "github"
	// ProviderGitLab represents GitLab.
	ProviderGitLab Provider = "gitlab"
	// ProviderBitbucket represents Bitbucket.
	ProviderBitbucket Provider = "bitbucket"
	// ProviderGeneric represents any other Git host.
	ProviderGeneric Provider = "generic"
)

type Reference

type Reference struct {
	Original string        // Original input string
	Type     ReferenceType // Git, Zip, Local
	Provider Provider      // GitHub, GitLab, Bitbucket, Generic
	Host     string        // github.com, gitlab.com, etc.
	Owner    string        // user or org
	Repo     string        // repository name
	Version  string        // tag, branch, or commit (empty = default branch)
	SubPath  string        // subdirectory within repo/archive
	URL      string        // Resolved full URL for cloning/downloading
}

Reference represents a parsed template reference.

func Parse

func Parse(input string) (*Reference, error)

Parse parses a template reference string into a Reference struct. Supported formats:

  • Shorthand: gh:user/repo, gl:user/repo, bb:user/repo
  • With version: gh:user/repo@v1.0.0
  • With subpath: gh:user/repo/subdir or gh:user/repo@v1.0.0/subdir
  • Full Git URL: https://github.com/user/repo.git
  • Git+SSH: git+ssh://git@github.com/user/repo.git
  • Zip URL: https://example.com/template.zip
  • Local path: ./template, ../template, /absolute/path
  • Local zip: ./template.zip

func (*Reference) CacheKey

func (r *Reference) CacheKey() string

CacheKey returns a filesystem-safe cache key for this reference. For shorthands: gh_user_repo or gh_user_repo@v1.0.0 For URLs: _url_{hash}

func (*Reference) IsRemote

func (r *Reference) IsRemote() bool

IsRemote returns true if this reference requires network access to fetch.

func (*Reference) String

func (r *Reference) String() string

String returns a human-readable representation of the reference.

type ReferenceType

type ReferenceType string

ReferenceType indicates the type of template source.

const (
	// ReferenceTypeGit represents a Git repository source.
	ReferenceTypeGit ReferenceType = "git"
	// ReferenceTypeZip represents a zip file source (remote or local).
	ReferenceTypeZip ReferenceType = "zip"
	// ReferenceTypeLocal represents a local directory source.
	ReferenceTypeLocal ReferenceType = "local"
)

type ResolveOptions

type ResolveOptions struct {
	ForceUpdate bool // Ignore cache, always fetch fresh
	Offline     bool // Only use cache, don't fetch
}

ResolveOptions configures the resolution behavior.

type Resolver

type Resolver struct {
	// contains filtered or unexported fields
}

Resolver orchestrates reference parsing, caching, and fetching.

func NewResolver

func NewResolver() (*Resolver, error)

NewResolver creates a new Resolver with default configuration.

func NewResolverWithOptions

func NewResolverWithOptions(cacheDir string, auth AuthProvider) (*Resolver, error)

NewResolverWithOptions creates a new Resolver with custom configuration.

func (*Resolver) Resolve

func (r *Resolver) Resolve(ctx context.Context, input string, opts ResolveOptions) (*FetchResult, error)

Resolve takes a template reference string and returns a FetchResult containing the local path and, for git sources, the resolved commit SHA.

type ZipFetcher

type ZipFetcher struct {
	// contains filtered or unexported fields
}

ZipFetcher fetches templates from zip files (remote or local).

func NewZipFetcher

func NewZipFetcher() *ZipFetcher

NewZipFetcher creates a new Zip fetcher.

func (*ZipFetcher) Fetch

func (f *ZipFetcher) Fetch(ctx context.Context, ref *Reference) (*FetchResult, error)

Fetch downloads (if remote) and extracts the zip file. Returns the path to the extracted template directory. CommitSHA is always empty for zip sources.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL