internal

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2025 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RootDir Cfg = "root_dir"

	Yes = "Yes"
	No  = "No"
)

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 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 Confirmation

func Confirmation(flag *bool, title string) error

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 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 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 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 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 Cfg

type Cfg 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 FileExistsAction

type FileExistsAction string
const (
	Replace        FileExistsAction = "replace"
	Skip           FileExistsAction = "skip"
	ReplaceIfNewer FileExistsAction = "replace_if_newer"
)

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"`
	Name           string            `yaml:"name"`
	Version        string            `yaml:"version"`
	Account        string            `yaml:"account"`
	BuildDirectory string            `yaml:"buildDirectory,omitempty"`
	LogDirectory   string            `yaml:"logDirectory,omitempty"`
	Stages         []Stage           `yaml:"stages"`
	Ignore         []string          `yaml:"ignore"`
}

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) 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) 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) 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 OptionProvider

type OptionProvider interface {
	Option() string
}

type Printer

type Printer interface {
	PrintSummary(verbose bool)
}

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"`
}

Jump to

Keyboard shortcuts

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