domain

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2021 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MetadataValueKey is the root key for the metadata variables.
	MetadataValueKey = "Metadata"
	// RepositoryValueKey is the key for the GitRepository variable.
	RepositoryValueKey = "Repository"
	// TemplateValueKey is the key for the Template variable.
	TemplateValueKey = "Template"
	// ValuesKey is the key for user-defined variables.
	ValuesKey = "Values"
)

Variables

View Source
var ErrInvalidArgument = errors.New("invalid argument")

ErrInvalidArgument is an error that indicates that a particular field is invalid.

View Source
var ErrKeyNotFound = errors.New("key not found")

ErrKeyNotFound is an error that indicates that a particular key was not found.

Functions

This section is empty.

Types

type CleanupContext

type CleanupContext struct {
	Repository *GitRepository
	ValueStore ValueStore
	// contains filtered or unexported fields
}

type CleanupService

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

func NewCleanupService

func NewCleanupService(
	instrumentation CleanupServiceInstrumentation,
) *CleanupService

func (*CleanupService) CleanupUnwantedFiles

func (s *CleanupService) CleanupUnwantedFiles(ctx CleanupContext) error

type CleanupServiceInstrumentation

type CleanupServiceInstrumentation interface {
	// FetchedFilesToDelete logs a message indicating that fetching file paths to delete from ValueStore was successful but only if fetchErr is nil.
	// Returns fetchErr unmodified for method chaining.
	FetchedFilesToDelete(fetchErr error, files []Path) error
	// DeletedFile logs a message indicating that deleting file occurred.
	DeletedFile(file Path)
	// WithRepository returns an instance that has the given repository as scope.
	WithRepository(repository *GitRepository) CleanupServiceInstrumentation
}

CleanupServiceInstrumentation provides methods for domain observability.

type Color

type Color string

Color is a 6-digit uppercase hexadecimal string value with '#' prefix

func (Color) CheckValue

func (c Color) CheckValue() error

CheckValue returns ErrInvalidArgument in case the string is not in an acceptable format. Returns nil otherwise.

func (Color) String

func (c Color) String() string

String returns the color in hexadecimal RGB format

type CommitOptions

type CommitOptions struct {
	// Message contains the commit message.
	Message string
	// Amend will edit the last commit instead of creating a new one.
	Amend bool
}

CommitOptions contains settings to influence the GitRepositoryStore.Commit action.

type GitRepository

type GitRepository struct {
	// RootDir is the full path to the Git root directory in the local filesystem.
	RootDir Path
	// URL is the remote URL of origin.
	URL *GitURL
	// PullRequest is the associated PullRequest for this repository in the remote Git hosting service.
	PullRequest *PullRequest
	// Labels contains the LabelSet that is present in the remote Git hosting service.
	Labels LabelSet

	// CommitBranch in the branch name of the current branch the working tree is in.
	CommitBranch string
	// DefaultBranch is the branch name of the remote default branch (usually `master` or `main`).
	DefaultBranch string
}

GitRepository is the heart of the domain.

The model itself doesn't feature common actions like Commit. It was decided against adding those rich functionalities since that would mean implementing a replayable history of actions to keep in memory. This was considered too complicated, thus these actions are to be implemented in Stores.

func NewGitRepository

func NewGitRepository(u *GitURL, root Path) *GitRepository

NewGitRepository creates a new instance.

func (GitRepository) AsValues

func (r GitRepository) AsValues() Values

AsValues returns the metadata as Values for rendering.

func (*GitRepository) SetLabels

func (r *GitRepository) SetLabels(labels LabelSet) error

SetLabels validates and sets the new LabelSet. Returns nil if there are no empty Label names or duplicates.

type GitRepositoryStore

