commitbee 0.6.0

AI-powered commit message generator using tree-sitter semantic analysis and local LLMs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
// SPDX-FileCopyrightText: 2026 Sephyi <me@sephy.io>
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial

use directories::ProjectDirs;
use figment::Figment;
use figment::providers::{Env, Format, Serialized, Toml};
use secrecy::SecretString;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
use tracing::warn;

use crate::cli::Cli;
use crate::error::{Error, Result};

/// Commit message format configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommitFormat {
    /// Include body in commit message (default: true)
    #[serde(default = "default_true")]
    pub include_body: bool,

    /// Include scope in commit type, e.g., feat(scope): (default: true)
    #[serde(default = "default_true")]
    pub include_scope: bool,

    /// Enforce lowercase first character of subject (default: true)
    #[serde(default = "default_true")]
    pub lowercase_subject: bool,
}

impl Default for CommitFormat {
    fn default() -> Self {
        Self {
            include_body: true,
            include_scope: true,
            lowercase_subject: true,
        }
    }
}

fn default_true() -> bool {
    true
}

#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
#[serde(rename_all = "lowercase")]
pub enum Provider {
    #[default]
    Ollama,
    OpenAI,
    Anthropic,
}

impl std::fmt::Display for Provider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Ollama => write!(f, "ollama"),
            Self::OpenAI => write!(f, "openai"),
            Self::Anthropic => write!(f, "anthropic"),
        }
    }
}

#[derive(Clone, Serialize, Deserialize)]
pub struct Config {
    #[serde(default)]
    pub provider: Provider,

    #[serde(default = "default_model")]
    pub model: String,

    #[serde(default = "default_ollama_host")]
    pub ollama_host: String,

    #[serde(default, skip_serializing)]
    pub api_key: Option<SecretString>,

    #[serde(default = "default_max_diff_lines")]
    pub max_diff_lines: usize,

    #[serde(default = "default_max_file_lines")]
    pub max_file_lines: usize,

    /// Maximum context characters for LLM prompt (~4 chars per token)
    /// Default 24000 is safe for 8K context models
    #[serde(default = "default_max_context_chars")]
    pub max_context_chars: usize,

    /// Request timeout in seconds (default 300)
    #[serde(default = "default_timeout_secs")]
    pub timeout_secs: u64,

    /// LLM temperature (0.0-1.0, default 0.3)
    #[serde(default = "default_temperature")]
    pub temperature: f32,

    /// Maximum tokens to generate (default 256)
    #[serde(default = "default_num_predict")]
    pub num_predict: u32,

    /// Enable thinking/reasoning for Ollama models that support it (default: false)
    /// When enabled, thinking tokens are separated from the response.
    /// Requires higher num_predict (8192+) to accommodate thinking tokens.
    #[serde(default)]
    pub think: bool,

    /// Base URL for OpenAI-compatible APIs (default: https://api.openai.com/v1)
    #[serde(default)]
    pub openai_base_url: Option<String>,

    /// Base URL for Anthropic API (default: https://api.anthropic.com/v1)
    #[serde(default)]
    pub anthropic_base_url: Option<String>,

    /// Rename detection similarity threshold (0-100, default 70)
    /// Set to 0 to disable rename detection.
    #[serde(default = "default_rename_threshold")]
    pub rename_threshold: u8,

    /// Additional custom secret patterns (regex strings)
    #[serde(default)]
    pub custom_secret_patterns: Vec<String>,

    /// Built-in secret pattern names to disable
    #[serde(default)]
    pub disabled_secret_patterns: Vec<String>,

    /// Language for commit message generation (ISO 639-1 code, e.g., "de", "ja", "fr")
    /// When set, the LLM is instructed to write in this language.
    /// Type/scope remain in English per Conventional Commits spec.
    #[serde(default)]
    pub locale: Option<String>,

    /// Enable experimental commit history style learning (default: false)
    /// Analyzes recent commits to learn scope naming, type patterns, and
    /// subject phrasing conventions for the repository.
    #[serde(default)]
    pub learn_from_history: bool,

    /// Number of recent commits to sample for style learning (default: 50)
    #[serde(default = "default_history_sample_size")]
    pub history_sample_size: usize,

    /// Glob patterns for files to exclude from analysis and diff context
    /// Excluded files are listed in output but not sent to the LLM.
    #[serde(default)]
    pub exclude_patterns: Vec<String>,

