RFC: Typed config API for format/config

Aberta
#2,002 2 comentários 1 reação 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 3 dias

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
5/5
Tempo estimado
Mais de uma semana
Facilidade para iniciantes
28/100
Tipo de issue
Funcionalidade
Clareza
Razoavelmente clara
Status de atividade
Pouca atividade
Stack de tecnologia
go

Direção de pesquisa

Comece lendo o pacote existente plumbing/format/config e o pacote config de nível mais alto, concentrando-se em Config, Options, Section, Subsection, Option e no decoder/encoder. O RFC lista o parsing tipado necessário, os acessors, o matching, os valores padrão, a resolução de URL, os comentários, a validação e as mudanças nos limites entre pacotes; considera-se concluído quando tudo isso estiver projetado e implementado de forma consistente em todo o modelo de configuração.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

no-autoclose

Summary

Make plumbing/format/config.Config the single data model for all git
configuration, replacing the higher-level config package's hard-coded
struct projection. Add a typed query/mutation API that mirrors the
capabilities of the canonical git config command — including
git-specific value types (bool, int, path, color, expiry-date), typed
getters and setters, value-pattern matching for multi-valued keys, regex
key search, section rename, default values, and inline comments.

Motivation

Current API is string-only and ad-hoc.

format/config stores every value as a raw string. The higher-level
config package performs type coercion case-by-case using strconv.ParseBool,
which does not match git's keyword set. There are no reusable typed accessors,
no value-pattern matching, and no canonicalisation on write.

Incorrect bool parsing.

Git accepts yes, on, no, off, non-zero integers, and bare keys (no =)
as booleans. Go's strconv.ParseBool only accepts true/false/1/0 and
their short forms. This is a correctness gap that affects any consumer that
reads boolean config values.

No integer suffix expansion.

Git config values like 10M, 1G, 512k are common (e.g.
pack.windowMemory, core.bigFileThreshold). go-git cannot parse them.

No multi-value discrimination.

Git's set --value=<pattern>, unset --value=<pattern>, and get --value=<pattern>
target specific values within a multi-valued key. go-git's SetOption
replaces the first occurrence by key only; RemoveOption removes all values.

No regex key search.

git config get --regexp finds all keys matching a regex. go-git has no
equivalent — consumers must iterate sections manually.

No URL-matched config.

git config get --url=<URL> resolves config scoped to a URL subsection
(e.g. [http "https://weak.example.com"]). go-git has no generic URL-match
resolution.

Hard-coded struct projection loses data and adds overhead.

The config package projects the raw config tree into a fixed Go struct
(config.Config with Core, Pack, User, etc.). This has three
problems:

  1. Data loss: any key not modelled in the struct is silently dropped
    unless it survives in the Raw escape hatch. A free-form config should
    be able to hold arbitrary data that the repository, global, or system
    scopes contain — just as git's own config_set does.

  2. Double decoding: raw bytes are decoded into a format.Config tree,
    then decoded again into the config.Config struct. Marshal must
    reverse the projection back into the tree before encoding. If a struct
    field is mutated but Marshal is not called, Raw becomes stale.

  3. Misplaced domain types: config.RemoteConfig, config.Branch, and
    config.Submodule are domain objects that happen to be populated from
    config — they are not config itself. In canonical git, these types live
    in their own subsystems (remote.h, branch.h, submodule.h), not
    in config.h.

Detailed design

1. Type-aware parse functions

Introduce standalone parse and canonicalise functions for each git config
value type. These live in plumbing/format/config so that both the raw
and high-level config packages share a single, correct implementation of
git's parsing rules.

2. Bool parsing

Replace all use of strconv.ParseBool with a git-compatible parser:

// ParseBool parses a git config boolean value.
// True:  "true", "yes", "on", any non-zero integer, bare key (empty value).
// False: "false", "no", "off", "0", empty string.
// Returns an error for unrecognised values.
func ParseBool(s string) (bool, error)

The empty-string case requires a sentinel: git treats a bare key (no =)
as true, but the current decoder stores it as "" which is ambiguous with
an explicitly empty value. The decoder should be updated to distinguish
these cases (see section 8).

3. Integer suffix expansion
// ParseInt parses a git config integer with optional suffix.
// Suffixes: k/K → 1024, m/M → 1048576, g/G → 1073741824.
func ParseInt(s string) (int64, error)
4. Path expansion
// ParsePath expands leading ~ to $HOME and ~user to the user's home
// directory, matching git's --type=path behaviour.
func ParsePath(s string) (string, error)
5. Color type
type Color struct {
    Foreground string   // e.g. "red", "bold blue", "#ff0000", "255"
    Background string   // optional, e.g. "normal red"
    Attributes []string // e.g. "bold", "ul", "reverse", "no-ul"
}