type GitRepositoryStore interface {
	// FetchGitRepositories loads a list of GitRepository from a configuration set.
	// Returns an empty list on first error.
	FetchGitRepositories() ([]*GitRepository, error)

	// Clone will download the given GitRepository to local filesystem.
	// The location is specified in GitRepository.RootDir.
	Clone(repository *GitRepository) error
	// Checkout checks out the GitRepository.CommitBranch.
	Checkout(repository *GitRepository) error
	// Fetch retrieves the objects and refs from remote.
	Fetch(repository *GitRepository) error
	// Reset current HEAD to GitRepository.CommitBranch.
	Reset(repository *GitRepository) error
	// Pull integrates objects from remote.
	Pull(repository *GitRepository) error

	// Add stages all files in GitRepository.RootDir.
	Add(repository *GitRepository) error
	// Commit records changes in the repository.
	Commit(repository *GitRepository, options CommitOptions) error
	// Diff returns a `patch`-compatible diff between HEAD and previous commit as string.
	// The diff may be empty.
	Diff(repository *GitRepository) (string, error)

	// Push updates remote refs.
	Push(repository *GitRepository, options PushOptions) error
}

GitRepositoryStore provides methods to interact with GitRepository on the local filesystem. Most methods described follow the corresponding Git operations.

In Domain-Driven Design language, the term `Store` corresponds to `Repository`, but to avoid name clash it was named `Store`.

type GitURL

type GitURL url.URL

GitURL is the same as url.URL but with additional helper methods.

func FromURL

func FromURL(url *url.URL) *GitURL

FromURL converts the given url.URL into a GitURL.

func (*GitURL) AsURL

func (u *GitURL) AsURL() *url.URL

AsURL converts GitURL to url.URL

func (*GitURL) GetFullName

func (u *GitURL) GetFullName() string

GetFullName returns the hostname (or host:port) joined by GetNamespace and GetRepositoryName delimited by slashes.

func (*GitURL) GetNamespace

func (u *GitURL) GetNamespace() string

GetNamespace returns the middle element(s) of the Git URL. Depending on the Git hosting service, this name may contain multiple slashes. Any leading "/" is removed.

func (*GitURL) GetRepositoryName

func (u *GitURL) GetRepositoryName() string

GetRepositoryName returns the last element of the Git URL. Strips the name from any .git extensions in the URL.

func (*GitURL) Redacted

func (u *GitURL) Redacted() string

Redacted returns the same as url.URL:Redacted().

func (*GitURL) String

func (u *GitURL) String() string

String returns the same as url.URL:String().

type Label

type Label struct {
	// Name is the label name
	Name string
	// Description adds additional details to the label.
	Description string
	// contains filtered or unexported fields
}

Label is a Value object containing the properties of labels in a Git hosting service.

func (Label) GetColor

func (l Label) GetColor() Color

GetColor returns the color of the Label.

func (Label) IsEqualTo

func (l Label) IsEqualTo(label Label) bool

IsEqualTo returns true if all properties of Label are equal.

func (Label) IsSameAs

func (l Label) IsSameAs(label Label) bool

IsSameAs returns true if each Label.Name is equal.

func (*Label) SetColor

func (l *Label) SetColor(color Color) error

SetColor sets the color of the Label. If Color.CheckValue fails, then that error is returned.

type LabelSet

type LabelSet []Label

LabelSet is a set of Label.

func FromStringSlice added in v0.2.1

func FromStringSlice(labels []string) LabelSet

FromStringSlice returns a LabelSet with the names from the given string slice. Label.GetColor and Label.Description are empty.

func (LabelSet) CheckForDuplicates

func (s LabelSet) CheckForDuplicates() error

CheckForDuplicates returns an error if two or more Label have the same Label.Name.

func (LabelSet) CheckForEmptyLabelNames

func (s LabelSet) CheckForEmptyLabelNames() error

CheckForEmptyLabelNames returns an error if there's a Label in the set that is an empty string.

func (LabelSet) FindLabelByName

func (s LabelSet) FindLabelByName(label string) (Label, bool)

FindLabelByName returns the Label by given Name, if there is one matching.

func (LabelSet) Merge

