core

package
v0.11.0 Latest Latest
Warning

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

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

Documentation

Overview

Package core contains every logic for working cli.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidRule            = errors.New("invalid rule")
	ErrRepositoryDoesNotExist = errors.New("repository does not exist")
	ErrEmptyInputFiles        = errors.New("empty input files")
)

Functions

func ApplyManagedMode added in v0.11.0

func ApplyManagedMode(
	descriptors []*descriptorpb.FileDescriptorProto,
	config ManagedModeConfig,
	fileToModule map[string]string,
) error

ApplyManagedMode applies managed mode settings to file descriptors.

func CheckIsIgnored

func CheckIsIgnored(comments []*parser.Comment, ruleName string) bool

CheckIsIgnored check if passed breakingCheckRuleName has to be ignored due to ignore command in comments

func GetRuleName

func GetRuleName(rule Rule) string

GetRuleName returns rule name

func SetAllowCommentIgnores

func SetAllowCommentIgnores(val bool)

Types

type BUFConfig

type BUFConfig struct {
	Version  string   `yaml:"version"`
	Deps     []string `yaml:"deps"`
	Build    Build    `yaml:"build"`
	Lint     Lint     `yaml:"lint"`
	Breaking Breaking `yaml:"breaking"`
}

BUFConfig is the configuration for the buf tool.

type Breaking

type Breaking struct {
	Use                    []string            `yaml:"use"`
	Except                 []string            `yaml:"except"`
	Ignore                 []string            `yaml:"ignore"`
	IgnoreOnly             map[string][]string `yaml:"ignore_only"`
	IgnoreUnstablePackages bool                `yaml:"ignore_unstable_packages"`
}

Breaking is the configuration for the breaking section of the buf tool.

type BreakingCheckConfig

type BreakingCheckConfig struct {
	// branch name to compare with
	AgainstGitRef string
	// dirs should be ignored
	IgnoreDirs []string
}

type BreakingChecker

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

func (*BreakingChecker) Check

func (b *BreakingChecker) Check() ([]IssueInfo, error)

type Build

type Build struct {
	Excludes []string `yaml:"excludes"`
}

Build is the configuration for the build section of the buf tool.

type Collection

type Collection struct {
	Imports  map[ImportPath]Import
	Services map[string]Service
	// key message path - for supporting nested messages:
	// message MainMessage {
	// 		message NestedMessage{};
	// };
	// will be: MainMessage.NestedMessage
	Messages map[string]Message
	OneOfs   map[string]OneOf
	Enums    map[string]Enum
}

type Config

type Config struct {
	Deps    []string
	Plugins []Plugin
	Inputs  Inputs
}

Config is the configuration for EasyP generate.

type Core

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

Core provide to business logic of EasyP.

func New

func New(
	rules []Rule,
	ignore []string,
	deps []string,
	ignoreOnly map[string][]string,
	logger *slog.Logger,
	plugins []Plugin,
	inputs Inputs,
	console console.Console,
	storage Storage,
	moduleConfig ModuleConfig,
	lockFile LockFile,
	currentProjectGitWalker CurrentProjectGitWalker,
	breakingCheckConfig BreakingCheckConfig,
	managedMode ManagedModeConfig,
) *Core

func (*Core) BreakingCheck

func (c *Core) BreakingCheck(ctx context.Context, workingDir, path string) ([]IssueInfo, error)

func (*Core) Download

func (c *Core) Download(ctx context.Context, dependencies []string) error

Download all packages from config dependencies slice of strings format: origin@version: github.com/company/repository@v1.2.3 if version is absent use the latest commit

func (*Core) Generate

func (c *Core) Generate(ctx context.Context, root, directory string) error

Generate generates files.

func (*Core) Get

func (c *Core) Get(ctx context.Context, requestedModule models.Module) error

Get download package.

func (*Core) Initialize

func (c *Core) Initialize(ctx context.Context, disk DirWalker, defaultLinters []string) error

Initialize initializes the EasyP configuration.

func (*Core) Lint