    /// Path to custom system prompt file (overrides built-in SYSTEM_PROMPT)
    #[serde(default)]
    pub system_prompt_path: Option<PathBuf>,

    /// Path to custom user prompt template file
    #[serde(default)]
    pub template_path: Option<PathBuf>,

    /// Commit message format options
    #[serde(default)]
    pub format: CommitFormat,
}

fn default_max_context_chars() -> usize {
    24_000
}

fn default_model() -> String {
    "qwen3.5:4b".into()
}
fn default_ollama_host() -> String {
    "http://localhost:11434".into()
}
fn default_max_diff_lines() -> usize {
    500
}
fn default_max_file_lines() -> usize {
    100
}
fn default_timeout_secs() -> u64 {
    300
}
fn default_temperature() -> f32 {
    0.3
}
fn default_num_predict() -> u32 {
    256
}
fn default_rename_threshold() -> u8 {
    70
}
fn default_history_sample_size() -> usize {
    50
}

impl Default for Config {
    fn default() -> Self {
        Self {
            provider: Provider::default(),
            model: default_model(),
            ollama_host: default_ollama_host(),
            api_key: None,
            max_diff_lines: default_max_diff_lines(),
            max_file_lines: default_max_file_lines(),
            max_context_chars: default_max_context_chars(),
            timeout_secs: default_timeout_secs(),
            temperature: default_temperature(),
            num_predict: default_num_predict(),
            think: false,
            openai_base_url: None,
            anthropic_base_url: None,
            rename_threshold: default_rename_threshold(),
            custom_secret_patterns: Vec::new(),
            disabled_secret_patterns: Vec::new(),
            locale: None,
            learn_from_history: false,
            history_sample_size: default_history_sample_size(),
            exclude_patterns: Vec::new(),
            system_prompt_path: None,
            template_path: None,
            format: CommitFormat::default(),
        }
    }
}

impl std::fmt::Debug for Config {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Config")
            .field("provider", &self.provider)
            .field("model", &self.model)
            .field("ollama_host", &self.ollama_host)
            .field("api_key", &self.api_key.as_ref().map(|_| "[REDACTED]"))
            .field("max_diff_lines", &self.max_diff_lines)
            .field("max_file_lines", &self.max_file_lines)
            .field("max_context_chars", &self.max_context_chars)
            .field("timeout_secs", &self.timeout_secs)
            .field("temperature", &self.temperature)
            .field("num_predict", &self.num_predict)
            .field("think", &self.think)
            .field("openai_base_url", &self.openai_base_url)
            .field("anthropic_base_url", &self.anthropic_base_url)
            .field("rename_threshold", &self.rename_threshold)
            .field("custom_secret_patterns", &self.custom_secret_patterns)
            .field("disabled_secret_patterns", &self.disabled_secret_patterns)
            .field("locale", &self.locale)
            .field("learn_from_history", &self.learn_from_history)
            .field("history_sample_size", &self.history_sample_size)
            .field("exclude_patterns", &self.exclude_patterns)
            .field("system_prompt_path", &self.system_prompt_path)
            .field("template_path", &self.template_path)
            .field("format", &self.format)
            .finish()
    }
}