func (s LabelSet) Merge(other LabelSet) LabelSet

Merge returns a new copy of LabelSet that contains the Label from other if they are missing in the original slice, and replaces existing ones. A label to replace is determined by equality of LabelSet.FindLabelByName.

No validation checks are performed. The original order is not preserved. Duplicates are removed from the result.

func (LabelSet) String

func (s LabelSet) String() string

String implements fmt.Stringer.

func (LabelSet) Without

func (s LabelSet) Without(other LabelSet) LabelSet

Without returns a new LabelSet that contain only the labels that do not exist in other set. A label is not included in the result if the name matches.

No validation checks are performed. The original order is preserved.

type LabelStore

type LabelStore interface {
	// FetchLabelsForRepository retrieves a LabelSet for the given repository.
	FetchLabelsForRepository(repository *GitRepository) (LabelSet, error)
	// EnsureLabelsForRepository creates or updates the given LabelSet in the given repository.
	// Labels that exist remotely, but not in the given LabelSet are ignored.
	// Remote labels have to be updated when Label.GetColor or Label.Description are not matching.
	//
	// Renaming labels are currently not supported.
	EnsureLabelsForRepository(repository *GitRepository, labels LabelSet) error
	// RemoveLabelsFromRepository remotely removes all labels in the given LabelSet.
	// Only the Label.Name is relevant to determine label equality.
	RemoveLabelsFromRepository(repository *GitRepository, labels LabelSet) error
}

LabelStore provides methods to interact with labels on a Git hosting service.

In Domain-Driven Design language, the term `Store` corresponds to `Repository`, but to avoid name clash it was named `Store`.

type Path

type Path string

Path is a Value object identifying a file path.

func NewFilePath

func NewFilePath(elems ...string) Path

NewFilePath constructs a new Path joined by the given elements. Paths are joined with filepath.Join.

func NewPath

func NewPath(elems ...string) Path

NewPath constructs a new Path joined by the given elements. Paths are joined with path.Join.

func (Path) Delete

func (p Path) Delete()

