get

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsCatalogReference added in v0.7.0

func IsCatalogReference(s string) bool

IsCatalogReference returns true when s looks like a catalog name or remote registry reference rather than a local file path. The check is intentionally conservative: when in doubt it returns false so callers are guided to use -f/--file instead of silently treating a filesystem path as a catalog lookup.

Returns false (local file path) when:

  • s starts with "/" (absolute path)
  • s starts with "." (relative path like ./foo or ../bar)
  • s ends with ".yaml", ".yml", or ".json" (file extension)
  • s starts with a Windows drive letter (e.g., "C:\dir\sol" or "C:/dir/sol")
  • s contains a backslash (Windows path separator)
  • s contains "/" but the first path segment does not look like a hostname (i.e., does not contain "." or ":") — catches relative paths like "configs/solution" that lack a leading "./" but are still local

Returns true (catalog / remote reference) for:

  • bare names ("my-app"), versioned names ("my-app@1.0.0")
  • registry refs where the first segment is hostname-like ("ghcr.io/org/sol:v1", "localhost:5000/sol")
  • URLs ("https://...", "oci://...")

func IsUnambiguousCatalogReference added in v0.11.0

func IsUnambiguousCatalogReference(s string) bool

IsUnambiguousCatalogReference returns true only when s is clearly a catalog reference rather than a bare name that could be an action or resolver name. Unlike IsCatalogReference, bare words like "deploy" return false. Accepted forms:

  • versioned refs ("my-app@1.0.0")
  • registry refs ("ghcr.io/org/sol", "localhost:5000/sol")
  • URLs ("https://...", "oci://...")

func PossibleSolutionPaths

func PossibleSolutionPaths() []string

PossibleSolutionPaths returns a slice of possible solution file paths by combining each root solution folder with each solution file name defined in the settings. It constructs the full path for each combination and aggregates them into a list.

func ValidatePositionalRef added in v0.7.0

func ValidatePositionalRef(arg, fileFlag, cmdUsage string) error

ValidatePositionalRef validates a positional CLI argument intended to be a catalog or registry reference. Returns an error if:

  • fileFlag is non-empty (both -f/--file and a positional arg were provided)
  • arg looks like a local file path rather than a catalog/registry name

cmdUsage is included in the error message to suggest the correct invocation (e.g., "scafctl explain solution").

Types

type BundleAwareCatalogResolver

type BundleAwareCatalogResolver interface {
	CatalogResolver
	// FetchSolutionWithBundle retrieves a solution and its bundle from the catalog.
	// Returns the solution content bytes, bundle tar bytes (nil if no bundle), and any error.
	FetchSolutionWithBundle(ctx context.Context, nameWithVersion string) (content, bundleData []byte, err error)
}

BundleAwareCatalogResolver extends CatalogResolver with bundle fetching.

type CatalogResolver

type CatalogResolver interface {
	// FetchSolution retrieves a solution from the catalog by name[@version].
	// Returns the solution content bytes and any error.
	FetchSolution(ctx context.Context, nameWithVersion string) ([]byte, error)
}

CatalogResolver is an interface for fetching solutions from a catalog. This avoids a circular dependency with the catalog package.

type CatalogSourcer added in v0.10.1

type CatalogSourcer interface {
	LastResolvedCatalog() string
}

CatalogSourcer is optionally implemented by CatalogResolver to report which catalog satisfied the most recent fetch. Used to include the catalog name in verbose output.

type DiscoveryResult added in v0.10.0

type DiscoveryResult struct {
	// Path is the discovered file path. Empty if nothing found.
	Path string
	// IsActionFile is true when the discovered file is an actions.yaml/yml.
	IsActionFile bool
	// Mode is the discovery mode that was used.
	Mode settings.DiscoveryMode
	// AlternatePath is populated when action mode finds an actions file and a
	// solution.yaml also exists in the same directory.
	AlternatePath string
}

DiscoveryResult holds metadata from the last FindSolution call.

type Getter

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

func NewGetter

func NewGetter(opts ...Option) *Getter

NewGetter creates a new Getter instance with the provided options. By default, it sets up the Getter with the standard file reading and stat functions, a default HTTP client, and a discard logger. Options can be supplied to customize the behavior of the Getter.

