internal

package
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2025 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ExternalType = "external"
	CommandType  = "command"
)
View Source
const (
	RootDir Cfg = "root_dir"

	Yes = "Yes"
	No  = "No"
)
View Source
const (
	Replace        FileExistsAction = "replace"
	Skip           FileExistsAction = "skip"
	ReplaceIfNewer FileExistsAction = "replace_if_newer"

	Commit ChangelogType = "commit"
	Tag    ChangelogType = "tag"

	Include ChangelogConditionType = "include"
	Exclude ChangelogConditionType = "exclude"

	Asc  ChangelogSort = "asc"
	Desc ChangelogSort = "desc"

	Release     BuildType = "release"
	LastVersion BuildType = "lastVersion"
)

Variables

This section is empty.

Functions

func AllModules

func AllModules(directory string) *[]string

AllModules returns a list of module names found in the specified directory.

The function reads the directory, checks for files (skipping directories), and attempts to read each file as a module using the ReadModule function. If a file can be successfully read as a module, its name is added to the list.

Parameters: - directory (string): The path to the directory to scan for modules.

Returns: - *[]string: A pointer to a slice of strings containing the names of all successfully read modules.

func CaptureOutput

func CaptureOutput(f func()) string

func ChangelogList added in v1.3.1

func ChangelogList(repository string, rules Changelog) ([]string, error)

func CheckContext

func CheckContext(ctx context.Context) error

CheckContext checks whether the provided context has been canceled or expired.

This function checks if the context has been canceled or the deadline exceeded. If the context is done, it returns an error indicating the cancellation or expiration. If the context is still active, it returns nil.

Parameters: - ctx (context.Context): The context to check.

Returns: - error: Returns an error if the context is done (canceled or expired), otherwise nil.

func CheckPath

func CheckPath(path string) error

CheckPath checks if a given path is valid and exists on the filesystem.

This function cleans the provided path and verifies its validity using the `isValidPath` function. It then checks if the file or directory exists using `os.Stat`. If the file or directory does not exist or is not valid, an appropriate error is returned.

Parameters: - path (string): The path to be validated and checked for existence.

Returns: - error: An error if the path is invalid or does not exist, otherwise returns nil.

func CheckStages

func CheckStages(module *Module) error

CheckStages validates the paths in the stages of the given module.

This function iterates over the stages in the provided module and concurrently checks the paths defined in each stage using goroutines. If any errors are encountered, they are collected in a channel and returned as a combined error.

Parameters: - module (*Module): The module containing stages to be validated.

Returns:

  • error: Returns an error if any validation fails in any stage's paths. If no errors are found, it returns nil.

func Choose

func Choose(items *[]string, value *string, title string) error

func CommitFilter added in v1.3.1

func CommitFilter(message string, conditions TypeValue[ChangelogConditionType, []string]) bool

func DefaultYAML

func DefaultYAML() string

func GetModulesDir

func GetModulesDir(path string) (string, error)

func IsDir

func IsDir(path string) (bool, error)

IsDir checks if the given path points to a directory.

This function first checks if the path is valid using the `CheckPath` function. Then, it retrieves the file information using `os.Stat` to determine whether the given path is a directory or not.

Parameters: - path (string): The path to be checked.

Returns: - bool: `true` if the path is a directory, `false` otherwise. - error: An error if the path is invalid or if there is an issue retrieving the file information.

func OpenRepository added in v1.3.1

func OpenRepository(repository string) (*git.Repository, error)

func ReplaceVariables

func ReplaceVariables(input string, variables map[string]string, depth int) (string, error)

ReplaceVariables recursively replaces variables in the input string with their corresponding values from the provided map of variables.

The function supports up to 5 levels of recursion (controlled by the `depth` parameter) to allow nested variable replacements. If the depth exceeds 5 or if the depth is less than 0, an error will be returned.

Parameters: - input (string): The input string containing variables in the format `{variableName}` to replace. - variables (map[string]string): A map containing variable names as keys and their replacement values as strings. - depth (int): The current recursion depth, which should start from 0. The function supports up to 5 levels of recursion.

Returns: - string: The updated string with variables replaced by their corresponding values, or an error if no replacement could be made. - error: An error is returned if the depth exceeds 5, if the depth is negative, or if the replacement results in an empty string.

func ResultMessage

func ResultMessage(format string, a ...any)

func ValidateArgument added in v1.3.0

func ValidateArgument(arg string) bool

ValidateArgument checks if the provided argument contains only alphanumeric characters, underscores, slashes, or hyphens.

Parameters: - arg (string): The argument to validate.

Returns: - bool: True if the argument is valid, otherwise false.

func ValidateBuilds added in v1.3.1

func ValidateBuilds(m *Module) error

func ValidateCallbacks added in v1.3.1