func (c *Core) Lint(ctx context.Context, fsWalker DirWalker) ([]IssueInfo, error)

Lint lints the proto file.

func (*Core) Update

func (c *Core) Update(ctx context.Context, dependencies []string) error

Update all packages from config dependencies slice of strings format: origin@version: github.com/company/repository@v1.2.3 if version is absent use the latest commit

func (*Core) Vendor

func (c *Core) Vendor(ctx context.Context) error

Vendor copy all proto files from deps to local dir

type CurrentProjectGitWalker

type CurrentProjectGitWalker interface {
	GetDirWalker(workingDir, gitRef, path string) (DirWalker, error)
}

CurrentProjectGitWalker is provider for fs walking for current project

type DirWalker

type DirWalker interface {
	FS
	WalkDir(callback func(path string, err error) error) error
}

type Enum

type Enum struct {
	EnumPath      string
	ProtoFilePath string
	PackageName   PackageName
	*unordered.Enum
}

type FS

type FS interface {
	Open(name string) (io.ReadCloser, error)
	Create(name string) (io.WriteCloser, error)
}

FS an interface for reading from some FS (os disk, git repo etc) and for writing to some FS

type FieldOptionHandler added in v0.11.0

type FieldOptionHandler struct {
	// Option is the option type identifier.
	Option FieldOptionType
	// HasDefault indicates if this option has a default value when managed mode is enabled.
	HasDefault bool
	// Default returns the default value for this option (if HasDefault is true).
	Default func() any
	// AppliesToType checks if this option applies to the given field type.
	AppliesToType func(t descriptorpb.FieldDescriptorProto_Type) bool
	// Apply applies the option value to the field.
	Apply func(field *descriptorpb.FieldDescriptorProto, value any)
}

FieldOptionHandler defines how to apply a field option.

type FieldOptionType added in v0.11.0

type FieldOptionType string

FieldOptionType represents the type of field option that can be managed.

const (
	// JavaScript type option for int64/uint64 fields
	FieldOptionJsType FieldOptionType = "jstype"
)

type FileOptionHandler added in v0.11.0

type FileOptionHandler struct {
	// Option is the option type identifier.
	Option FileOptionType
	// HasDefault indicates if this option has a default value when managed mode is enabled.
	// Only options listed in buf documentation as having defaults should have this set to true.
	HasDefault bool
	// Apply applies the option value to the file descriptor.
	// filePath is the path to the proto file (e.g., "internal/cms/as.proto").
	Apply func(fd *descriptorpb.FileDescriptorProto, value any, pkg, filePath string)
	// Default returns the default value for this option (if HasDefault is true).
	// This is called only when HasDefault is true and no override is specified.
	Default func(fd *descriptorpb.FileDescriptorProto, pkg string) any
	// AffectsOption specifies which base option this handler affects.
	// For example, go_package_prefix affects go_package.
	AffectsOption FileOptionType
}

FileOptionHandler defines how to apply a file option.

type FileOptionType added in v0.11.0

type FileOptionType string

FileOptionType represents the type of file option that can be managed.

const (
	// Go options
	FileOptionGoPackage       FileOptionType = "go_package"
	FileOptionGoPackagePrefix FileOptionType = "go_package_prefix"

	// Java options
	FileOptionJavaPackage         FileOptionType = "java_package"
	FileOptionJavaPackagePrefix   FileOptionType = "java_package_prefix"
	FileOptionJavaPackageSuffix   FileOptionType = "java_package_suffix"
	FileOptionJavaMultipleFiles   FileOptionType = "java_multiple_files"
	FileOptionJavaOuterClassname  FileOptionType = "java_outer_classname"
	FileOptionJavaStringCheckUtf8 FileOptionType = "java_string_check_utf8"

	// C# options
	FileOptionCsharpNamespace       FileOptionType = "csharp_namespace"
	FileOptionCsharpNamespacePrefix FileOptionType = "csharp_namespace_prefix"

	// Ruby options
	FileOptionRubyPackage       FileOptionType = "ruby_package"
	FileOptionRubyPackageSuffix FileOptionType = "ruby_package_suffix"

	// PHP options
	FileOptionPhpNamespace               FileOptionType = "php_namespace"
	FileOptionPhpMetadataNamespace       FileOptionType = "php_metadata_namespace"
	FileOptionPhpMetadataNamespaceSuffix FileOptionType = "php_metadata_namespace_suffix"

	// Objective-C options
	FileOptionObjcClassPrefix FileOptionType = "objc_class_prefix"

	// Swift options
	FileOptionSwiftPrefix FileOptionType = "swift_prefix"

	// Optimization options
	FileOptionOptimizeFor FileOptionType = "optimize_for"

	// C++ options
	FileOptionCcEnableArenas FileOptionType = "cc_enable_arenas"
)