// ParseColor validates and parses a git color specification.
func ParseColor(s string) (Color, error)

// String returns the canonical form.
func (c Color) String() string
6. Expiry-date type
// ParseExpiryDate parses a git expiry-date value.
// Supports both absolute timestamps and relative dates like "2.weeks.ago".
func ParseExpiryDate(s string) (time.Time, error)
7. Typed getters on Options

Add typed accessors to Options that use the git-compatible parsers:

func (o Options) GetBool(key string) (bool, error)
func (o Options) GetInt(key string) (int64, error)
func (o Options) GetPath(key string) (string, error)
func (o Options) GetColor(key string) (Color, error)
func (o Options) GetExpiryDate(key string) (time.Time, error)

These complement — not replace — the existing Get, GetAll, and Has
methods.

8. Default config values

Provide a package-level default config that contains the canonical default
values for key git config options that go-git supports. This serves as the
single source of truth for defaults and is used by GetDefault and typed
getters when a key is absent.

// defaultConfig holds the canonical default values for git config options
// that go-git recognises.  It mirrors the defaults documented in git-config(1).
var defaultConfig = &Config{
    // populated with sections/options for:
    //   core.filemode = true
    //   core.bare = false
    //   core.logallrefupdates = true
    //   core.repositoryformatversion = "0"
    //   pack.window = 10
    //   ...
}

// Default returns a copy of the default config.  Consumers can use it
// directly or as a fallback when a key is not present in their own config.
func Default() *Config

The GetDefault method on Options uses this to resolve defaults without
the caller having to supply them explicitly:

// GetDefault returns the value for key from the default config.
// The bool indicates whether a default exists for that key.
// If the key is absent from both the options and the defaults, returns ("", false).
func (o Options) GetDefault(key string) (string, bool)

