commit-wizard 0.0.4

A lightweight CLI assistant for Conventional Commits, semantic versioning, and changelog automation.
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
//! Get, set and unset a single setting by dotted key, validating the value before it is written.

use std::path::{Path, PathBuf};

use toml::Value;

use crate::engine::{
    config::{ConfigFormat, ProjectConfig, StandardConfig},
    error::{ErrorCode, Result},
};

use super::{
    patch::patch_toml,
    show::{ConfigTarget, resolve_config_path},
};

#[derive(Debug, Clone)]
pub struct ConfigGetInput<'a> {
    pub cwd: &'a Path,
    pub target: ConfigTarget,
    pub explicit_path: Option<&'a Path>,
    pub key: &'a str,
}

pub struct ConfigGetOutput {
    pub path: PathBuf,
    pub key: String,
    pub value: Value,
}

#[derive(Debug, Clone)]
pub struct ConfigSetInput<'a> {
    pub cwd: &'a Path,
    pub target: ConfigTarget,
    pub key: &'a str,
    pub value: &'a str,
    pub dry_run: bool,
    pub explicit_path: Option<&'a Path>,
}

pub struct ConfigSetOutput {
    pub path: PathBuf,
    pub key: String,
    pub value: Value,
}

#[derive(Debug, Clone)]
pub struct ConfigUnsetInput<'a> {
    pub cwd: &'a Path,
    pub target: ConfigTarget,
    pub key: &'a str,
    pub dry_run: bool,
    pub explicit_path: Option<&'a Path>,
}

pub struct ConfigUnsetOutput {
    pub path: PathBuf,
    pub key: String,
    pub removed: bool,
}

pub fn config_get(input: &ConfigGetInput<'_>) -> Result<ConfigGetOutput> {
    ensure_supported_key(input.key)?;

    let path = if let Some(explicit_path) = input.explicit_path {
        explicit_path.to_path_buf()
    } else {
        resolve_config_path(input.target, input.cwd)?
    };
    if !path.exists() {
        return Err(ErrorCode::ConfigUnreadable
            .error()
            .with_context("path", path.display().to_string())
            .with_context("reason", "config file does not exist"));
    }

    let raw = std::fs::read_to_string(&path)?;
    let doc = parse_doc(input.target, ConfigFormat::from_path(&path), &raw)?;

    let value = get_value(&doc, input.key).cloned().ok_or_else(|| {
        ErrorCode::ConfigInvalid
            .error()
            .with_context("key", input.key)
            .with_context("reason", "unknown key")
    })?;

    Ok(ConfigGetOutput {
        path,
        key: input.key.to_string(),
        value,
    })
}

pub fn config_set(input: &ConfigSetInput<'_>) -> Result<ConfigSetOutput> {
    ensure_supported_key(input.key)?;

    let path = if let Some(explicit_path) = input.explicit_path {
        explicit_path.to_path_buf()
    } else {
        resolve_config_path(input.target, input.cwd)?
    };
    let format = ConfigFormat::from_path(&path);
    let raw = if path.exists() {
        std::fs::read_to_string(&path)?
    } else {
        default_doc(input.target, format)?
    };

    let mut doc = parse_doc(input.target, format, &raw)?;
    let before = doc.clone();
    let value = parse_value_for_key(input.key, input.value)?;

    set_value(&mut doc, input.key, value.clone())?;
    let validated = validate_doc(input.target, doc)?;
    let rendered = render_for_save(input.target, format, &raw, &before, &validated)?;

    if !input.dry_run {
        if let Some(parent) = path.parent()
            && !parent.as_os_str().is_empty()
        {
            std::fs::create_dir_all(parent)?;
        }
        crate::engine::fs::write_text(&path, &rendered)?;
    }

    Ok(ConfigSetOutput {
        path,
        key: input.key.to_string(),
        value,
    })
}