func ValidateCallbacks(m *Module) error

func ValidateIgnore added in v1.3.1

func ValidateIgnore(m *Module) error

func ValidateLastVersion added in v1.3.1

func ValidateLastVersion(m *Module) error

func ValidateModuleName

func ValidateModuleName(name, directory string) error

ValidateModuleName checks if a module with the given name already exists in the specified directory.

The function constructs the expected file path for the module definition using the format "<directory>/<name>.yaml". It then checks if the file exists: - If the file does not exist, the function returns nil (indicating the module name is available). - If the file exists, it returns an error indicating that the module name is already taken. - If an error occurs while checking the file, it is returned.

Returns nil if the module name is available, otherwise returns an error.

func ValidatePassword

func ValidatePassword(password string) error

ValidatePassword checks if the given password meets basic validation criteria.

The function performs the following checks: - Trims any leading and trailing whitespace. - Ensures the password is not empty. - Ensures the password is at least 6 characters long.

Returns an error if the password is invalid, otherwise returns nil.

func ValidateStages added in v1.3.1

func ValidateStages(m *Module) error

func ValidateVariables added in v1.3.1

func ValidateVariables(m *Module) error

func ValidateVersion

func ValidateVersion(version string) error

ValidateVersion checks if the given module version is valid.

The function performs the following checks: - Trims any leading and trailing whitespace. - Ensures the version is not empty. - Validates the version format using a predefined regex.

Returns nil if the version is valid, otherwise returns an error.

Types

type BuildType added in v1.3.1

type BuildType string

type Builder

type Builder interface {
	Build() error
	Prepare(log *zerolog.Logger) error
	Cleanup(log *zerolog.Logger) error
	Rollback(log *zerolog.Logger) error
	Collect(log *zerolog.Logger) error
}

type Builds added in v1.3.1

type Builds struct {
	Release     []string `yaml:"release"`
	LastVersion []string `yaml:"lastVersion,omitempty"`
}

type Callback added in v1.3.0

type Callback struct {
	Stage string             `yaml:"stage"`
	Pre   CallbackParameters `yaml:"pre,omitempty"`
	Post  CallbackParameters `yaml:"post,omitempty"`
}

func (*Callback) IsValid added in v1.3.0

func (c *Callback) IsValid() error

IsValid checks if the Callback structure is valid. It ensures that the stage name is provided and that either pre or post parameters exist. Additionally, it validates the pre and post parameters if they are set.

Returns: - error: An error if validation fails, otherwise nil.

func (Callback) PostRun added in v1.3.0

func (c Callback) PostRun(ctx context.Context, wg *sync.WaitGroup, log *zerolog.Logger)

func (Callback) PreRun added in v1.3.0

func (c Callback) PreRun(ctx context.Context, wg *sync.WaitGroup, log *zerolog.Logger)

type CallbackParameters added in v1.3.0

type CallbackParameters struct {
	Type       string   `yaml:"type"`
	Action     string   `yaml:"action"`
	Method     string   `yaml:"method,omitempty"`
	Parameters []string `yaml:"parameters,omitempty"`
}

func (*CallbackParameters) IsValid added in v1.3.0

func (c *CallbackParameters) IsValid() error

IsValid checks if the CallbackParameters structure is valid. It performs type, method, action, and parameters validation.

Returns: - error: An error if validation fails, otherwise nil.

func (*CallbackParameters) Run added in v1.3.0

Run executes the callback based on its type (external or command). It first validates the callback parameters, then either runs an external HTTP request or a system command depending on the `Type` of the callback.

Parameters: - ctx (context.Context): The context for the execution, used for cancellation and timeouts. - log (*zerolog.Logger): The logger to record any logs or errors during execution.

Returns: - error: Returns an error if validation fails or if execution of the callback fails.

type Cfg

type Cfg string

type Changelog added in v1.3.1

type Changelog struct {
	From      TypeValue[ChangelogType, string]            `yaml:"from"`
	To        TypeValue[ChangelogType, string]            `yaml:"to"`
	Sort      ChangelogSort                               `yaml:"sort,omitempty"`
	Condition TypeValue[ChangelogConditionType, []string] `yaml:"condition,omitempty"`
}

type ChangelogConditionType added in v1.3.1

type ChangelogConditionType string

type ChangelogSort added in v1.3.1

type ChangelogSort string

type ChangelogType added in v1.3.1

type ChangelogType string

type Client

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

func NewClient

func NewClient(client HTTPClient, jar http.CookieJar) *Client

func (*Client) Authorization

func (c *Client) Authorization(login, password string) ([]*http.Cookie, error)

Authorization performs user authentication by sending login credentials to the Bitrix Partner Portal.

It sends a POST request with the login and password as form data and checks the response for authentication success by verifying the presence of a "BITRIX_SM_LOGIN" cookie.