Callers that need a custom fallback (e.g. a default that differs from
git's canonical one) can still call Get and handle the empty-string
case themselves.

9. Typed setters on Options
func (o *Options) SetBool(key string, v bool)
func (o *Options) SetInt(key string, v int64)
func (o *Options) SetColor(key string, c Color)

These canonicalise values on write (e.g. SetBool("bare", true) writes
"true", not "True" or "1").

10. Value-pattern matching for multi-valued keys

Today SetOption replaces the first occurrence by key, and RemoveOption
removes all values. Git allows targeting specific values within a
multi-valued key via --value=<pattern> (regex) and --fixed-value
(exact string).

type ValueMatch struct {
    Pattern     string // regex or literal
    FixedValue  bool   // true → exact string match; false → regex
    Negated     bool   // true → match values that don't match the pattern
}

// SetOptionValue replaces values matching the pattern with newValue.
// If no pattern is provided, replaces the first occurrence (current behaviour).
func (s *Section) SetOptionValue(key string, match ValueMatch, newValue string) *Section

// RemoveOptionValue removes only values matching the pattern.
func (s *Section) RemoveOptionValue(key string, match ValueMatch) *Section

// Same on Subsection.
func (s *Subsection) SetOptionValue(key string, match ValueMatch, newValue string) *Subsection
func (s *Subsection) RemoveOptionValue(key string, match ValueMatch) *Subsection

The --append semantics (git config set --append) map to
SetOptionValue with ValueMatch{Pattern: "", FixedValue: true} (i.e.
never match, always append) — matching git's CONFIG_REGEX_NONE sentinel.

11. Regex key search
type KeyValue struct {
    Key   string
    Value string
}

// Find returns all key-value pairs whose key matches the given regexp.
// The regexp is matched against the canonicalised key
// (section.lowercase + "." + variable.lowercase, subsection preserves case).
func (c *Config) Find(pattern string) ([]KeyValue, error)

This maps to git config get --all --show-names --regexp <pattern>.

12. Section rename
// RenameSection renames all sections with oldName to newName.
// Options and subsections are preserved.
func (c *Config) RenameSection(oldName, newName string) *Config
13. URL-matched config
// GetURLMatch resolves a config value scoped to the best-matching URL
// subsection.  For a two-part name like "http.sslVerify", it looks for
// [http "<URL>"] sslVerify where <URL> best matches the given url,
// falling back to [http] sslVerify.
func (c *Config) GetURLMatch(section, key, url string) (string, error)

URL matching follows git's specificity rules: scheme must match exactly,
host is compared with optional wildcard, port must match, longer path
prefix wins, explicit username wins over no username.

14. Inline comments on options
type Option struct {
    Key     string
    Value   string
    Comment string // inline comment after the value (without the " #" prefix)
}

The encoder writes key = value # comment when Comment is non-empty.
The decoder populates it when a comment is found on the same line as a value.

// AddOptionComment adds a key=value pair with an inline comment.
func (s *Section) AddOptionComment(key, value, comment string) *Section
15. Key validation
// ValidateKey checks that a key conforms to git's naming rules:
// section.variable where section and variable contain only
// alphanumeric characters and '-', start with an alphabetic character,
// and are case-insensitively unique.
func ValidateKey(key string) error

// ValidateSectionName checks that a section name contains only
// alphanumeric characters, '-', and '.', and starts with an alphabetic
// character.
func ValidateSectionName(name string) error
16. Bare-key representation in the decoder

Currently the decoder treats a bare key (no =) as having value "", which
is ambiguous with key = "" (explicit empty string). In git, a bare key means
boolean true. The decoder should be updated to store the value as the
constant BoolTrue (e.g. a special sentinel like "\0" or a new field on
Option), so that ParseBool can correctly interpret it.

Options for representation:

  • Option A: Add bool IsBareKey field to Option. Simple, explicit.
  • Option B: Use a sentinel value constant (const BareKeyTrue = "\x00")
    that ParseBool recognises. Avoids struct change but is a magic value.

Recommendation: Option A — explicit is better than implicit.

17. Dissolving the config package

This RFC proposes making format/config.Config the single data model for all
git configuration, which eliminates the need for the config package's
struct projection. This follows how canonical git works.

How canonical git organises config

Git's config subsystem (config.h / config.c) is a generic key-value
store
with typed getters. It has zero knowledge of remotes, branches, or
submodules. When remote.c needs a struct remote, it calls
git_config_get_value("remote.origin.url") at the call site to populate
it. The rich domain types live in their own subsystems:

Subsystem Defines Populated from config via
remote.h / remote.c struct remote git_config_get_value("remote.<name>.url")
branch.h / branch.c struct branch git_config_get_value("branch.<name>.remote")
submodule.h / submodule.c struct submodule git_config_get_value("submodule.<name>.url")

The config layer never defines struct remote or struct branch. It
provides the primitives (get, set, list, type-aware parse) and each
subsystem builds its own view on demand.

Proposed mapping for go-git
Canonical git go-git today go-git after this RFC
config.h / config.c format/config format/config (enriched with typed getters, defaults, value-pattern, etc.)
remote.h / remote.c config.RemoteConfig git.RemoteConfig (or plumbing/remote)
branch.h / branch.c config.Branch git.Branch (or plumbing/branch)
submodule.h / submodule.c config.Submodule git.Submodule (or plumbing/submodule)

The config package itself dissolves. Its only remaining purpose was the
struct projection, which is eliminated by making format/config.Config the
single data model. Code that currently reads cfg.Core.IsBare would
instead call cfg.Section("core").GetBool("bare"). Domain types like
RemoteConfig are constructed on demand by their respective porcelain
packages from the underlying config tree, not maintained as a parallel
projection.

Why this is better
  • No data loss: format/config.Config holds everything the config
    files contain. There is no struct to be incomplete relative to the
    real config.
  • No double decoding: one parse pass, one data model. No Raw field,
    no stale-tree bugs, no Marshal round-trip.
  • Single source of truth: typed getters on Options replace ad-hoc
    parsing scattered across the config package. Every consumer uses the
    same git-compatible ParseBool, ParseInt, etc.
  • Domain types live where they belong: RemoteConfig is a remote concern,
    not a config concern. Putting it in git (or plumbing/remote) follows
    canonical git's own separation and keeps format/config clean.
  • Extensibility: new config sections require no changes to format/config.
    Consumers read them with the generic API. Only when a rich domain type
    is warranted does a subsystem define one.
18. What is NOT in scope

The following are explicitly out of scope for this RFC but could be addressed
in future RFCs:

  • Conditional includes (includeIf): requires repository context
    (current branch, .git path, remote URLs) and cannot be resolved at the
    format/config layer alone. A future RFC could add an EvaluateIncludes
    method that accepts a repository context interface.

  • Scope and origin tracking: Adding Origin and Scope fields to
    Option would enable --show-origin / --show-scope display and
    protected-config filtering. This is a separate concern that can be layered
    on top.

  • Atomic file writes with locking: This is a storage/filesystem concern
    and does not belong in format/config.

  • Config file discovery (--system, --global, --local): This is the
    responsibility of the config package and the ConfigLoader plugin, not
    format/config.

Drawbacks

1. API surface growth

The proposal adds ~20 new methods and types to format/config. This
increases the maintenance burden and the learning curve for new consumers.
Mitigation: the new methods are additive and the existing string-only API
remains fully functional. Consumers can adopt typed methods incrementally.

2. Implementation complexity for color and expiry-date types

Color parsing involves ~10 attributes, 256-color and 24-bit RGB support,
and negated attribute forms (no-ul, noreverse). ExpiryDate requires
a relative-date parser ("2.weeks.ago") which is non-trivial.
Mitigation: these can be implemented incrementally. The MVP can ship with
bool, int, and path types first; color and expiry-date can follow.

3. Bare-key representation is a subtle breaking change

Adding IsBareKey to Option changes the struct layout. Any code that
constructs Option literals will need updating. Mitigation: since this is
targeting main (v6), breaking changes are acceptable with proper
documentation. The zero-value (IsBareKey: false) preserves existing
behaviour for all current usage.

4. Value-pattern matching requires regex support

The ValueMatch type introduces a dependency on regexp for value-pattern
matching. Mitigation: regexp is already widely used in the codebase and
is part of the Go standard library.

Rationale and alternatives

Why put types in format/config rather than a separate package?

Alternative 1: Create a configtypes sub-package with ParseBool,
ParseInt, etc. Both format/config and config import it.

Rationale for rejection: Adds an extra package for a concern that is
inherently tied to the git config format. The parsing rules (bool keywords,
integer suffixes, path expansion) are specific to git config files, not
generic utilities. Co-locating them with the config types they operate on
keeps the API discoverable.

Alternative 2: Keep types in the higher-level config package only.

Rationale for rejection: Anyone using format/config directly (e.g. for
custom config sections not modelled by the config package) must re-implement
git's parsing rules. This is the status quo and leads to bugs (wrong bool
keyword set, missing suffix expansion).