pub fn config_unset(input: &ConfigUnsetInput<'_>) -> Result<ConfigUnsetOutput> {
    ensure_supported_key(input.key)?;

    let path = if let Some(explicit_path) = input.explicit_path {
        explicit_path.to_path_buf()
    } else {
        resolve_config_path(input.target, input.cwd)?
    };
    if !path.exists() {
        return Err(ErrorCode::ConfigUnreadable
            .error()
            .with_context("path", path.display().to_string())
            .with_context("reason", "config file does not exist"));
    }

    let format = ConfigFormat::from_path(&path);
    let raw = std::fs::read_to_string(&path)?;
    let mut doc = parse_doc(input.target, format, &raw)?;
    let before = doc.clone();
    let removed = unset_value(&mut doc, input.key)?;

    let validated = validate_doc(input.target, doc)?;
    let rendered = render_for_save(input.target, format, &raw, &before, &validated)?;

    if !input.dry_run {
        crate::engine::fs::write_text(&path, &rendered)?;
    }

    Ok(ConfigUnsetOutput {
        path,
        key: input.key.to_string(),
        removed,
    })
}

/// The text to save for `after`, given the file as it was.
///
/// A TOML file is patched in place, so comments, spacing and key order survive
/// and only the changed keys differ. The patch is checked by reading it back:
/// if it does not parse to exactly `after` (it always should), the whole file
/// is re-rendered instead, which is always correct but drops comments. JSON
/// and YAML files are always re-rendered.
fn render_for_save(
    target: ConfigTarget,
    format: ConfigFormat,
    raw: &str,
    before: &Value,
    after: &Value,
) -> Result<String> {
    if format == ConfigFormat::Toml
        && let Ok(patched) = patch_toml(raw, before, after)
        && parse_doc(target, format, &patched).is_ok_and(|reparsed| reparsed == *after)
    {
        return Ok(patched);
    }
    format.render(after)
}

fn ensure_supported_key(key: &str) -> Result<()> {
    if is_supported_key(key) {
        Ok(())
    } else {
        Err(ErrorCode::ConfigInvalid
            .error()
            .with_context("key", key)
            .with_context("reason", "unsupported or unknown key"))
    }
}

fn is_supported_key(key: &str) -> bool {
    matches!(
        key,
        "commit.subject_max_length"
            | "commit.ticket.required"
            | "commit.ticket.pattern"
            | "commit.ticket.header_format"
            | "commit.ticket.source"
            | "branch.remote"
            | "branch.naming.pattern"
            | "branch.naming.require_type"
            | "branch.naming.require_ticket"
            | "release.enabled"
            | "release.source_branch"
            | "release.target_branch"
            | "ai.enabled"
            | "ai.provider"
            | "global.inherit"
            | "changelog.output"
            | "changelog.format"
            | "versioning.tag_prefix"
            | "commit.use_emojis"
            | "commit.scopes.mode"
            | "commit.scopes.restrict_to_defined"
            | "commit.breaking.require_header"
            | "commit.breaking.require_footer"
            | "check.require_conventional"
            | "check.commits.enabled"
            | "check.commits.enforce_on"
            | "push.allow.protected"
            | "push.allow.force"
            | "push.check.commits"
            | "push.check.branch_policy"
    )
}

fn parse_doc(target: ConfigTarget, format: ConfigFormat, raw: &str) -> Result<Value> {
    match target {
        ConfigTarget::Project => {
            let parsed = ProjectConfig::from_str_as(format, raw)?;
            toml::Value::try_from(parsed).map_err(|err| {
                ErrorCode::SerializationFailure
                    .error()
                    .with_context("error", err.to_string())
            })
        }
        ConfigTarget::Global => {
            let parsed = StandardConfig::from_str_as(format, raw)?;
            toml::Value::try_from(parsed).map_err(|err| {
                ErrorCode::SerializationFailure
                    .error()
                    .with_context("error", err.to_string())
            })
        }
    }
}

fn validate_doc(target: ConfigTarget, value: Value) -> Result<Value> {
    match target {
        ConfigTarget::Project => {
            let parsed: ProjectConfig = value.clone().try_into().map_err(|err| {
                ErrorCode::ConfigInvalid
                    .error()
                    .with_context("error", err.to_string())
            })?;
            toml::Value::try_from(parsed).map_err(|err| {
                ErrorCode::SerializationFailure
                    .error()
                    .with_context("error", err.to_string())
            })
        }
        ConfigTarget::Global => {
            let parsed: StandardConfig = value.clone().try_into().map_err(|err| {
                ErrorCode::ConfigInvalid
                    .error()
                    .with_context("error", err.to_string())
            })?;
            toml::Value::try_from(parsed).map_err(|err| {
                ErrorCode::SerializationFailure
                    .error()
                    .with_context("error", err.to_string())
            })
        }
    }
}

