Documentation
¶
Overview ¶
Package xlsxcfg converts Excel (.xlsx) sheets into Protocol Buffer-defined config data.
Pipeline: parse .proto → build TypeProvider → optionally load constants → read .xlsx row-wise (or column-wise for transposed sheets) → parse rows into OrderedMaps → convert to dynamicpb.Messages → write output (JSON, msgpack, protobuf binary).
Package xlsxcfg converts Excel (.xlsx) sheets into Protocol Buffer-defined config data. Sheets are read row-wise (or column-wise for transposed sheets), then mapped to nested structures via closure-based cell-to-field dispatch.
Index ¶
- func GetFieldDescriptor(md protoreflect.MessageDescriptor, path ...string) protoreflect.FieldDescriptor
- func IsStrField(md protoreflect.MessageDescriptor, path ...string) bool
- func IterXlsxFiles(ctx context.Context, param *Config, files ...string) iter.Seq2[*SheetResult, error]
- func LoadXlsxFiles(ctx context.Context, param *Config, files ...string) (map[string][]any, error)
- func ResolveRowMessageType(tp TypeProvider, sheetName string, cfg *Config) (string, error)
- type Config
- func (p *Config) GetFieldDescriptor(typeName, fieldPath string) protoreflect.FieldDescriptor
- func (p *Config) IsComment(i int, row []string) bool
- func (p *Config) IsData(i int, row []string) bool
- func (p *Config) IsMeta(i int, row []string) bool
- func (p *Config) IsStrField(typeName, fieldPath string) bool
- func (p *Config) IsTransposeComment(i int, col []string) bool
- func (p *Config) IsTransposeData(i int, col []string) bool
- func (p *Config) IsTransposeMeta(i int, col []string) bool
- func (p *Config) TypeProvider() TypeProvider
- type ConfigFile
- func (c *ConfigFile) EffectiveRepeatedScalarSeparator() string
- func (c *ConfigFile) EffectiveTransposeCommentCols() []int
- func (c *ConfigFile) EffectiveTransposeDataColCount() int
- func (c *ConfigFile) EffectiveTransposeDataColStart() int
- func (c *ConfigFile) EffectiveTransposeMark() string
- func (c *ConfigFile) EffectiveTransposeMetaCol() int
- func (c *ConfigFile) EffectiveTransposeSkipRows() map[int]bool
- func (c *ConfigFile) FieldOrder() string
- func (c *ConfigFile) IsIgnored(sheetName string) bool
- func (c *ConfigFile) IsSourceOrder() bool
- func (c *ConfigFile) IsTransposed(sheetName string) bool
- func (c *ConfigFile) ResolveDir(formatDir string) string
- func (c *ConfigFile) StripTransposeMark(sheetName string) string
- func (c *ConfigFile) Validate() error
- type JSONOutputFormat
- type OrderedMap
- func (m *OrderedMap) All() iter.Seq2[string, any]
- func (m *OrderedMap) Get(key string) (any, bool)
- func (m *OrderedMap) Keys() []string
- func (m *OrderedMap) Len() int
- func (m *OrderedMap) MarshalJSON() ([]byte, error)
- func (m *OrderedMap) Set(key string, val any)
- func (m *OrderedMap) UnmarshalJSON(data []byte) error
- type OutputFormat
- type SheetResult
- type TransposeSheetConfig
- type TypeProvider
- type ValueConvert
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetFieldDescriptor ¶
func GetFieldDescriptor(md protoreflect.MessageDescriptor, path ...string) protoreflect.FieldDescriptor
GetFieldDescriptor walks a dot-separated field path through a message descriptor and returns the leaf FieldDescriptor, or nil if any segment doesn't resolve. Map values are traversed into their value message type.
func IsStrField ¶
func IsStrField(md protoreflect.MessageDescriptor, path ...string) bool
IsStrField reports whether the leaf field at the given path is a string type.
func IterXlsxFiles ¶
func IterXlsxFiles(ctx context.Context, param *Config, files ...string) iter.Seq2[*SheetResult, error]
IterXlsxFiles returns an iterator yielding one SheetResult per sheet across all xlsx files. Only one sheet's rows are in memory at a time. Duplicate sheet names produce an error.
for sr, err := range xlsxcfg.IterXlsxFiles(ctx, param, "data.xlsx") {
if err != nil { ... }
for row, err := range sr.Rows { ... }
}
func LoadXlsxFiles ¶
LoadXlsxFiles eagerly loads all sheets from multiple xlsx files into a map keyed by sheet name. For streaming, use IterXlsxFiles instead.
func ResolveRowMessageType ¶
func ResolveRowMessageType(tp TypeProvider, sheetName string, cfg *Config) (string, error)
ResolveRowMessageType returns the fully-qualified proto type name for the row messages of a sheet. When proto is enabled, it reads the wrapper message (resolved via sheetName + Sheet.TypeSuffix), finds the field named by Sheet.ListFieldName, and returns the message type of that field — the proto's own ground truth for the row type. When proto is disabled (raw mode), it falls back to sheetName + Sheet.RowTypeSuffix because no descriptor is available.
Errors name the sheet, the wrapper message attempted, and the field name attempted so misconfigured sheets can be diagnosed at iteration time rather than via a deferred panic deep in field resolution.
Types ¶
type Config ¶
type Config struct {
*ConfigFile
ConstData *constant.Data // nil when constant loading is disabled
// contains filtered or unexported fields
}
Config combines ConfigFile with a TypeProvider for runtime proto field lookups.
func NewConfig ¶
func NewConfig(cfg *ConfigFile, tp TypeProvider) *Config
NewConfig creates a runtime Config from a ConfigFile and TypeProvider.
func (*Config) GetFieldDescriptor ¶
func (p *Config) GetFieldDescriptor(typeName, fieldPath string) protoreflect.FieldDescriptor
GetFieldDescriptor returns the proto FieldDescriptor for the leaf field at the dot-separated fieldPath, or nil if not resolvable.
func (*Config) IsComment ¶
IsComment reports whether the row at 0-based index i is a comment row. Compares against 1-based config values (i+1).
func (*Config) IsData ¶
IsData reports whether the row at 0-based index i is a data row (i+1 >= DataRowStart).
func (*Config) IsMeta ¶
IsMeta reports whether the row at 0-based index i is the metadata row (compares i+1 against 1-based MetaRow).
func (*Config) IsStrField ¶
IsStrField checks whether the leaf field at the dot-separated fieldPath within the named proto message is a string type. Returns true for all fields when proto is disabled.
When the named message cannot be found in the loaded proto schema, it reports a structured error and returns true so the unknown field is treated as a string. This avoids terminating the process from library code; callers that need an error should validate the proto message type earlier in the pipeline. An error-returning signature is tracked as a follow-up since the sole caller (the row parser closure) treats this as a bool.
func (*Config) IsTransposeComment ¶
IsTransposeComment reports whether the column at 0-based index i is a comment column.
func (*Config) IsTransposeData ¶
IsTransposeData reports whether the column at 0-based index i is a data column.
func (*Config) IsTransposeMeta ¶
IsTransposeMeta reports whether the column at 0-based index i is the metadata column.
func (*Config) TypeProvider ¶
func (p *Config) TypeProvider() TypeProvider
TypeProvider returns the proto TypeProvider for this Config, or nil when proto is disabled.
type ConfigFile ¶
type ConfigFile struct {
// Proto configures which .proto files to load and where to resolve imports.
Proto struct {
Enabled bool `yaml:"enabled"`
Files []string `yaml:"files"` // e.g. ["hero.proto"]
ImportPath []string `yaml:"import_path"` // like protoc's -I flag
} `yaml:"proto"`
// Sheet configures row classification and sheet-to-proto name mapping.
Sheet struct {
CommentRows []int `yaml:"comment_rows"` // 1-based row indices to skip
MetaRow int `yaml:"meta_row"` // 1-based row index for metadata/type hints
DataRowStart int `yaml:"data_row_start"` // 1-based; must be > MetaRow
TypeSuffix string `yaml:"type_suffix"` // e.g. "Sheet" → "Hero" maps to "HeroSheet"
ListFieldName string `yaml:"list_field_name"` // e.g. "rows" in `repeated HeroSheetRow rows = 1;`
ListFieldNameCaseInsensitive bool `yaml:"list_field_name_case_insensitive"` // opt-in EqualFold fallback after exact list_field_name lookup
CellTrimSpace bool `yaml:"cell_trim_space"` // opt-in: strip leading/trailing Unicode whitespace from every cell at the read boundary
RepeatedScalarSeparator string `yaml:"repeated_scalar_separator"` // opt-in; "" disables packed-cell parsing for repeated scalar fields without #N
RowTypeSuffix string `yaml:"row_type_suffix"` // e.g. "SheetRow" → "Hero" maps to "HeroSheetRow"
Transpose TransposeSheetConfig `yaml:"transpose"` // column-per-record parsing config
TransposeMark string `yaml:"transpose_mark"` // legacy prefix/suffix marking transposed sheets (e.g. "~")
IgnoreMark string `yaml:"ignore_mark"` // prefix/suffix marking ignored sheets (e.g. "!")
} `yaml:"sheet"`
// Constant configures optional key-value constant loading from xlsx files.
// Cell values matching [Key] are replaced with the corresponding constant value.
Constant constant.Config `yaml:"constant"`
// ValueConvert configures opt-in string→typed mappings for scalar numeric
// and boolean proto fields. See ValueConvert for semantics.
ValueConvert ValueConvert `yaml:"value_convert"`
// Output configures where and how converted data is written.
Output struct {
Dir string `yaml:"dir"` // default output directory
FieldOrder string `yaml:"field_order"` // "schema" (proto field#) or "source" (xlsx column order)
RawJSON JSONOutputFormat `yaml:"raw_json"` // raw JSON without proto validation
RawMsgpack OutputFormat `yaml:"raw_msgpack"` // raw msgpack without proto validation
JSON JSONOutputFormat `yaml:"json"` // proto-validated JSON
Msgpack OutputFormat `yaml:"msgpack"` // proto-validated msgpack
PbBytes OutputFormat `yaml:"pb_bytes"` // proto-validated protobuf binary
} `yaml:"output"`
}
ConfigFile represents the YAML configuration that controls how xlsx sheets map to proto messages and how output is written.
func ConfigFromFile ¶
func ConfigFromFile(f string) (*ConfigFile, error)
ConfigFromFile reads and parses a YAML configuration file.
func DefaultConfig ¶
func DefaultConfig() *ConfigFile
DefaultConfig returns a ConfigFile with proto disabled and only raw_json enabled.
func (*ConfigFile) EffectiveRepeatedScalarSeparator ¶
func (c *ConfigFile) EffectiveRepeatedScalarSeparator() string
EffectiveRepeatedScalarSeparator returns the configured packed-cell separator.
func (*ConfigFile) EffectiveTransposeCommentCols ¶
func (c *ConfigFile) EffectiveTransposeCommentCols() []int
EffectiveTransposeCommentCols returns comment columns for transposed sheets. A nil sheet.transpose.comment_cols falls back to sheet.comment_rows; an empty configured list means no comment columns.
func (*ConfigFile) EffectiveTransposeDataColCount ¶
func (c *ConfigFile) EffectiveTransposeDataColCount() int
EffectiveTransposeDataColCount returns the configured transposed data column limit. Zero means unbounded.
func (*ConfigFile) EffectiveTransposeDataColStart ¶
func (c *ConfigFile) EffectiveTransposeDataColStart() int
EffectiveTransposeDataColStart returns the first data column for transposed sheets.
func (*ConfigFile) EffectiveTransposeMark ¶
func (c *ConfigFile) EffectiveTransposeMark() string
EffectiveTransposeMark returns the configured transposed sheet marker. The nested sheet.transpose.mark takes precedence over legacy sheet.transpose_mark.
func (*ConfigFile) EffectiveTransposeMetaCol ¶
func (c *ConfigFile) EffectiveTransposeMetaCol() int
EffectiveTransposeMetaCol returns the metadata column for transposed sheets.
func (*ConfigFile) EffectiveTransposeSkipRows ¶
func (c *ConfigFile) EffectiveTransposeSkipRows() map[int]bool
EffectiveTransposeSkipRows returns configured transposed skip rows as a set of 1-based Excel row numbers. Duplicate entries collapse harmlessly.
func (*ConfigFile) FieldOrder ¶
func (c *ConfigFile) FieldOrder() string
FieldOrder returns the configured field ordering, defaulting to "schema" (proto field number order).
func (*ConfigFile) IsIgnored ¶
func (c *ConfigFile) IsIgnored(sheetName string) bool
IsIgnored reports whether sheetName should be skipped.
func (*ConfigFile) IsSourceOrder ¶
func (c *ConfigFile) IsSourceOrder() bool
IsSourceOrder reports whether output should use xlsx column order.
func (*ConfigFile) IsTransposed ¶
func (c *ConfigFile) IsTransposed(sheetName string) bool
IsTransposed reports whether sheetName should be parsed column-per-record instead of row-per-record.
func (*ConfigFile) ResolveDir ¶
func (c *ConfigFile) ResolveDir(formatDir string) string
ResolveDir returns the effective output directory for a format. Priority: format's own dir > output.dir > "."
func (*ConfigFile) StripTransposeMark ¶
func (c *ConfigFile) StripTransposeMark(sheetName string) string
StripTransposeMark removes the leading or trailing effective transpose mark from sheetName.
func (*ConfigFile) Validate ¶
func (c *ConfigFile) Validate() error
Validate checks that the configuration is well-formed: data_row_start > meta_row, no comment/meta overlap, suffixes and proto files set when proto is enabled, and at least one output format enabled.
type JSONOutputFormat ¶
type JSONOutputFormat struct {
OutputFormat `yaml:",inline"`
Indent string `yaml:"indent"` // e.g. " "; empty produces compact JSON
}
JSONOutputFormat adds JSON-specific settings to OutputFormat.
type OrderedMap ¶
type OrderedMap struct {
// contains filtered or unexported fields
}
OrderedMap is a map[string]any that preserves key insertion order. It implements json.Marshaler and json.Unmarshaler. The zero value is ready to use.
func NewOrderedMap ¶
func NewOrderedMap(n int) *OrderedMap
NewOrderedMap creates an OrderedMap pre-allocated for n entries.
func (*OrderedMap) All ¶
func (m *OrderedMap) All() iter.Seq2[string, any]
All returns an iterator over key-value pairs in insertion order.
func (*OrderedMap) Get ¶
func (m *OrderedMap) Get(key string) (any, bool)
Get returns the value for a key. The second return indicates whether the key was found.
func (*OrderedMap) Keys ¶
func (m *OrderedMap) Keys() []string
Keys returns the keys in insertion order.
func (*OrderedMap) MarshalJSON ¶
func (m *OrderedMap) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler. Keys are written in insertion order.
func (*OrderedMap) Set ¶
func (m *OrderedMap) Set(key string, val any)
Set stores a key-value pair, updating in place if the key exists.
func (*OrderedMap) UnmarshalJSON ¶
func (m *OrderedMap) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, preserving key order.
type OutputFormat ¶
type OutputFormat struct {
Enabled bool `yaml:"enabled"`
Dir string `yaml:"dir"` // inherits from Output.Dir when empty
Extension string `yaml:"extension"` // e.g. ".json", ".bytes"; uses format default when empty
}
OutputFormat configures a single output format.
type SheetResult ¶
type SheetResult struct {
Name string // xlsx sheet name (e.g., "Hero", "Item")
Rows iter.Seq2[*OrderedMap, error] // yields parsed data rows; empty rows are skipped
}
SheetResult holds a sheet name and a row iterator. Rows must be fully consumed before advancing to the next sheet because the underlying xlsx reader is shared.
type TransposeSheetConfig ¶
type TransposeSheetConfig struct {
Mark string `yaml:"mark"` // prefix/suffix marking transposed sheets; overrides Sheet.TransposeMark when set
CommentCols []int `yaml:"comment_cols"` // 1-based column indices to skip; falls back to Sheet.CommentRows when nil
MetaCol int `yaml:"meta_col"` // 1-based metadata column; falls back to Sheet.MetaRow when zero
DataColStart int `yaml:"data_col_start"` // 1-based data start column; falls back to Sheet.DataRowStart when zero
DataColCount int `yaml:"data_col_count"` // 0 means unbounded; positive limits data columns; negative is invalid
SkipRows []int `yaml:"skip_rows"` // 1-based Excel row indices to ignore in transposed columns
}
TransposeSheetConfig configures column-per-record parsing for transposed sheets.
type TypeProvider ¶
type TypeProvider interface {
// MessageByName returns the MessageDescriptor for the given short name, or nil.
MessageByName(string) protoreflect.MessageDescriptor
}
TypeProvider looks up proto message descriptors by short name (e.g. "HeroSheet"). The row parser uses it to determine field types, walk nested messages, and build dynamic proto messages.
func LoadProtoFiles ¶
func LoadProtoFiles(ctx context.Context, importPaths []string, fileNames ...string) (tp TypeProvider, err error)
LoadProtoFiles compiles .proto files at runtime using protocompile (no protoc needed). Returns a TypeProvider indexing all top-level messages from the compiled files and their transitive imports by short name.
type ValueConvert ¶
type ValueConvert struct {
Enabled bool `yaml:"enabled"` // master switch; false means maps are ignored entirely
ToNumber map[string]int64 `yaml:"to_number"` // cell text → int64 for numeric proto fields
ToBool map[string]bool `yaml:"to_bool"` // cell text → bool for proto bool fields
}
ValueConvert configures opt-in string→typed mappings for cell values targeting scalar numeric and boolean proto fields. Lookup is case-sensitive, runs after constant resolution and before strconv.ParseInt, and only fires for fields whose proto kind is BoolKind or one of the numeric Kinds. Has no effect when Enabled is false or when proto is disabled (the parser falls back to string verbatim).
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package app orchestrates the xlsxcfg pipeline.
|
Package app orchestrates the xlsxcfg pipeline. |
|
bin
|
|
|
xlsxcfg
command
Package main is the CLI entry point for xlsxcfg.
|
Package main is the CLI entry point for xlsxcfg. |
|
Package constant loads key-value lookup tables from Excel files.
|
Package constant loads key-value lookup tables from Excel files. |
|
Package convert converts parsed xlsx data into protobuf dynamic messages.
|
Package convert converts parsed xlsx data into protobuf dynamic messages. |
|
Package flagutil deep-merges unrecognized --key=value CLI args into a ConfigFile.
|
Package flagutil deep-merges unrecognized --key=value CLI args into a ConfigFile. |
|
Package writer writes parsed xlsx sheet data to files in various formats.
|
Package writer writes parsed xlsx sheet data to files in various formats. |