Returns a slice of cookies if authentication is successful or an error if authentication fails or an issue occurs during the request.

func (*Client) SessionId

func (c *Client) SessionId(module *Module, cookies []*http.Cookie) string

SessionId retrieves the session ID for a given module from the Bitrix Partner Portal.

The function sends a GET request to the edit page of the module, then parses the HTML response to extract the session ID. The session ID is needed for later operations like uploading data to the portal.

Parameters: - module: The module for which the session ID is being retrieved. - cookies: The cookies containing the authentication information.

Returns: - The session ID as a string if found, otherwise returns an empty string.

func (*Client) UploadZIP

func (c *Client) UploadZIP(module *Module, cookies []*http.Cookie) error

UploadZIP uploads a ZIP file containing the module's data to the Bitrix Partner Portal.

This function first validates that the module and cookies are provided. It then retrieves the session ID and prepares the ZIP file for upload. The request is sent with the necessary form data, including the session ID, module name, and the ZIP file. The response body is checked for the result of the upload operation.

Parameters: - module: The module whose ZIP file is being uploaded. - cookies: The cookies containing the authentication information.

Returns: - An error if any step fails (e.g., missing session, file errors, upload failure).

type CommitFilterFunc added in v1.3.1

type CommitFilterFunc func(string, TypeValue[ChangelogConditionType, []string]) bool

type FileExistsAction

type FileExistsAction string

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

type Module

type Module struct {
	Ctx            context.Context   `yaml:"-"`
	Variables      map[string]string `yaml:"variables,omitempty"`
	Builds         Builds            `yaml:"builds"`
	BuildDirectory string            `yaml:"buildDirectory,omitempty"`
	Version        string            `yaml:"version"`
	Account        string            `yaml:"account"`
	Name           string            `yaml:"name"`
	LogDirectory   string            `yaml:"logDirectory,omitempty"`
	Repository     string            `yaml:"repository,omitempty"`
	Changelog      Changelog         `yaml:"changelog,omitempty"`
	Stages         []Stage           `yaml:"stages"`
	Ignore         []string          `yaml:"ignore"`
	Callbacks      []Callback        `yaml:"callbacks,omitempty"`
	LastVersion    bool              `yaml:"-"`
}

func ReadModule

func ReadModule(path, name string, file bool) (*Module, error)

ReadModule reads a module from a YAML file or directory path and returns a Module object.

This function attempts to read a module from the specified path. If the `file` flag is true, the function treats `path` as the file path directly. Otherwise, it expects a YAML file with the name of the module, combining the `path` and `name` parameters to form the file path.

Parameters:

  • path (string): The directory or file path where the module file is located.
  • name (string): The name of the module. Used to construct the file path when `file` is false.
  • file (bool): Flag indicating whether the `path` is a direct file path or a directory where a module file should be looked for.

Returns: - *Module: A pointer to a `Module` object if the file can be successfully read and unmarshalled. - error: An error if reading or unmarshalling the file fails.

func (*Module) Build

func (m *Module) Build() error

Build orchestrates the entire build process for the module. It logs the progress of each phase, such as preparation, collection, and cleanup. If any of these phases fails, the build will be rolled back to ensure a clean state.

The method returns an error if any of the steps (Prepare, Collect, or Cleanup) fail.

func (*Module) Cleanup

func (m *Module) Cleanup(log *zerolog.Logger) error

Cleanup removes any temporary files and directories created during the build process. It ensures the environment is cleaned up by deleting the version-specific build directory.

The method returns an error if the cleanup process fails.

func (*Module) Collect

func (m *Module) Collect(log *zerolog.Logger) error

Collect gathers the necessary files for the build. It processes each stage in parallel using goroutines to handle file copying. The function creates the necessary directories for each stage and copies files as defined in the stage configuration.

The method returns an error if any stage fails or if there are issues zipping the collected files.

func (*Module) FindStage added in v1.3.1

func (m *Module) FindStage(name string) (Stage, error)

FindStage searches for a stage with the specified name in the module. It iterates through the module's stages and returns the matching stage if found. If no stage with the given name exists, it returns an empty Stage and an error with the message "stage not found".

name - the name of the stage to search for.

Returns:

  • Stage: the stage with the matching name.
  • error: nil if the stage is found; otherwise, an error indicating that the stage was not found.

func (*Module) GetVersion added in v1.3.1

func (m *Module) GetVersion() string

func (*Module) IsValid

func (m *Module) IsValid() error

IsValid validates the fields of the Module struct.