impl Config {
    /// Load with priority: CLI > ENV > user config > project config > defaults
    pub fn load(cli: &Cli) -> Result<Self> {
        let mut figment = Figment::new().merge(Serialized::defaults(Config::default()));

        // Project-level config (.commitbee.toml in repo root)
        // Security: project config can override settings but should not
        // be able to set api_key or redirect cloud provider base URLs.
        let mut has_project_config = false;
        if let Ok(cwd) = std::env::current_dir() {
            let project_config = cwd.join(".commitbee.toml");
            if project_config.exists() {
                has_project_config = true;
                figment = figment.merge(Toml::file(&project_config));
            }
        }

        // User-level config
        if let Some(path) = Self::config_path()
            && path.exists()
        {
            figment = figment.merge(Toml::file(&path));
        }

        // Environment variables (COMMITBEE_MODEL, COMMITBEE_PROVIDER, etc.)
        // Use __ separator for nested keys (e.g., COMMITBEE_FORMAT__INCLUDE_BODY)
        figment = figment.merge(Env::prefixed("COMMITBEE_").split("__"));

        let mut config: Config = figment
            .extract()
            .map_err(|e| Error::Config(e.to_string()))?;

        // Security: warn if project-level config overrides security-sensitive fields
        if has_project_config
            && let Ok(cwd) = std::env::current_dir()
            && let Ok(content) = fs::read_to_string(cwd.join(".commitbee.toml"))
            && let Ok(table) = content.parse::<toml::Table>()
        {
            if table.contains_key("api_key") {
                warn!("project .commitbee.toml sets api_key — ignoring for security");
                config.api_key = None;
            }
            if table.contains_key("openai_base_url") {
                warn!("project .commitbee.toml sets openai_base_url — blocked for security");
                config.openai_base_url = None;
            }
            if table.contains_key("anthropic_base_url") {
                warn!("project .commitbee.toml sets anthropic_base_url — blocked for security");
                config.anthropic_base_url = None;
            }
            if table.contains_key("ollama_host") {
                warn!("project .commitbee.toml sets ollama_host — blocked for security");
                config.ollama_host = Config::default().ollama_host;
            }
        }

        // CLI overrides (highest priority — must run before API key resolution
        // so that --provider is applied before keyring/env var lookup)
        config.apply_cli(cli)?;

        // Provider-specific API key fallback (after CLI overrides set the provider)
        if config.api_key.is_none() {
            config.api_key = match config.provider {
                Provider::OpenAI => std::env::var("OPENAI_API_KEY").ok().map(SecretString::from),
                Provider::Anthropic => std::env::var("ANTHROPIC_API_KEY")
                    .ok()
                    .map(SecretString::from),
                Provider::Ollama => None,
            };
        }

        // Keyring fallback (if still no key and secure-storage feature is enabled)
        #[cfg(feature = "secure-storage")]
        if config.api_key.is_none() && config.provider != Provider::Ollama {
            let provider_name = config.provider.to_string();
            if let Ok(entry) = keyring::Entry::new("commitbee", &provider_name)
                && let Ok(key) = entry.get_password()
            {
                config.api_key = Some(SecretString::from(key));
            }
        }

        config.validate(&cli.command)?;
        Ok(config)
    }

    pub fn config_dir() -> Option<PathBuf> {
        ProjectDirs::from("", "", "commitbee").map(|dirs| dirs.config_dir().to_path_buf())
    }

    pub fn config_path() -> Option<PathBuf> {
        Self::config_dir().map(|d| d.join("config.toml"))
    }

    fn apply_cli(&mut self, cli: &Cli) -> Result<()> {
        if let Some(ref p) = cli.provider {
            self.provider = match p.to_lowercase().as_str() {
                "ollama" => Provider::Ollama,
                "openai" => Provider::OpenAI,
                "anthropic" => Provider::Anthropic,
                other => {
                    return Err(Error::Config(format!(
                        "Unknown provider '{}'. Valid options: ollama, openai, anthropic",
                        other
                    )));
                }
            };
        }
        if let Some(ref m) = cli.model {
            self.model = m.clone();
        }
        if cli.no_scope {
            self.format.include_scope = false;
        }
        if let Some(ref l) = cli.locale {
            self.locale = Some(l.clone());
        }
        if !cli.exclude.is_empty() {
            self.exclude_patterns.extend(cli.exclude.iter().cloned());
        }
        Ok(())
    }

    /// Check if the API key is required for the current command.
    /// Subcommands that don't invoke the LLM don't need a key.
    fn requires_api_key(command: &Option<crate::cli::Commands>) -> bool {
        match command {
            None => true, // Default command (generate commit) needs a key
            Some(cmd) => matches!(cmd, crate::cli::Commands::Doctor),
            // Init, Config, Completions, Hook, SetKey, GetKey, Eval — don't need a key
        }
    }

