Skip to content

feat(options): template expressions in segment options#7455

Open
MO2k4 wants to merge 14 commits into
JanDeDobbeleer:mainfrom
MO2k4:worktree-template-aware-options
Open

feat(options): template expressions in segment options#7455
MO2k4 wants to merge 14 commits into
JanDeDobbeleer:mainfrom
MO2k4:worktree-template-aware-options

Conversation

@MO2k4
Copy link
Copy Markdown
Contributor

@MO2k4 MO2k4 commented Apr 10, 2026

Summary

  • Segment options (Int, Float64, Bool, Color) now accept Go template expressions as string values, resolved at render time using the segment writer as context
  • Users can compute option values dynamically — e.g. max_width = '{{ sub .TerminalWidth 30 }}' to size a path based on terminal width
  • The path segment's getMaxWidth drops ~20 lines of manual template handling in favor of the new template-aware Int() accessor
  • JSON schema updated so max_depth and mixed_threshold accept string alongside integer
  • Docs added for template expressions in segment options

How it works

After Init, the segment writer is stored as a template context in the options map. When a typed accessor finds a string value with {{ }}, it resolves the template before parsing. If resolution or parsing fails, the default value is used.

Test plan

  • go test ./segments/options/ — template resolution tests for Int, Float64, Bool, Color
  • go test ./segments/ -run TestGetMaxWidth — path segment uses template-aware Int() correctly
  • Existing option accessor tests stay green (no regressions in non-template code paths)

Closes #7243

Copy link
Copy Markdown
Owner

@JanDeDobbeleer JanDeDobbeleer left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ignore this one

@JanDeDobbeleer JanDeDobbeleer dismissed their stale review April 29, 2026 05:54

Resubmitting with corrected formatting

Copy link
Copy Markdown
Owner

@JanDeDobbeleer JanDeDobbeleer left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Three issues to address before merging:


1. 🔴 The .TerminalWidth example in the docs won't work

The example in the new "Template Expressions in Options" section uses:

max_width = '{{ sub .TerminalWidth 30 }}'

and the prose below it says "segment-specific fields (like .TerminalWidth on the path segment) are available."

Neither is accurate. .TerminalWidth is not a field on Path (or any segment writer). TerminalWidth() is a method on runtime.Environment, stored in the unexported env field of Base — not reachable from a template. The global template cache (cache.Template) also has no terminal-width value. At runtime this template silently fails and max_width falls back to 0.

Working alternatives:

  • {{ .Env.COLUMNS }} — if the shell exports it (not guaranteed cross-platform)
  • Add a TerminalWidth() int getter to Path that delegates to pt.env.TerminalWidth()

2. 🟡 Sentinel key pollutes the user-facing options map

Storing the runtime context inside options.Map via "__template_context__" mixes internal state with user options. Consequences:

  • m.Any("__template_context__", nil) returns the live writer — any code that iterates all options (debug logging, serialisation, future tooling) will encounter it unexpectedly.
  • It creates a reference cycle: Map → writer → Map (safe today because gob encoding happens before MapSegmentWithWriter, but fragile if that order ever changes).

A cleaner approach: wrap Map in a small struct with a separate ctx any field, keeping user options and runtime state cleanly separated.


3. 🟡 SetContext is absent from the Provider interface

SetContext only exists on the concrete Map type. Any mock Provider in tests silently never gets template resolution, and segment code that holds a Provider variable can't call SetContext without a type assertion. If template-aware options are a first-class feature, SetContext(ctx any) should be added to the Provider interface so all implementations are required to handle it.

@MO2k4
Copy link
Copy Markdown
Contributor Author

MO2k4 commented Apr 30, 2026

Thanks for the detailed review. Before I start, I want to flag the blast radius of the "clean" fix for #2 so we can agree on scope.

Issue 2 — wrap Map in a struct with a separate ctx field

Today Map is type Map map[Option]any. Moving to type Map struct { data map[Option]any; ctx any } is a breaking type change: every options.Map{Foo: x} literal stops compiling, and SetContext has to become a pointer-receiver method, so Segment.Options / Segment.Properties move to *options.Map.

