parser

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package parser provides a bunch of functions to be wrapped with engine.Parser function signature.

Example

type config struct { ... }

func CustomParser(ctx context.Context, destdir string, c *config) error {
	...
}

var _ engine.Parser[config] = CustomParser // ensure interface is implemented

// single parser call
func main() {
	var c config
	err := CustomParser(ctx, "path/to/dir", &c)
	// handle err
}

// fully used with engine.Generate
func main() {
	destdir, _ := os.Getwd()

	var c config
	err := engine.Generate(ctx, destdir, c, []engine.Parser[config]{CustomParser}, ...)
	// handle err
}

Index

Constants

View Source
const (
	// FolderCMD represents the cmd folder where main.go files should be placed according to the Go layout.
	FolderCMD = "cmd"

	// FileGomod represents the go.mod filename.
	FileGomod = "go.mod"

	// FileMain represents the main.go filename.
	FileMain = "main.go"
)
View Source
const (
	// Bitbucket is just the bitbucket constant.
	Bitbucket = "bitbucket"
	// Gitea is just the gitea constant.
	Gitea = "gitea"
	// GitHub is just the github constant.
	GitHub = "github"
	// GitLab is just the gitlab constant.
	GitLab = "gitlab"
)
View Source
const FileGowork = "go.work"

FileGowork represents the go.work filename.

View Source
const FilePackageJSON = "package.json"

FilePackageJSON represents package.json filename.

Variables

View Source
var (
	// ErrMissingModuleStatement is the error returned when module statement is missing from go.mod.
	ErrMissingModuleStatement = errors.New("invalid go.mod, module statement is missing")

	// ErrMissingGoStatement is the error returned when go statement is missing from go.mod.
	ErrMissingGoStatement = errors.New("invalid go(.mod or .work), go statement is missing")
)
View Source
var (
	// ErrMissingPackageName is the error returned when package.json name is missing.
	ErrMissingPackageName = errors.New("package.json 'name' is missing")

	// ErrInvalidPackageManager is the error returned when packageManager is missing or invalid in package.json.
	ErrInvalidPackageManager = errors.New("package.json 'packageManager' is missing or isn't valid")
)
View Source
var ErrNoGowork = errors.New("no go.work file")

ErrNoGowork is a specific case of fs.ErrNotExist when go.work file doesn't exist in ReadGowork call.

View Source
var ErrNoHugo = errors.New("no hugo or hugo theme configuration found")

ErrNoHugo is returned by ReadHugo when neither a hugo.(toml|yaml|yml) configuration file nor a theme.(toml|yaml|yml) hugo theme configuration file is found.

It's a convenient error to use with errors.Is.

Functions

func MergeValues

func MergeValues(in any, filepaths ...string) (map[string]any, error)

MergeValues merges all input values files into a single map.

It can also take an input values struct / map that could have been read beforehand and marshals it with JSON as base values.

All successive merges are made with override strategy, meaning that a value can be overridden by the next values file. See mergo.Merge for more details.

In case of error, merging stops on the first error and returns it.

It can be used as a simple function, calling it directly, but its expected usage is with engine.Generate:

type config struct { ... }

func ParserChart(ctx context.Context, destdir string, c *config) error {
	chartdir := filepath.Join(destdir, "chart")
	if c.CI != nil && c.CI.Deployment != nil && c.CI.Deployment.Helm {
		engine.GetLogger().Infof("skipping helm chart, configuration has 'exclude' key with 'chart' in it")
		if err := os.RemoveAll(chartdir); err != nil {
			return fmt.Errorf("remove chart dir: %w", err)
		}
		return nil
	}
	engine.GetLogger().Infof("helm chart detected, configuration doesn't have 'exclude' key or 'chart' isn't present in it")

	values, err := parser.MergeValues(c,
		filepath.Join(chartdir, "values.custom1.yaml"),
		filepath.Join(chartdir, "values.custom2.yaml"))
	if err != nil {
		return fmt.Errorf("merge values: %w", err)
	}
	// do something with values (e.g. update config since it's a pointer)
	return nil
}

Types

type Executables