func NewGetterFromContext added in v0.7.0

func NewGetterFromContext(ctx context.Context, opts ...Option) *Getter

NewGetterFromContext creates a Getter using the binary name from settings.Run in the context to configure solution discovery paths. If the context does not contain settings or the binary name matches the default, no override is applied. Additional options are applied after the context-derived configuration.

func (*Getter) FindSolution

func (o *Getter) FindSolution() string

FindSolution searches for a solution file by iterating over the configured root solution folders and solution file names. It returns the full path to the first solution file found using the provided stat function. If no solution file is found, it returns an empty string.

When discoveryMode is set, the file name list is overridden via settings.FileNamesForMode before searching. The result metadata is stored and can be retrieved via LastDiscoveryResult().

func (*Getter) FromLocalFileSystem

func (o *Getter) FromLocalFileSystem(ctx context.Context, path string) (*solution.Solution, error)

FromLocalFileSystem reads a solution from the local filesystem at the specified path. It uses the configured readFile function (defaults to os.ReadFile) to read the file contents, then unmarshals the data into a solution.Solution object. Logging is performed at various stages, including reading the file, unmarshalling, and error handling. If successful, the solution's path is set and the populated solution is returned. On failure, an empty solution and a wrapped error are returned.

Parameters:

ctx  - The context for cancellation and deadlines (currently unused).
path - The filesystem path to the solution file.

Returns:

*solution.Solution - The loaded solution object (empty on error).
error              - An error if reading or unmarshalling fails.

func (*Getter) FromURL

func (o *Getter) FromURL(ctx context.Context, url string) (*solution.Solution, error)

FromURL fetches a solution from the specified URL, unmarshals its contents, and returns a Solution object. It validates the URL, performs an HTTP GET request, checks for a successful response, reads the response body, and unmarshals the solution data. If any step fails, an error is returned with appropriate logging. The solution's path is set to the provided URL upon successful retrieval.

Parameters:

ctx - The context for controlling cancellation and timeouts.
url - The URL from which to fetch the solution.

Returns:

*solution.Solution - The unmarshalled solution object.
error - An error if the operation fails at any step.

func (*Getter) Get

func (o *Getter) Get(ctx context.Context, path string) (*solution.Solution, error)

Get retrieves a Solution from the specified path, which can be a local file or a URL. If the path is empty, it attempts to find a solution file in default locations. The method records the time taken to retrieve the solution for metrics purposes. Returns an error if no solution path is provided or found.

Parameters:

ctx  - The context for cancellation and deadlines.
path - The path to the solution file or URL.

Returns:

*solution.Solution - The retrieved solution object.
error              - An error if retrieval fails.

func (*Getter) GetWithBundle

func (o *Getter) GetWithBundle(ctx context.Context, path string) (*solution.Solution, []byte, error)

GetWithBundle retrieves a Solution and its bundle tar data from the specified path. bundleData is nil when the solution has no bundle or comes from a local file/URL.

func (*Getter) LastDiscoveryResult added in v0.10.0

func (o *Getter) LastDiscoveryResult() DiscoveryResult

LastDiscoveryResult returns metadata from the most recent FindSolution call.

func (*Getter) SetDiscoveryMode added in v0.10.0

func (o *Getter) SetDiscoveryMode(mode settings.DiscoveryMode)

SetDiscoveryMode sets the discovery mode on the Getter. This is useful when the mode needs to be changed after construction (e.g., from prepare).

type Interface

type Interface interface {
	FromLocalFileSystem(ctx context.Context, path string) (*solution.Solution, error)
	FromURL(ctx context.Context, url string) (*solution.Solution, error)
	Get(ctx context.Context, path string) (*solution.Solution, error)
	// GetWithBundle retrieves a Solution and its bundle tar data (if any).
	// bundleData is nil when the solution has no bundle or comes from a local file.
	GetWithBundle(ctx context.Context, path string) (sol *solution.Solution, bundleData []byte, err error)
	FindSolution() string
}

Interface defines methods for retrieving a Solution from different sources. Implementations should provide logic to load a Solution either from the local file system, from a remote URL, or automatically discover from default locations.