Ripple count from a quick grep:

  • ~190 options.Map{...} literals across ~73 files (mostly src/config/default.go and src/segments/*_test.go)
  • TOML decoder has to switch to toml.NewDecoder(...).EnableUnmarshalerInterface().Decode(&cfg) so UnmarshalTOML is invoked
  • len(segment.Options) call sites need a new Len() accessor
  • All accessor methods (Int, String, Bool, …) move to pointer receivers

It's a single mechanical commit, but it's a big one.

Slimmer alternative

If the goal is just to stop the sentinel key leaking into serialised output, we can keep Map as a map alias and add MarshalJSON / MarshalYAML / MarshalTOML methods that filter keys starting with __. That's ~1 file for #2, plus the obvious fixes for #1
(Path.TerminalWidth()) and #3 (SetContext on the Provider interface — already implemented by Map, just needs the interface line). Total: ~5 files instead of ~73.

The map-alias approach keeps the sentinel mechanism internally — slightly less elegant — but addresses the user-visible concern (no leak into JSON/YAML/TOML) and the reference cycle stays contained inside the package.

Question

Which do you prefer?

  1. Full struct refactor (~73 files, cleanest separation, no sentinel)
  2. Marshaler-filter approach (~5 files, sentinel stays as an implementation detail)

Happy to go either way, just want to make sure the bigger one is what you actually want before I touch every test fixture in the repo.

@JanDeDobbeleer
Copy link
Copy Markdown
Owner

@MO2k4 ignore the second bullet, however, I want to make sure it doesn't export when the user uses oh-my-posh config export (did not validate this). The problem with it being stored this way is that it's 100% internal and runtime relevant only, which should stay that way. I don't have a clean solution top of mind either.

MO2k4 added 8 commits May 4, 2026 10:56
Add SetContext/getContext for storing template context on options.Map
via a sentinel key. Add resolveTemplate helper that checks for {{
syntax and resolves via template.Render before type conversion.
…ccessors

Each typed accessor now checks for string values containing {{ template
syntax and resolves them via template.Render before type conversion.
On failure, the default value is returned.
…check

- Extract setupTemplateTestEnv() to deduplicate mock environment setup
  repeated across 6 test functions (~100 lines removed)
- Remove redundant strings.Contains check in Color() since
  resolveTemplate() already performs that check
@MO2k4 MO2k4 force-pushed the worktree-template-aware-options branch from bf8bd4e to 5df92b3 Compare May 4, 2026 08:56
@MO2k4
Copy link
Copy Markdown
Contributor Author

MO2k4 commented May 4, 2026

@JanDeDobbeleer Pushed fixes for the three review items:

  1. .TerminalWidth on the path segment
  • Added Path.TerminalWidth() so the docs example (max_width = '{{ sub .TerminalWidth 30 }}') actually resolves. Returns 0 on TTY error.
  • Extended TestGetMaxWidth with an end-to-end case that resolves through the template-aware Int accessor.
  • Documented the field on the path segment's properties table and clarified the template-context mechanism in segment.mdx.
  1. Sentinel key leaking via serialization
  • Exported the constant as options.TemplateContextKey so the config package can reference it directly.
  • Added Config.stripRuntimeState() and call it at the top of Export and Base64, so JSON/YAML/TOML/gob can never emit template_context regardless of caller ordering.
  • Added a lockdown test in src/config/backup_test.go that calls MapSegmentWithWriter (which injects the sentinel), then asserts the sentinel is absent from all four export formats and from the in-memory map after each export. Also smoke-tested with oh-my-posh config export against a config using template-aware options — grep -c template_context returns 0 for json/yaml/toml.
  1. SetContext on Provider
  • Added SetContext(ctx any) to the interface and var _ Provider = Map{} as a compile-time check.

I've also run some local testing to see if there was a leak of the ctx, but it never was leaked. 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Ability to use templating on segment options

2 participants