type Executables struct {
	// Clis is a map of CLI names without value (empty struct).
	Clis map[string]any

	// Crons is a map of cronjob names without value (empty struct).
	Crons map[string]any

	// Jobs is a map of job names without value (empty struct).
	Jobs map[string]any

	// Workers is a map of worker names without value (empty struct).
	Workers map[string]any
}

Executables represents a collection of executables (CLIs, cronjobs, jobs, workers).

func ReadGoCmd

func ReadGoCmd(destdir string) (Executables, error)

ReadGoCmd reads cmd folder at destdir and returns all executables found.

An executable is a main.go present in a subfolder of cmd. For instance cmd/<name>/main.go.

Executables are categorized as CLI, Cron, Job and Worker. The prefix of <name> indicates in which category the executable belongs:

  • <name> for CLI executables
  • cron-<name> for cron executables
  • job-<name> for job executables
  • worker-<name> for worker executables

It can be used as a simple function, calling it directly, but its expected usage is with engine.Generate:

type config struct { ... }

func ParserGolang(ctx context.Context, destdir string, c *config) error {
	gomod, err := parser.ReadGomod(destdir)
	if err != nil {
		if errors.Is(err, fs.ErrNotExist) {
			return nil
		}
		return fmt.Errorf("read go.mod: %w", err)
	}

	engine.GetLogger().Infof("golang detected, file '%s' is present and valid", parser.FileGomod)
	// do something with gomod (e.g. update config since it's a pointer)

	executables, err := parser.ReadGoCmd(destdir)
	if err != nil {
		if errors.Is(err, fs.ErrNotExist) {
			return nil
		}
		return fmt.Errorf("read cmd: %w", err)
	}
	// do something with executables (e.g. update config since it's a pointer)
	return nil
}

func (*Executables) AddCLI

func (g *Executables) AddCLI(name string)

AddCLI sets a CLI with its name. In case a CLI with the same name already exists, it is replaced.

func (*Executables) AddCron

func (g *Executables) AddCron(name string)

AddCron sets a cronjob with its name. In case a cronjob with the same name already exists, it is replaced.

func (*Executables) AddJob

func (g *Executables) AddJob(name string)

AddJob sets a job with its name. In case a job with the same name already exists, it is replaced.

func (*Executables) AddWorker

func (g *Executables) AddWorker(name string)

AddWorker sets a worker with its name. In case a worker with the same name already exists, it is replaced.

func (Executables) Binaries

func (g Executables) Binaries() int

Binaries returns the sum of all executables (CLIs, cronjobs, jobs, workers).

type Gomod

type Gomod struct {
	// ContainerImage is the container image to build the module with,
	// a placeholder to be filled with generator.FetchContainerImage.
	ContainerImage string

	// Go is the go statement,
	// i.e. "go 1.23.4" without "go" (and space) part.
	Go string

	// Module is the module statement,
	// i.e. "module gitlab.com/kickr-dev/engine" without "module" (and space) part.
	Module string

	// Toolchain is the toolchain statement,
	// i.e. "toolchain go1.23.4" without "toolchain go" part.
	Toolchain string

	// Tools is the slice of tools present in go.mod file.
	// Nothing is done on it like formatting, as such the path of each tool is the full path given in go.mod.
	Tools []string
}

Gomod represents the parsed struct for go.mod file.

func ReadGomod

func ReadGomod(destdir string) (Gomod, error)

ReadGomod reads the go.mod file at destdir and returns its representation.

It will return an error if the go.mod file is missing the following properties:

  • module statement
  • go statement

It can be used as a simple function, calling it directly, but its expected usage is with engine.Generate:

type config struct { ... }

func Golang(ctx context.Context, destdir string, c *config) error {
	gomod, err := parser.ReadGomod(destdir)
	if err != nil {
		if errors.Is(err, fs.ErrNotExist) {
			return nil
		}
		return fmt.Errorf("read go.mod: %w", err)
	}
	engine.GetLogger().Infof("golang detected, file '%s' is present and valid", parser.FileGomod)
	// do something with gomod (e.g. update config since it's a pointer)
	return nil
}

func (Gomod) AsVCS

func (g Gomod) AsVCS() VCS

AsVCS returns the vcs configuration associated with module statement in go.mod.

type Gowork