    fn validate(&self, command: &Option<crate::cli::Commands>) -> Result<()> {
        if Self::requires_api_key(command)
            && self.provider != Provider::Ollama
            && self.api_key.is_none()
        {
            return Err(Error::Config(format!(
                "{} requires an API key. Set COMMITBEE_API_KEY, {}_API_KEY, or store securely with: commitbee config set-key {}",
                self.provider,
                format!("{:?}", self.provider).to_uppercase(),
                format!("{:?}", self.provider).to_lowercase()
            )));
        }

        if !(10..=10_000).contains(&self.max_diff_lines) {
            return Err(Error::Config(format!(
                "max_diff_lines must be 10–10000, got {}",
                self.max_diff_lines
            )));
        }

        if !(10..=1_000).contains(&self.max_file_lines) {
            return Err(Error::Config(format!(
                "max_file_lines must be 10–1000, got {}",
                self.max_file_lines
            )));
        }

        if !(1_000..=200_000).contains(&self.max_context_chars) {
            return Err(Error::Config(format!(
                "max_context_chars must be 1000–200000, got {}",
                self.max_context_chars
            )));
        }

        if !(1..=3600).contains(&self.timeout_secs) {
            return Err(Error::Config(format!(
                "timeout_secs must be 1–3600, got {}",
                self.timeout_secs
            )));
        }

        if !(0.0..=2.0).contains(&self.temperature) {
            return Err(Error::Config(format!(
                "temperature must be 0.0–1.0, got {}",
                self.temperature
            )));
        }

        if self.rename_threshold > 100 {
            return Err(Error::Config(format!(
                "rename_threshold must be 0–100, got {}",
                self.rename_threshold
            )));
        }

        if self.ollama_host.is_empty() {
            return Err(Error::Config("ollama_host cannot be empty".into()));
        }

        if !self.ollama_host.starts_with("http://") && !self.ollama_host.starts_with("https://") {
            return Err(Error::Config(format!(
                "ollama_host must start with http:// or https://, got '{}'",
                self.ollama_host
            )));
        }

        // Validate cloud provider base URLs
        if let Some(ref url) = self.openai_base_url
            && !url.starts_with("http://")
            && !url.starts_with("https://")
        {
            return Err(Error::Config(format!(
                "openai_base_url must start with http:// or https://, got '{}'",
                url
            )));
        }
        if let Some(ref url) = self.anthropic_base_url
            && !url.starts_with("http://")
            && !url.starts_with("https://")
        {
            return Err(Error::Config(format!(
                "anthropic_base_url must start with http:// or https://, got '{}'",
                url
            )));
        }

        Ok(())
    }

    /// Create default config file with secure permissions
    pub fn create_default() -> Result<PathBuf> {
        let Some(dir) = Self::config_dir() else {
            return Err(Error::Config("Cannot determine config directory".into()));
        };

        fs::create_dir_all(&dir)?;

        let path = dir.join("config.toml");
        let content = Self::generate_default_config();

        fs::write(&path, &content)?;

        // Set secure permissions (0600)
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = fs::metadata(&path)?.permissions();
            perms.set_mode(0o600);
            fs::set_permissions(&path, perms)?;
        }