Delete removes the path (and possibly all children if it's a directory), ignoring any errors. If you need error handling, use os.RemoveAll directly.

func (Path) DirExists

func (p Path) DirExists() bool

DirExists returns true if the path exists in the local file system and is a directory.

func (Path) Exists

func (p Path) Exists() bool

Exists returns true if the path exists in the local file system.

func (Path) FileExists

func (p Path) FileExists() bool

FileExists returns true if the path exists in the local file system and is a file.

func (Path) Join

func (p Path) Join(elems ...Path) Path

Join takes this Path as root and makes a new Path with given elements.

func (Path) String

func (p Path) String() string

String returns a string representation of itself.

type Permissions

type Permissions fs.FileMode

Permissions is an alias for file permissions.

func (Permissions) FileMode

func (p Permissions) FileMode() fs.FileMode

FileMode converts Permissions to fs.FileMode.

func (Permissions) Octal

func (p Permissions) Octal() string

Octal returns an octal permission representation (Linux)

type PullRequest

type PullRequest struct {

	// CommitBranch is the branch name of the current working tree.
	CommitBranch string
	// BaseBranch is the branch name into which CommitBranch should be merged into.
	BaseBranch string
	// contains filtered or unexported fields
}

PullRequest is a model that represents a pull request in a remote Git hosting service.

func NewPullRequest

func NewPullRequest(
	number *PullRequestNumber, title, body, commitBranch, baseBranch string,
	labels LabelSet,
) (*PullRequest, error)

NewPullRequest returns a new instance. An error is returned if the given properties do not satisfy constraints.

func (*PullRequest) AttachLabels

func (pr *PullRequest) AttachLabels(labels LabelSet) error

AttachLabels sets the LabelSet of this PR. There cannot be duplicates or labels with no name.

func (*PullRequest) ChangeDescription

func (pr *PullRequest) ChangeDescription(title, body string) error

ChangeDescription changes the title and body of this PR. An error is returned if the title is empty.

func (*PullRequest) GetBody

func (pr *PullRequest) GetBody() string

GetBody returns the PR description.

func (*PullRequest) GetLabels

func (pr *PullRequest) GetLabels() LabelSet

GetLabels returns the LabelSet of this PR.

func (*PullRequest) GetNumber

func (pr *PullRequest) GetNumber() *PullRequestNumber

GetNumber returns the pull request number. It returns nil if this PullRequest does not yet exist in remote.

func (*PullRequest) GetTitle

func (pr *PullRequest) GetTitle() string

GetTitle returns the PR title.

func (*PullRequest) SetNumber

func (pr *PullRequest) SetNumber(nr *PullRequestNumber) error

SetNumber sets the pull request number.

type PullRequestNumber

type PullRequestNumber int

PullRequestNumber identifies a PullRequest by a number in a Git hosting service.

func NewPullRequestNumber

func NewPullRequestNumber(nr *int) *PullRequestNumber

NewPullRequestNumber takes the given number and returns a new instance. If nr is nil, then nil is returned.

func (*PullRequestNumber) Int

func (nr *PullRequestNumber) Int() *int

Int returns nil if nr is also nil. Otherwise, it returns an int pointer.

func (PullRequestNumber) String

func (nr PullRequestNumber) String() string

String returns the number prefixed with `#`.

type PullRequestService

type PullRequestService struct {
}

func NewPullRequestService

func NewPullRequestService() *PullRequestService

func (*PullRequestService) NewPullRequestForRepository

func (prs *PullRequestService) NewPullRequestForRepository(prsCtx PullRequestServiceContext) error

type PullRequestServiceContext

type PullRequestServiceContext struct {
	Repository     *GitRepository
	TemplateEngine TemplateEngine
	Body           string
	Title          string
	TargetBranch   string
	Labels         LabelSet
}

type PullRequestStore

type PullRequestStore interface {
	// FindMatchingPullRequest returns the PullRequest that has the same branch as GitRepository.CommitBranch.
	// If not found, it returns nil without error.
	FindMatchingPullRequest(repository *GitRepository) (*PullRequest, error)

	// EnsurePullRequest creates or updates the GitRepository.PullRequest in the repository.
	//
	//  * This operation does not alter any properties of existing labels.
	//  * Existing labels are left untouched, but any extraneous labels are removed.
	//  * Title and Body are updated.
	//  * Existing Commit and Base branches are left untouched.
	//
	// The first error encountered aborts the operation.
	EnsurePullRequest(repository *GitRepository) error
}

PullRequestStore provides methods to interact with PullRequest on a Git hosting service.

In Domain-Driven Design language, the term `Store` corresponds to `Repository`, but to avoid name clash it was named `Store`.

type PushOptions

type PushOptions struct {
	// Force overwrites the remote state when pushing.
	Force bool
}

PushOptions contains settings to influence the GitRepositoryStore.Push action.

type RenderContext

type RenderContext struct {
	Repository    *GitRepository
	ValueStore    ValueStore
	TemplateStore TemplateStore
	Engine        TemplateEngine
	// contains filtered or unexported fields
}

RenderContext represents a single rendering context for a GitRepository.

type RenderResult

type RenderResult string

RenderResult represents the string value after rendering from a Template.

func (RenderResult) String

func (r RenderResult) String() string

String implements fmt.Stringer.

func (RenderResult) WriteToFile

func (r RenderResult) WriteToFile(path Path, permissions Permissions) error

WriteToFile writes the content to the given Path with given Permissions. Otherwise, an error is returned.

type RenderService

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

RenderService is a domain service that helps rendering templates.

func NewRenderService

func NewRenderService(instrumentation RenderServiceInstrumentation) *RenderService

func (*RenderService) RenderTemplates

func (s *RenderService) RenderTemplates(ctx RenderContext) error

RenderTemplates loads the Templates and renders them in the GitRepository.RootDir of the given RenderContext.Repository.

type RenderServiceInstrumentation

type RenderServiceInstrumentation interface {
	// FetchedTemplatesFromStore logs a message indicating that fetching templates from TemplateStore was successful, but only if fetchErr is nil.
	// Returns fetchErr unmodified for method chaining.
	FetchedTemplatesFromStore(fetchErr error) error
	// FetchedValuesForTemplate logs a message indicating that fetching Values from ValueStore was successful but only if fetchErr is nil.
	// Returns fetchErr unmodified for method chaining.
	FetchedValuesForTemplate(fetchErr error, template *Template) error
	// AttemptingToRenderTemplate logs a message indicating that the actual rendering is about to begin.
	AttemptingToRenderTemplate(template *Template)
	WrittenRenderResultToFile(template *Template, targetPath Path, writeErr error) error
	// WithRepository creates a new RenderServiceInstrumentation instance using the given GitRepository as context.
	WithRepository(repository *GitRepository) RenderServiceInstrumentation
}

RenderServiceInstrumentation provides methods for domain observability.

type Template

type Template struct {
	// RelativePath is the Path reference to where the template file is contained within the template root directory.
	RelativePath Path
	// FilePermissions defines what file permissions this template file has.
	// Rendered files should have the same permissions as template files.
	FilePermissions Permissions
}

Template is a reference to a file that contains special syntax.

func NewTemplate

func NewTemplate(relPath Path, perms Permissions) *Template

NewTemplate returns a new instance.

func (*Template) AsValues

func (t *Template) AsValues() Values

AsValues returns the metadata as Values for rendering.

func (*Template) CleanPath

func (t *Template) CleanPath() Path

CleanPath returns a new Path with the first occurrence of ".tpl" in the base file name removed.

func (*Template) Render

func (t *Template) Render(values Values, engine TemplateEngine) (RenderResult, error)

Render takes the given Values and returns a RenderResult from the given TemplateEngine.

type TemplateEngine

type TemplateEngine interface {
	// Execute renders the given Template with the given Values.
	Execute(template *Template, values Values) (RenderResult, error)

	// ExecuteString renders the given template string with the given Values.
	ExecuteString(template string, values Values) (RenderResult, error)
}

TemplateEngine provides methods to process a Template.

type TemplateStore

type TemplateStore interface {
	// FetchTemplates lists all templates.
	// It aborts on first error.
	FetchTemplates() ([]*Template, error)
}

TemplateStore provides methods to load Template from template root directory.

In Domain-Driven Design language, the term `Store` corresponds to `Repository`, but to avoid name clash it was named `Store`.

type ValueStore

type ValueStore interface {
	// FetchValuesForTemplate retrieves the Values for the given template.
	FetchValuesForTemplate(template *Template, repository *GitRepository) (Values, error)
	// FetchUnmanagedFlag returns true if the given template should not be rendered.
	// The implementation may return ErrKeyNotFound if the flag is undefined, as the boolean 'false' is ambiguous.
	FetchUnmanagedFlag(template *Template, repository *GitRepository) (bool, error)
	// FetchTargetPath returns an alternative output path for the given template relative to the Git repository.
	// An empty string indicates that there is no alternative path configured.
	FetchTargetPath(template *Template, repository *GitRepository) (Path, error)
	// FetchFilesToDelete returns a slice of Path that should be deleted in the Git repository.
	// The paths are relative to the Git root directory.
	FetchFilesToDelete(repository *GitRepository) ([]Path, error)
}

ValueStore provides methods to query Values from a configuration.

In Domain-Driven Design language, the term `Store` corresponds to `Repository`, but to avoid name clash it was named `Store`.

type Values

type Values map[string]interface{}

Values contain a tree of properties to be consumed by a TemplateEngine.

func (Values) Keys

func (v Values) Keys() []string

Keys returns a list of keys of the top level. Returns an empty string slice if Values is nil or empty.

Jump to

Keyboard shortcuts

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