Why not change Option(key) to return (string, bool)?

Alternative: Change the existing Option(key) / Get(key) signature to
return (string, bool) so callers can distinguish absent keys from empty
values.

Rationale for rejection: This is a breaking API change that affects every
caller. Adding GetDefault as a new method achieves the same goal without
breaking existing code. A future major version can consider changing the
return signature.

Why ValueMatch as a struct instead of optional parameters?

Alternative: Use functional options (...Option) or separate methods
(SetOptionFixed, SetOptionRegexp).

Rationale for rejection: A struct is simpler, more explicit, and mirrors
git's own flag combination (--value=<pattern> + --fixed-value). Functional
options add allocation overhead and complexity for what is a fixed set of
modifiers. Separate methods would multiply the API surface (3+ variants per
operation).

What about conditional includes?

This RFC deliberately excludes includeIf because it cannot be resolved
within format/config alone — it requires knowledge of the repository's
working directory, current branch, and remote URLs. A future RFC should
define a RepositoryContext interface that the config layer can accept to
evaluate conditions.

What is the impact of not doing this?
  • Boolean config values continue to be parsed incorrectly (yes, on, no,
    off are silently rejected).
  • Integer suffixes (10M, 1G) cause parse errors on real-world configs.
  • Multi-valued keys cannot be selectively updated or queried — consumers
    must either accept replacing all values or implement custom iteration.
  • URL-scoped config (common for HTTP proxy and SSL settings) must be resolved
    manually by each consumer.
  • The config package's hard-coded struct continues to lose data, require
    double decoding, and misplace domain types. New config sections require
    changes to both the struct and the marshal/unmarshal methods.
  • The Raw escape hatch continues to be the only way to access unsupported
    keys, leading to stale-tree bugs when struct fields and Raw diverge.
Why dissolve the config package instead of improving it?

Alternative: Keep the config package but fix its parsing and add
missing fields.

Rationale for rejection: This is the approach that has been taken so far
and it does not scale. Every new config key requires a struct field, a
marshal method, and an unmarshal method. The struct can never be complete
relative to the real config files — git adds new keys every release and
users and tools define their own. The Raw escape hatch proves the struct
is insufficient. Dissolving the package and using a single data model
eliminates this entire class of problems.

Why put rich types in porcelain packages instead of format/config?

Alternative: Keep RemoteConfig, Branch, etc. in format/config or
a sibling package.

Rationale for rejection: In canonical git, struct remote is defined in
remote.h, not config.h. The config subsystem provides primitives;
domain types are built from those primitives in their own subsystems. This
separation keeps format/config focused on the config format and its
semantics, not on the many higher-level concepts that happen to be
configured via git-config files. It also means format/config has no
dependencies on plumbing types like plumbing.ReferenceName — those belong
to the domain, not the format.

Linguagem predominante
Go
Estrelas
7.9k
Forks
1.1k
Merge médio
4d 19h
PRs com merge (30d)
34

Preparar o ambiente

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de go-git/go-git

Todas as issues de go-git/go-git

Issues semelhantes

Mais issues de Go

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.