        Ok(path)
    }

    /// Generate the default config TOML string with descriptive comments.
    ///
    /// Values are pulled from `Config::default()` so the template never
    /// drifts from the struct defaults. Comments are maintained alongside
    /// field descriptors in a single list.
    pub fn generate_default_config() -> String {
        let default = Config::default();
        let table: toml::Table = {
            let s = toml::to_string(&default).expect("Config serializes to TOML");
            toml::from_str(&s).expect("round-trips as TOML table")
        };

        /// Whether to show the field commented-out (advanced/optional settings)
        /// or active (core settings the user should see immediately).
        #[derive(Clone, Copy)]
        enum Show {
            Active,
            CommentedOut,
        }

        struct Field {
            key: &'static str,
            comment: &'static str,
            show: Show,
            /// Override value for Option/Vec fields that serialize to nothing
            example: Option<&'static str>,
        }

        let fields: &[Field] = &[
            Field {
                key: "provider",
                comment: "LLM provider: ollama, openai, anthropic",
                show: Show::Active,
                example: None,
            },
            Field {
                key: "model",
                comment: "Model name (for Ollama, use `ollama list` to see available)",
                show: Show::Active,
                example: None,
            },
            Field {
                key: "ollama_host",
                comment: "Ollama server URL",
                show: Show::Active,
                example: None,
            },
            Field {
                key: "max_diff_lines",
                comment: "Maximum lines of diff to include in prompt",
                show: Show::Active,
                example: None,
            },
            Field {
                key: "max_file_lines",
                comment: "Maximum lines per file in diff",
                show: Show::Active,
                example: None,
            },
            Field {
                key: "num_predict",
                comment: "Maximum tokens to generate\n\
                          Increase to 8192+ if using thinking models with think = true",
                show: Show::CommentedOut,
                example: None,
            },
            Field {
                key: "think",
                comment: "Enable thinking/reasoning for Ollama models\n\
                          When enabled, models like qwen3 will reason before responding.\n\
                          Requires higher num_predict (8192+) to accommodate thinking tokens.",
                show: Show::CommentedOut,
                example: None,
            },
            Field {
                key: "max_context_chars",
                comment: "Maximum context characters for LLM prompt (~4 chars per token)\n\
                          Increase for larger models (e.g., 48000 for 16K context)",
                show: Show::CommentedOut,
                example: None,
            },
            Field {
                key: "timeout_secs",
                comment: "Request timeout in seconds",
                show: Show::CommentedOut,
                example: None,
            },
            Field {
                key: "temperature",
                comment: "LLM temperature (0.0-1.0, default 0.3)",
                show: Show::CommentedOut,
                example: None,
            },
            Field {
                key: "rename_threshold",
                comment: "Rename detection similarity threshold (0-100)\n\
                          Set to 0 to disable rename detection",
                show: Show::CommentedOut,
                example: None,
            },
            Field {
                key: "locale",
                comment: "Language for commit message generation (ISO 639-1 code)\n\
                          Type and scope remain in English per Conventional Commits spec.",
                show: Show::CommentedOut,
                example: Some("\"de\""),
            },
            Field {
                key: "custom_secret_patterns",
                comment: "Custom secret patterns (additional regex patterns for secret scanning)",
                show: Show::CommentedOut,
                example: Some("[\"CUSTOM_KEY_[a-zA-Z0-9]{32}\"]"),
            },
            Field {
                key: "disabled_secret_patterns",
                comment: "Disable built-in secret patterns by name",
                show: Show::CommentedOut,
                example: Some("[\"Generic Secret (unquoted)\"]"),
            },
            Field {
                key: "learn_from_history",
                comment: "Experimental: learn commit style from repository history\n\
                          Analyzes recent commits to learn scope naming, type patterns, and\n\
                          subject phrasing conventions for the repository.",
                show: Show::CommentedOut,
                example: None,
            },
            Field {
                key: "history_sample_size",
                comment: "Number of recent commits to sample for style learning",
                show: Show::CommentedOut,
                example: None,
            },
            Field {
                key: "exclude_patterns",
                comment: "Exclude files matching glob patterns from analysis and diff context\n\
                          Excluded files are listed in output but not sent to the LLM.",
                show: Show::CommentedOut,
                example: Some("[\"*.lock\", \"**/*.generated.*\"]"),
            },
            Field {
                key: "openai_base_url",
                comment: "Base URL for OpenAI-compatible APIs",
                show: Show::CommentedOut,
                example: Some("\"https://api.openai.com/v1\""),
            },
            Field {
                key: "anthropic_base_url",
                comment: "Base URL for Anthropic API",
                show: Show::CommentedOut,
                example: Some("\"https://api.anthropic.com/v1\""),
            },
            Field {
                key: "system_prompt_path",
                comment: "Custom system prompt file (overrides built-in prompt)",
                show: Show::CommentedOut,
                example: Some("\"/path/to/system_prompt.txt\""),
            },
            Field {
                key: "template_path",
                comment: "Custom user prompt template file\n\
                          Supports {{diff}}, {{symbols}}, {{files}} variables",
                show: Show::CommentedOut,
                example: Some("\"/path/to/template.txt\""),
            },
        ];

        let format_fields: &[(&str, &str)] = &[
            ("include_body", "Include body/description in commit message"),
            (
                "include_scope",
                "Include scope in commit type, e.g., feat(scope): subject",
            ),
            (
                "lowercase_subject",
                "Enforce lowercase first character of subject (conventional commits best practice)",
            ),
        ];

        let mut out = String::from("# CommitBee Configuration\n");

        for field in fields {
            out.push('\n');
            for line in field.comment.lines() {
                out.push_str("# ");
                out.push_str(line);
                out.push('\n');
            }

            // Resolve the display value: serialized default, or example for Option/Vec fields
            let val_str = if let Some(v) = table.get(field.key) {
                // f32 round-trips through f64 in TOML and gains precision noise;
                // format from the struct directly for float fields
                if v.is_float() {
                    format!("{} = {}", field.key, default.temperature)
                } else {
                    format!("{} = {v}", field.key)
                }
            } else if let Some(ex) = field.example {
                format!("{} = {ex}", field.key)
            } else {
                continue;
            };

            if matches!(field.show, Show::CommentedOut) {
                out.push_str("# ");
            }
            out.push_str(&val_str);
            out.push('\n');
        }

        // [format] section
        out.push_str("\n# Commit message format options\n[format]\n");
        if let Some(toml::Value::Table(fmt)) = table.get("format") {
            for (key, comment) in format_fields {
                if let Some(v) = fmt.get(*key) {
                    out.push_str(&format!("# {comment}\n{key} = {v}\n"));
                }
            }
        }

        out
    }
}