Methods:

  • FromLocalFileSystem: Loads a Solution from a specified local file path.
  • FromUrl: Loads a Solution from a specified remote URL.
  • Get: Loads a Solution from a path (local or URL) with auto-discovery support.
  • FindSolution: Searches for a solution file in default locations.

type MockGetter

type MockGetter struct {
	mock.Mock
}

MockGetter is a mock implementation of the Interface for testing purposes. It uses testify/mock to provide flexible mocking capabilities.

Basic Usage Example:

func TestMyFunction(t *testing.T) {
    // Create a mock
    mockGetter := &MockGetter{}

    // Set up expectations
    expectedSolution := &solution.Solution{Name: "test-solution"}
    mockGetter.On("FromLocalFileSystem", mock.Anything, "/path/to/solution.yaml").
        Return(expectedSolution, nil)

    // Use the mock in your code
    result, err := mockGetter.FromLocalFileSystem(context.Background(), "/path/to/solution.yaml")
    require.NoError(t, err)
    assert.Equal(t, expectedSolution, result)

    // Verify all expectations were met
    mockGetter.AssertExpectations(t)
}

Advanced Usage - Multiple Calls:

mockGetter.On("FromLocalFileSystem", mock.Anything, "/path1").
    Return(&solution.Solution{}, nil).Once()
mockGetter.On("FromLocalFileSystem", mock.Anything, "/path2").
    Return(nil, errors.New("not found")).Once()

Advanced Usage - Argument Matchers:

// Match any context
mockGetter.On("FromUrl", mock.Anything, "https://example.com").
    Return(&solution.Solution{}, nil)

// Match specific context with custom matcher
mockGetter.On("FromUrl", mock.MatchedBy(func(ctx context.Context) bool {
    return ctx.Value("key") == "value"
}), "https://example.com").Return(&solution.Solution{}, nil)
Example

ExampleMockGetter demonstrates basic usage of the MockGetter for testing.

// Create a new mock
mockGetter := &MockGetter{}

// Set up expectations
expectedSolution := &solution.Solution{}
mockGetter.On("FromLocalFileSystem", mock.Anything, "/path/to/solution.yaml").
	Return(expectedSolution, nil)

// Use the mock in your code
ctx := context.Background()
sol, err := mockGetter.FromLocalFileSystem(ctx, "/path/to/solution.yaml")
if err != nil {
	panic(err)
}

_ = sol // Use the solution

// In a real test, you would assert expectations at the end
// mockGetter.AssertExpectations(t)

func (*MockGetter) AssertExpectations

func (m *MockGetter) AssertExpectations(t mock.TestingT) bool

AssertExpectations asserts that all expected calls were made. This should be called at the end of tests to verify mock expectations.

Example usage:

func TestSomething(t *testing.T) {
    mockGetter := &MockGetter{}
    mockGetter.On("FromLocalFileSystem", mock.Anything, "/path").Return(&solution.Solution{}, nil)
    // ... test code that uses mockGetter ...
    mockGetter.AssertExpectations(t)
}

func (*MockGetter) FindSolution

func (m *MockGetter) FindSolution() string

FindSolution mocks the FindSolution method which searches for a solution file in default locations. It returns the configured mock response.

Example usage:

mockGetter := &MockGetter{}
mockGetter.On("FindSolution").Return("/path/to/solution.yaml")

func (*MockGetter) FromLocalFileSystem

func (m *MockGetter) FromLocalFileSystem(ctx context.Context, path string) (*solution.Solution, error)

FromLocalFileSystem mocks the FromLocalFileSystem method of the Interface. It returns the configured mock response for the given path.

Example usage:

mockGetter := &MockGetter{}
expectedSolution := &solution.Solution{Name: "test"}
mockGetter.On("FromLocalFileSystem", mock.Anything, "/path/to/solution.yaml").
    Return(expectedSolution, nil)

func (*MockGetter) FromURL

func (m *MockGetter) FromURL(ctx context.Context, url string) (*solution.Solution, error)

FromURL mocks the FromURL method which retrieves a solution from a URL. It returns the configured mock response for the given URL.

Example usage:

mockGetter := &MockGetter{}
expectedSolution := &solution.Solution{Name: "test"}
mockGetter.On("FromURL", mock.Anything, "https://example.com/solution.yaml").
    Return(expectedSolution, nil)