type GenerateBucket added in v0.10.0

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

GenerateBucket is a thread-safe in-memory bucket for storing generated files. It provides methods for adding, retrieving, and removing files.

func NewGenerateBucket added in v0.10.0

func NewGenerateBucket() *GenerateBucket

func (*GenerateBucket) DumpToFs added in v0.10.0

func (b *GenerateBucket) DumpToFs(_ context.Context) error

func (*GenerateBucket) GetFile added in v0.10.0

func (b *GenerateBucket) GetFile(_ context.Context, path string) (*ImmutableData, bool)

func (*GenerateBucket) PutFile added in v0.10.0

func (b *GenerateBucket) PutFile(_ context.Context, path string, data []byte)

func (*GenerateBucket) RemoveFile added in v0.10.0

func (b *GenerateBucket) RemoveFile(_ context.Context, path string)

type GitRefNotFoundError

type GitRefNotFoundError struct {
	GitRef string
}

func (*GitRefNotFoundError) Error

func (e *GitRefNotFoundError) Error() string

type ImmutableData added in v0.10.0

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

ImmutableData represents an immutable byte slice.

func (*ImmutableData) Data added in v0.10.0

func (i *ImmutableData) Data() []byte

type Import

type Import struct {
	ProtoFilePath string
	PackageName   PackageName
	*parser.Import
}

type ImportPath

type ImportPath string

ImportPath type alias for path import in proto file

func ConvertImportPath

func ConvertImportPath(source string) ImportPath

type InputFilesDir added in v0.7.12

type InputFilesDir struct {
	Path string
	Root string
}

InputFilesDir is the configuration of the directory with additional functionality.

type InputGitRepo

type InputGitRepo struct {
	URL          string
	SubDirectory string
	Out          string
	Root         string
}

InputGitRepo is the configuration of the git repository.

type Inputs

type Inputs struct {
	InputFilesDir []InputFilesDir
	InputGitRepos []InputGitRepo
}

Inputs is the source for generating code.

type InstructionInfo

type InstructionInfo struct {
	PkgName     PackageName
	Instruction string
}

instructionInfo collects info about instruction in proto file e.g `google.api.http`:

`google.api` - package name
'http' - instruction name

func (InstructionInfo) GetFullName

func (i InstructionInfo) GetFullName() string

type InstructionParser

type InstructionParser struct {
	SourcePkgName PackageName
}

parseInstruction parse input string and return its package name if passed input does not have package -> return pkgName as package name source proto file

func (InstructionParser) Parse

func (p InstructionParser) Parse(input string) InstructionInfo

type Issue

type Issue struct {
	Position   meta.Position
	SourceName string
	Message    string
	RuleName   string
}

Issue contains the information of an issue.

func AppendIssue

func AppendIssue(
	issues []Issue, lintRule Rule, pos meta.Position, sourceName string, comments []*parser.Comment,
) []Issue

AppendIssue check if lint error is ignored -> add new error to slice otherwise ignore appending

type IssueInfo

type IssueInfo struct {
	Issue
	Path string
}

IssueInfo contains the information of an issue and the path.

type JSType added in v0.11.0

type JSType string

JSType represents the JavaScript type for int64/uint64 fields.