type Gowork struct {
	// ContainerImage is the container image to build the workspace with,
	// a placeholder to be filled with generator.FetchContainerImage.
	ContainerImage string

	// Go is the go statement,
	// i.e. "go 1.23.4" without "go" (and space) part.
	Go string

	// Toolchain is the toolchain statement,
	// i.e. "toolchain go1.23.4" without "toolchain go" part.
	Toolchain string

	// Uses is the slice of all 'use' directives in go.work file.
	Uses []GoworkUse
}

Gowork represents the parsed struct for go.work file.

func ReadGowork

func ReadGowork(destdir string) (Gowork, error)

ReadGowork reads the go.work file at destdir and returns its representation alongside all go.mod that could be defined in 'use' directive.

It will return an error if the go.work file is missing the 'go' statement.

It can be used as a simple function, calling it directly, but its expected usage is with engine.Generate:

type config struct { ... }

func Golang(ctx context.Context, destdir string, c *config) error {
	gowork, err := parser.ReadGowork(destdir)
	if err == nil {
		engine.GetLogger().Infof("golang detected, file '%s' is present and valid", parser.FileGowork)
		// do something with gowork (e.g. update config since it's a pointer)
		return nil
	}
	// fs.ErrNotExist is also valid,
	// however it would also match the case where at least one 'use' go.mod file doesn't exist
	if !errors.Is(err, parser.ErrNoGowork) {
		return fmt.Errorf("read go.work: %w", err)
	}
	// go.work doesn't exist, maybe it's a simple Go repository with a go.mod
	// let's check that just below

	gomod, err := parser.ReadGomod(destdir)
	if err != nil {
		if errors.Is(err, fs.ErrNotExist) {
			return nil
		}
		return fmt.Errorf("read go.mod: %w", err)
	}
	engine.GetLogger().Infof("golang detected, file '%s' is present and valid", parser.FileGomod)
	// do something with gomod (e.g. update config since it's a pointer)
	return nil
}

func (Gowork) Module

func (g Gowork) Module() string

Module returns the common prefix between all 'use' of current go.work.

In case there's no 'use' at all or no common prefix can be found between them, then an empty string is returned.

type GoworkUse

type GoworkUse struct {
	// Gomod is the parsed go.mod of current go.work use element.
	Gomod Gomod

	// Module path in the go.work.
	ModulePath string

	// Use path of module.
	Use string
}

GoworkUse is one use of a go.work file. It contains its valid parsed go.mod and its use path.

type HugoCompose

type HugoCompose struct {
	*HugoTheme
	*HugoConfig

	// ContainerImage is the container image to build the site with,
	// a placeholder to be filled with generator.FetchContainerImage.
	ContainerImage string
}

HugoCompose is the composition of both hugo.(toml|yaml|yml) configuration files and theme.(toml|yaml|yml) hugo theme configuration files.

Note that when retrieving a HugoCompose with ReadHugo, either HugoTheme or HugoConfig will be provided but never both.

func ReadHugo

func ReadHugo(destdir string) (HugoCompose, error)

ReadHugo detects if the project is a Hugo project.

Detection consists of reading hugo.(toml|yaml|yml) or theme.(toml|yaml|yml) files in the given destdir.

The following checking order is made and the function will return on first successful match:

  • theme.toml, theme.yaml, theme.yml
  • hugo.toml, hugo.yaml, hugo.yml

It can be used as a simple function, calling it directly, but its expected usage is with engine.Generate:

type config struct { ... }

func ParserHugo(ctx context.Context, destdir string, c *config) error {
	hugoc, err := parser.ReadHugo(destdir)
	if err != nil {
		if errors.Is(err, parser.ErrNoHugo) {
			return nil
		}
		return fmt.Errorf("read hugo: %w", err)
	}
	engine.GetLogger().Infof("hugo detected, theme or hugo files are present")
	// do something with hugo config (e.g. update config since it's a pointer)
	return nil
}

func (HugoCompose) Module

func (h HugoCompose) Module() HugoModule

Module returns the module section of the detected theme or configuration.

type HugoConfig

type HugoConfig struct {
	BaseURL    string     `yaml:"baseURL,omitempty"    toml:"baseurl,omitempty"`
	Copyright  string     `yaml:"copyright,omitempty"  toml:"copyright,omitempty"`
	Module     HugoModule `yaml:"module,omitempty"     toml:"module,omitempty"`
	PublishDir string     `yaml:"publishDir,omitempty" toml:"publishdir,omitempty"`
	Title      string     `yaml:"title,omitempty"      toml:"title,omitempty"`
}