func (*MockGetter) Get

func (m *MockGetter) Get(ctx context.Context, path string) (*solution.Solution, error)

Get mocks the Get method which retrieves a solution from a path (URL or local file). It returns the configured mock response for the given path.

Example usage:

mockGetter := &MockGetter{}
expectedSolution := &solution.Solution{Name: "test"}
mockGetter.On("Get", mock.Anything, "/path/to/solution.yaml").
    Return(expectedSolution, nil)

func (*MockGetter) GetWithBundle

func (m *MockGetter) GetWithBundle(ctx context.Context, path string) (*solution.Solution, []byte, error)

GetWithBundle mocks the GetWithBundle method which retrieves a solution and its bundle.

type Option

type Option func(*Getter)

Option defines a function type that modifies a Getter instance. It can be used to configure or customize the behavior of Getter by applying various options.

func WithAppConfig

func WithAppConfig(cfg *config.HTTPClientConfig, logger logr.Logger) Option

WithAppConfig returns an Option that configures the HTTP client using the application configuration. It creates an HTTP client with settings from the provided config.HTTPClientConfig. The logger is used for HTTP client logging.

func WithCatalogResolver

func WithCatalogResolver(resolver CatalogResolver) Option

WithCatalogResolver returns an Option that sets the catalog resolver for the Getter. When a catalog resolver is set, the Getter will attempt to resolve bare names (names without path separators or URL schemes) from the catalog first.

func WithCustomActionFiles added in v0.10.0

func WithCustomActionFiles(files []string) Option

WithCustomActionFiles returns an Option that overrides the action file names used when discovery mode is DiscoveryModeAction.

func WithDiscoveryMode added in v0.10.0

func WithDiscoveryMode(mode settings.DiscoveryMode) Option

WithDiscoveryMode returns an Option that sets the discovery mode on the Getter. This controls which file names FindSolution searches for.

func WithHTTPClient

func WithHTTPClient(client *httpc.Client) Option

WithHTTPClient returns an Option that sets the HTTP client for the Getter. This allows customization of the HTTP client used for network requests.

func WithLogger

func WithLogger(logger logr.Logger) Option

WithLogger returns an Option that sets the logger for the Getter. It allows customizing the logging behavior by providing a logr.Logger instance.

func WithReadFile

func WithReadFile(readFile fs.ReadFileFunc) Option

WithReadFile returns an Option that sets the readFile function used by the Getter. This allows customization of how files are read, enabling dependency injection for testing or alternative file systems.

readFile: a function conforming to fs.ReadFileFunc, used to read files. Returns: an Option that sets the Getter's readFile field.

func WithRemoteResolver added in v0.8.0

func WithRemoteResolver(resolver RemoteResolver) Option

WithRemoteResolver returns an Option that sets the remote resolver for the Getter. When a remote resolver is set, the Getter will attempt to resolve Docker-style OCI references (e.g., "ghcr.io/myorg/starter-kit@1.0.0") from remote registries.

func WithSolutionDiscovery added in v0.7.0

func WithSolutionDiscovery(folders, fileNames []string) Option

WithSolutionDiscovery overrides the default solution folder and file name lists used by FindSolution. Pass the result of settings.SolutionFoldersFor and settings.SolutionFileNamesFor to search for <binaryName>.yaml etc.

func WithStatFunc

func WithStatFunc(statFunc fs.StatFunc) Option

WithStatFunc returns an Option that sets the statFunc field of a Getter. The provided statFunc is used to retrieve file information during operations. This allows customization of how file statistics are obtained.

type RemoteResolver added in v0.8.0

type RemoteResolver interface {
	// FetchRemoteSolution fetches a solution from a remote OCI reference.
	// The ref is the full remote reference string (e.g., "ghcr.io/myorg/starter-kit@1.0.0").
	FetchRemoteSolution(ctx context.Context, ref string) (content, bundleData []byte, err error)
}

RemoteResolver resolves Docker-style OCI remote references (e.g., "ghcr.io/myorg/starter-kit@1.0.0"). Implementations are responsible for registry authentication and fetching.

Jump to

Keyboard shortcuts

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