fn default_doc(target: ConfigTarget, format: ConfigFormat) -> Result<String> {
    match target {
        ConfigTarget::Project => format.render(&ProjectConfig::minimal()),
        ConfigTarget::Global => format.render(&StandardConfig::minimal()),
    }
}

fn get_value<'a>(root: &'a Value, key: &str) -> Option<&'a Value> {
    let mut current = root;
    for segment in key.split('.') {
        current = current.get(segment)?;
    }
    Some(current)
}

fn set_value(root: &mut Value, key: &str, value: Value) -> Result<()> {
    let mut current = root;
    let mut segments = key.split('.').peekable();

    while let Some(segment) = segments.next() {
        let is_last = segments.peek().is_none();

        if is_last {
            let table = current.as_table_mut().ok_or_else(|| {
                ErrorCode::ConfigInvalid
                    .error()
                    .with_context("key", key)
                    .with_context("reason", "target parent is not a table")
            })?;
            table.insert(segment.to_string(), value);
            return Ok(());
        }

        let table = current.as_table_mut().ok_or_else(|| {
            ErrorCode::ConfigInvalid
                .error()
                .with_context("key", key)
                .with_context("reason", "intermediate path is not a table")
        })?;

        current = table
            .entry(segment.to_string())
            .or_insert_with(|| Value::Table(Default::default()));
    }

    Err(ErrorCode::ConfigInvalid.error().with_context("key", key))
}

fn unset_value(root: &mut Value, key: &str) -> Result<bool> {
    let mut current = root;
    let mut segments = key.split('.').peekable();

    while let Some(segment) = segments.next() {
        let is_last = segments.peek().is_none();

        if is_last {
            let table = current.as_table_mut().ok_or_else(|| {
                ErrorCode::ConfigInvalid
                    .error()
                    .with_context("key", key)
                    .with_context("reason", "target parent is not a table")
            })?;
            return Ok(table.remove(segment).is_some());
        }

        current = match current.get_mut(segment) {
            Some(next) => next,
            None => return Ok(false),
        };
    }

    Ok(false)
}

fn parse_value_for_key(key: &str, raw: &str) -> Result<Value> {
    match key {
        "commit.subject_max_length" => raw.parse::<i64>().map(Value::Integer).map_err(|_| {
            ErrorCode::ConfigInvalid
                .error()
                .with_context("key", key)
                .with_context("value", raw)
                .with_context("reason", "expected integer")
        }),
        "commit.ticket.required"
        | "release.enabled"
        | "ai.enabled"
        | "global.inherit"
        | "commit.use_emojis"
        | "commit.scopes.restrict_to_defined"
        | "commit.breaking.require_header"
        | "commit.breaking.require_footer"
        | "check.require_conventional"
        | "check.commits.enabled"
        | "push.allow.protected"
        | "push.allow.force"
        | "push.check.commits"
        | "push.check.branch_policy"
        | "branch.naming.require_type"
        | "branch.naming.require_ticket" => raw.parse::<bool>().map(Value::Boolean).map_err(|_| {
            ErrorCode::ConfigInvalid
                .error()
                .with_context("key", key)
                .with_context("value", raw)
                .with_context("reason", "expected boolean")
        }),
        "branch.remote"
        | "branch.naming.pattern"
        | "commit.ticket.pattern"
        | "commit.ticket.header_format"
        | "commit.ticket.source"
        | "release.source_branch"
        | "release.target_branch"
        | "ai.provider"
        | "changelog.output"
        | "changelog.format"
        | "commit.scopes.mode"
        | "check.commits.enforce_on"
        | "versioning.tag_prefix" => Ok(Value::String(raw.to_string())),
        _ => Err(ErrorCode::ConfigInvalid
            .error()
            .with_context("key", key)
            .with_context("reason", "unsupported or unknown key")),
    }
}