const (
	JSTypeNormal JSType = "JS_NORMAL"
	JSTypeString JSType = "JS_STRING"
	JSTypeNumber JSType = "JS_NUMBER"
)

type Lint

type Lint struct {
	Use                                  []string            `yaml:"use"`
	Except                               []string            `yaml:"except"`
	Ignore                               []string            `yaml:"ignore"`
	IgnoreOnly                           map[string][]string `yaml:"ignore_only"`
	AllowCommentIgnores                  bool                `yaml:"allow_comment_ignores"`
	EnumZeroValueSuffix                  string              `yaml:"enum_zero_value_suffix"`
	RPCAllowSameRequestResponse          bool                `yaml:"rpc_allow_same_request_response"`
	RPCAllowGoogleProtobufEmptyRequests  bool                `yaml:"rpc_allow_google_protobuf_empty_requests"`
	RPCAllowGoogleProtobufEmptyResponses bool                `yaml:"rpc_allow_google_protobuf_empty_responses"`
	ServiceSuffix                        string              `yaml:"service_suffix"`
}

Lint is the configuration for the lint section of the buf tool.

type LockFile

type LockFile interface {
	Read(moduleName string) (models.LockFileInfo, error)
	Write(
		moduleName string, revisionVersion string, installedPackageHash models.ModuleHash,
	) error
	IsEmpty() bool
	DepsIter() iter.Seq[models.LockFileInfo]
}

LockFile should implement adapter for lock file workflow

type ManagedDisableRule added in v0.11.0

type ManagedDisableRule struct {
	// Module disables managed mode for all files in the specified module.
	Module string
	// Path disables managed mode for files matching the specified path (directory or file).
	Path string
	// FileOption disables a specific file option from being modified.
	FileOption FileOptionType
	// FieldOption disables a specific field option from being modified.
	FieldOption FieldOptionType
	// Field disables a specific field (fully qualified name: package.Message.field).
	Field string
}

ManagedDisableRule defines a rule to disable managed mode for specific conditions.

type ManagedModeConfig added in v0.11.0

type ManagedModeConfig struct {
	// Enabled activates managed mode.
	Enabled bool
	// Disable contains rules to disable managed mode for specific conditions.
	Disable []ManagedDisableRule
	// Override contains rules to override file and field options.
	Override []ManagedOverrideRule
}

ManagedModeConfig is the runtime configuration for managed mode.

func (*ManagedModeConfig) GetFieldOptionOverride added in v0.11.0

func (c *ManagedModeConfig) GetFieldOptionOverride(filePath, module string, option FieldOptionType, fieldName string) any

GetFieldOptionOverride returns the override value for a field option, or nil if not overridden. If multiple overrides match, the last matching rule wins (buf behavior).

func (*ManagedModeConfig) GetFileOptionOverride added in v0.11.0

func (c *ManagedModeConfig) GetFileOptionOverride(filePath, module string, option FileOptionType) any

GetFileOptionOverride returns the override value for a file option, or nil if not overridden. If multiple overrides match, the last matching rule wins (buf behavior).

func (*ManagedModeConfig) IsFieldOptionDisabled added in v0.11.0

func (c *ManagedModeConfig) IsFieldOptionDisabled(filePath, module string, option FieldOptionType, fieldName string) bool

IsFieldOptionDisabled checks if a field option is disabled for the given field.

func (*ManagedModeConfig) IsFileOptionDisabled added in v0.11.0

func (c *ManagedModeConfig) IsFileOptionDisabled(filePath, module string, option FileOptionType) bool

IsFileOptionDisabled checks if a file option is disabled for the given file.

type ManagedOverrideRule added in v0.11.0

type ManagedOverrideRule struct {
	// FileOption specifies which file option to override.
	FileOption FileOptionType
	// FieldOption specifies which field option to override.
	FieldOption FieldOptionType
	// Value is the value to set for the option.
	Value any
	// Module applies this override only to files in the specified module.
	Module string
	// Path applies this override only to files matching the specified path.
	Path string
	// Field applies this override only to the specified field (fully qualified name).
	Field string
}