It checks the following conditions:

  1. The `Name` field must not be an empty string and must not contain spaces.
  2. The `Version` field must be a valid version, validated by the `ValidateVersion` function.
  3. The `Account` field must not be empty.
  4. If the `Variables` map is not nil, it checks that each key and value in the map is non-empty.
  5. The `Stages` field must contain at least one stage. Each stage must have a valid `Name`, `To` field, and an `ActionIfFileExists` field. Additionally, each `From` path in a stage must be non-empty.
  6. If the `Ignore` field is not empty, each rule must be non-empty.
  7. The `NormalizeStages` function is called to ensure the validity of the stages after other checks.

If any of these conditions are violated, the method returns an error with a detailed message. If all validations pass, it returns nil.

func (*Module) NormalizeStages

func (m *Module) NormalizeStages() error

NormalizeStages processes and normalizes the stages in the Module by replacing any variables within the stage fields (Name, To, From) with values from the Module's Variables map.

The method iterates over each stage in the Module's Stages slice, and for each field (Name, To, From), it uses the `ReplaceVariables` function to replace any placeholders with corresponding variable values.

If any error occurs while replacing variables or processing the stages, it returns the error. If no errors are encountered, it returns nil.

Returns: - error: Any error that occurred during the variable replacement process. If successful, returns nil.

func (*Module) PasswordEnv

func (m *Module) PasswordEnv() string

PasswordEnv returns the environment variable name that stores the password for the module.

The variable name is generated based on the module's name: - Converted to uppercase - All dots (".") are replaced with underscores ("_") - The suffix "_PASSWORD" is appended

For example, for a module named "my.module", the function will return "MY_MODULE_PASSWORD".

func (*Module) Prepare

func (m *Module) Prepare(log *zerolog.Logger) error

Prepare sets up the environment for the build process. It validates the module, checks the stages, and creates the necessary directories for the build output and logs. If any validation or directory creation fails, an error will be returned.

The method returns an error if the module is invalid or if directories cannot be created.

func (*Module) Rollback

func (m *Module) Rollback(log *zerolog.Logger) error

Rollback reverts any changes made during the build process. It deletes the generated zip file and version-specific directories created during the build. This function ensures that any temporary build files are removed and that the environment is restored to its previous state.

The method returns an error if the rollback process fails.

func (*Module) StageCallback added in v1.3.0

func (m *Module) StageCallback(stageName string) (Runnable, error)

StageCallback returns the callback associated with the given stage. If no matching callback is found, an error is returned.

stageName - the name of the stage to find the callback for.

Returns: - Runnable - the found callback if it exists. - error - an error if the callback is not found.

func (*Module) ToYAML

func (m *Module) ToYAML() ([]byte, error)

ToYAML converts the Module struct to its YAML representation.

It uses the `yaml.Marshal` function to serialize the `Module` struct into a YAML format. If the conversion is successful, it returns the resulting YAML as a byte slice. If an error occurs during marshaling, it returns the error.

Returns: - []byte: The YAML representation of the Module struct. - error: Any error that occurred during the marshaling process.

func (*Module) ValidateChangelog added in v1.3.1

func (m *Module) ValidateChangelog() error

ValidateChangelog validates the changelog configuration of the module. It checks for the presence and correctness of required fields: - Ensures 'repository' is specified if 'from' or 'to' types are defined. - Validates that 'from' and 'to' types are either 'commit' or 'tag'. - Confirms 'from' and 'to' values are non-empty. - If 'condition' is specified, checks that:

  • a Condition type is either 'include' or 'exclude'.
  • Condition values are non-empty and valid regular expressions.

Returns an error detailing the first encountered validation issue, or nil if the configuration is valid.

func (*Module) ZipPath

func (m *Module) ZipPath() (string, error)

ZipPath generates the absolute path for the ZIP file associated with the Module.

The method constructs a path by combining the Module's BuildDirectory and Version fields, appending the ".zip" extension. It then checks if the path exists and is valid using the `CheckPath` function.

If the path is valid, it returns the cleaned absolute path of the ZIP file. If any error occurs during path creation or validation, it returns an empty string along with the error.

Returns: - string: The absolute path of the ZIP file. - error: Any error encountered during path creation or validation, otherwise nil.

type Runnable added in v1.3.0

type Runnable interface {
	PreRun(ctx context.Context, wg *sync.WaitGroup, log *zerolog.Logger)
	PostRun(ctx context.Context, wg *sync.WaitGroup, log *zerolog.Logger)
}

type Stage

type Stage struct {
	Name               string           `yaml:"name"`
	To                 string           `yaml:"to"`
	ActionIfFileExists FileExistsAction `yaml:"actionIfFileExists"`
	From               []string         `yaml:"from"`
	ConvertTo1251      bool             `yaml:"convertTo1251,omitempty"`
}

type TypeValue added in v1.3.1

type TypeValue[T1 any, T2 any] struct {
	Type  T1 `yaml:"type"`
	Value T2 `yaml:"value"`
}

Jump to

Keyboard shortcuts

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