HugoConfig is the representation of a hugo.(toml|yaml|yml) configuration file.

type HugoModule

type HugoModule struct {
	HugoVersion HugoVersion `yaml:"hugoVersion,omitempty" toml:"hugoversion,omitempty"`
}

HugoModule is the module section of hugo configuration files.

type HugoTheme

type HugoTheme struct {
	DemoSite    string     `yaml:"demosite,omitempty"    toml:"demosite,omitempty"`
	Description string     `yaml:"description,omitempty" toml:"description,omitempty"`
	HomePage    string     `yaml:"homepage,omitempty"    toml:"homepage,omitempty"`
	License     string     `yaml:"license,omitempty"     toml:"license,omitempty"`
	Module      HugoModule `yaml:"module,omitempty"      toml:"module,omitempty"`
	Name        string     `yaml:"name,omitempty"        toml:"name,omitempty"`
}

HugoTheme is the representation of a theme.(toml|yaml|yml) hugo theme configuration file.

type HugoVersion

type HugoVersion struct {
	Max string `yaml:"max,omitempty" toml:"max,omitempty"`
	Min string `yaml:"min,omitempty" toml:"min,omitempty"`
}

HugoVersion is the hugo version constraints of a hugo module.

type PackageJSON

type PackageJSON struct {
	Author *string `json:"author,omitempty"`
	Config struct {
		BuildDir string `json:"buildDir,omitempty"`
	} `json:"config,omitzero"`
	Description    *string  `json:"description,omitempty"`
	Files          []string `json:"files,omitempty"`
	Keywords       []string `json:"keywords,omitempty"`
	License        *string  `json:"license,omitempty"`
	Main           *string  `json:"main,omitempty"`
	Module         string   `json:"module,omitempty"`
	Name           string   `json:"name,omitempty"`
	PackageManager string   `json:"packageManager,omitempty"`
	Private        bool     `json:"private,omitempty"`
	PublishConfig  struct {
		Access     string `json:"access,omitempty"`
		Provenance bool   `json:"provenance,omitempty"`
		Registry   string `json:"registry,omitempty"`
		Tag        string `json:"tag,omitempty"`
	} `json:"publishConfig,omitzero"`
	Repository *struct {
		URL string `json:"url,omitempty"`
	} `json:"repository,omitempty"`
	Scripts map[string]string `json:"scripts,omitempty"`
	Version string            `json:"version,omitempty"`
}

PackageJSON represents the Node.js package.json file.

func (*PackageJSON) Validate

func (p *PackageJSON) Validate() error

Validate validates the given PackageJSON struct.

type VCS

type VCS struct {
	// Name is the version control system name.
	Name string

	// Platform represents the vcs platform hosting the project.
	//
	// Self-hosted or aliased hosts that don't contain 'bitbucket', 'gitea', 'github', 'gitlab' or 'stash'
	// won't have their platform detected.
	// In such cases, override the attribute manually.
	Platform string

	// ProjectHost represents the host where the project is hosted.
	ProjectHost string

	// ProjectName is the project name being generated.
	ProjectName string

	// ProjectPath is the project path.
	ProjectPath string

	// Tags is the slice of repository tags.
	Tags []string
}

VCS structure contains all properties related to VCS (Version Control System).

func Git

func Git(destdir string) (VCS, error)

Git reads the input destdir directory remote.origin.url to retrieve various project information (git host, project name, etc.).

It can be used as a simple function, calling it directly, but its expected usage is with engine.Generate:

type config struct { ... }

func ParserGit(ctx context.Context, destdir string, c *config) error {
	vcs, err := parser.Git(destdir)
	if err != nil {
		engine.GetLogger().Warnf("failed to retrieve git vcs configuration: %v", err)
		return nil // a repository may not be a git repository
	}
	engine.GetLogger().Infof("git repository detected")
	// do something with vcs (e.g. update config since it's a pointer)
	return nil
}

Two errors may be checked with errors.Is when one is returned:

  • git.ErrRepositoryNotExists
  • git.ErrRemoteNotFound

Jump to

Keyboard shortcuts

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