ManagedOverrideRule defines a rule to override file or field options.

type Message

type Message struct {
	MessagePath   string
	ProtoFilePath string
	PackageName   PackageName
	*unordered.Message
}

type Migrate

type Migrate struct {
	BUF *BUFConfig
}

Migrate contains original configuration for the migration.

type ModuleConfig

type ModuleConfig interface {
	ReadFromRepo(ctx context.Context, repo repository.Repo, revision models.Revision) (models.ModuleConfig, error)
}

ModuleConfig should implement adapter for reading module configs

type OneOf

type OneOf struct {
	OneOfPath     string
	ProtoFilePath string
	PackageName   PackageName
	*parser.Oneof
}

type OpenImportFileError

type OpenImportFileError struct {
	FileName string
}

func (*OpenImportFileError) Error

func (e *OpenImportFileError) Error() string

type OptimizeMode added in v0.11.0

type OptimizeMode string

OptimizeMode represents the optimization mode for generated code.

const (
	OptimizeModeSpeed       OptimizeMode = "SPEED"
	OptimizeModeCodeSize    OptimizeMode = "CODE_SIZE"
	OptimizeModeLiteRuntime OptimizeMode = "LITE_RUNTIME"
)

type PackageName

type PackageName string

PackageName type alias for package name `package` section in protofile.

func GetPackageName

func GetPackageName(protoFile *unordered.Proto) PackageName

type Plugin

type Plugin struct {
	Source      PluginSource
	Out         string
	Options     map[string]string
	WithImports bool
}

Plugin is a plugin for gRPC generator.

type PluginSource added in v0.8.0

type PluginSource struct {
	Name    string
	Remote  string
	Path    string
	Command []string
}

PluginSource is the source of the plugin.

type ProtoData

type ProtoData map[PackageName]*Collection

collects proto data collections packageName -> services,messages etc

type ProtoInfo

type ProtoInfo struct {
	Path                 string
	Info                 *unordered.Proto
	ProtoFilesFromImport map[ImportPath]*unordered.Proto
}

ProtoInfo is the information of a proto file.

type Query

type Query struct {
	Imports []string
	Plugins []Plugin
	Files   []string
}

Query is a query for making sh command.

type Repo

type Repo interface {
	// GetFiles returns list of all files in repository
	GetFiles(ctx context.Context, revision models.Revision, dirs ...string) ([]string, error)

	// ReadFile returns file's content from repository
	ReadFile(ctx context.Context, revision models.Revision, fileName string) (string, error)

	// Archive passed storage to archive and return full path to archive
	Archive(
		ctx context.Context, revision models.Revision, cacheDownloadPaths models.CacheDownloadPaths,
	) error

	// ReadRevision reads commit's revision by passed version
	// or return the latest commit if version is empty
	ReadRevision(ctx context.Context, requestedVersion models.RequestedVersion) (models.Revision, error)

	// Fetch from remote repository specified version
	Fetch(ctx context.Context, revision models.Revision) error
}

type Rule

type Rule interface {
	// Message returns the message of the rule.
	Message() string
	// Validate validates the proto rule.
	Validate(ProtoInfo) ([]Issue, error)
}

Rule is an interface for a rule checking.

type Service

type Service struct {
	ProtoFilePath string
	PackageName   PackageName
	*unordered.Service
}

type Storage

type Storage interface {
	CreateCacheRepositoryDir(name string) (string, error)
	CreateCacheDownloadDir(models.CacheDownloadPaths) error
	GetCacheDownloadPaths(module models.Module, revision models.Revision) models.CacheDownloadPaths
	Install(
		cacheDownloadPaths models.CacheDownloadPaths,
		module models.Module,
		revision models.Revision,
		moduleConfig models.ModuleConfig,
	) (models.ModuleHash, error)
	GetInstalledModuleHash(moduleName string, revisionVersion string) (models.ModuleHash, error)
	IsModuleInstalled(module models.Module) (bool, error)
	GetInstallDir(moduleName string, revisionVersion string) string
}

Storage should implement workflow with storage adapter

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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