git_policy_cli/config_parse.rs
1//! What:
2//! Turn `cli-git.config.jsonc` text into validated typed settings.
3//! Why:
4//! Every unknown key,
5//! wrong type or ambiguous duplicate is rejected before any
6//! policy or transaction reads a setting.
7//!
8//! In TS you'd write (pseudocode):
9//! ```ts
10//! // parseConfig(source) returns CliGitConfig or throws ConfigError naming the key.
11//! ```
12
13/// What:
14/// `use super::...` imports sibling modules of this crate.
15/// Why:
16/// Parsing combines the error type,
17/// the policy section reader,
18/// the typed
19/// settings and the shared value readers.
20///
21/// In TS you'd write (pseudocode):
22/// ```ts
23/// import { ConfigError } from './config-error.ts';
24/// ```
25use super::config_error::ConfigError;
26use super::config_policies::parse_policies;
27use super::config_schema::{CliGitConfig, ConcurrencyConfig};
28use super::config_values::{boolean, member_keys, member_path, safe_integer, wrong_kind};
29/// What:
30/// Import the repository's JSONC parser and its value type.
31/// Why:
32/// cli-git reads its configuration through the shared JSONC package only.
33///
34/// In TS you'd write (pseudocode):
35/// ```ts
36/// import { parseJsonc, type JsoncValue } from 'jsonc-edit';
37/// ```
38use monochromatic_jsonc_edit::{JsoncValue, parse_jsonc};
39
40/// What:
41/// Every accepted top-level key,
42/// for the unknown-key diagnostic.
43/// `&str` is borrowed text compiled into the executable (sibling:
44/// owned `String`).
45/// Why:
46/// One list keeps the message and the dispatch from drifting apart.
47///
48/// In TS you'd write (pseudocode):
49/// ```ts
50/// const ACCEPTED_KEYS = 'policies, hooks, indexLock, landing';
51/// ```
52const ACCEPTED_KEYS: &str = "policies, hooks, indexLock, landing";
53
54/// What:
55/// Explain a top-level key the schema does not accept.
56/// Why:
57/// `plugins` and `trust` existed in the executable TypeScript configuration;
58/// their
59/// authors need the reason and the remedy,
60/// not a bare "unknown key".
61///
62/// In TS you'd write (pseudocode):
63/// ```ts
64/// function unknownTopLevelKey(key: string): ConfigError;
65/// ```
66fn unknown_top_level_key(key: &str) -> ConfigError {
67 if key == "plugins" {
68 return ConfigError::new(
69 "Configuration key plugins is retired: policies are compiled into cli-git and \
70 JSONC configuration cannot load plugin code. Remove the key and configure the \
71 shipped policies under policies.",
72 );
73 }
74 if key == "postCommit" {
75 return ConfigError::new(
76 "Configuration key postCommit is not supported: cli-git runs no program named by any configuration, so \
77 there is nothing to declare under it. Remove the key. A check that must run on every commit belongs in \
78 a cli-git policy under policies.",
79 );
80 }
81 if key == "trust" {
82 return ConfigError::new(
83 "Configuration key trust is retired: JSONC configuration is data and needs no \
84 code-execution approval. Remove the key.",
85 );
86 }
87 // What: `format!` builds owned text; `.as_str()` lends it to the constructor.
88 // Why: The message names the offending key and every accepted one.
89 //
90 // In TS you'd write (pseudocode):
91 // ```ts
92 // return new ConfigError(`Unknown configuration key: ${key}. Accepted keys: ...`);
93 // ```
94 return ConfigError::new(
95 format!("Unknown configuration key: {key}. Accepted keys: {ACCEPTED_KEYS}.").as_str(),
96 );
97}
98
99/// What:
100/// Validate one concurrency section and apply its single optional key.
101/// `Result<T, E>` is "value or error":
102/// `Ok(...)` or `Err(...)`.
103/// Why:
104/// `hooks`,
105/// `indexLock` and `landing` share one shape:
106/// an object whose only
107/// accepted key may be omitted to keep the default.
108/// They tune hook serialization,
109/// index-lock patience and landing starvation;
110/// none can disable the transaction.
111///
112/// In TS you'd write (pseudocode):
113/// ```ts
114/// function applyConcurrency(base: ConcurrencyConfig, key: string, value: JsoncValue): ConcurrencyConfig;
115/// ```
116fn apply_concurrency(
117 base: ConcurrencyConfig,
118 key: &str,
119 value: &JsoncValue,
120) -> Result<ConcurrencyConfig, ConfigError> {
121 // The single key each section accepts.
122 let allowed: &str = if key == "hooks" {
123 "concurrentCommits"
124 } else if key == "indexLock" {
125 "unprovenOwnerTimeoutMs"
126 } else {
127 "reserveAfterLostRaces"
128 };
129 // What: `let Some(x) = ... else { return ... };` unwraps the present case or exits.
130 // Why: A section that is not an object has no keys to read.
131 //
132 // In TS you'd write (pseudocode):
133 // ```ts
134 // if (!isRecord(value)) throw wrongKind(value, key, "an object");
135 // ```
136 let Some(entries) = value.entries() else {
137 // `Err(...)` is the failure variant returned to the caller.
138 return Err(wrong_kind(value, key, "an object"));
139 };
140 // A trailing `?` returns the reader error to our caller, or unwraps its value.
141 let keys: Vec<String> = member_keys(entries, key)?;
142 // `ConcurrencyConfig` is `Copy`, so this is an independent editable copy.
143 let mut result: ConcurrencyConfig = base;
144 // What: `.iter().enumerate()` yields `(index, item)` pairs; `usize` is the index type.
145 // Why: The decoded keys are parallel to `entries`, so the index reaches the value.
146 //
147 // In TS you'd write (pseudocode):
148 // ```ts
149 // for (const [index, member] of keys.entries()) { ... }
150 // ```
151 for (index, member) in keys.iter().enumerate() {
152 let path: String = member_path(key, member.as_str());
153 if member != allowed {
154 return Err(ConfigError::new(
155 format!(
156 "Unknown configuration key: {path}. The only accepted key under {key} is {allowed}."
157 )
158 .as_str(),
159 ));
160 }
161 // `&entries[index].value` borrows the member value parallel to this key.
162 let member_value: &JsoncValue = &entries[index].value;
163 if key == "hooks" {
164 result.hooks.concurrent_commits = boolean(member_value, path.as_str())?;
165 result.hooks.present = true;
166 } else if key == "indexLock" {
167 result.index_lock.unproven_owner_timeout_ms =
168 safe_integer(member_value, path.as_str(), 0)?;
169 } else {
170 result.landing.reserve_after_lost_races = safe_integer(member_value, path.as_str(), 1)?;
171 }
172 }
173 // `Ok(result)` is the success variant carrying the tuned copy.
174 return Ok(result);
175}
176
177/// What:
178/// Parse and validate one complete configuration document.
179/// Why:
180/// This is the only way settings enter the native wrapper:
181/// data in,
182/// typed
183/// settings or one actionable error out.
184/// Nothing in the document is executed,
185/// imported or resolved as a path.
186///
187/// In TS you'd write (pseudocode):
188/// ```ts
189/// function parseConfig(source: string): CliGitConfig;
190/// ```
191pub fn parse_config(source: &str) -> Result<CliGitConfig, ConfigError> {
192 // What: `match` on the parser's `Result` keeps the value or converts its error.
193 // `Ok(parsed) => parsed` unwraps success; `Err(error) => { ... }` handles failure.
194 // Why: A syntax failure must keep its byte offset so the author can find it.
195 //
196 // In TS you'd write (pseudocode):
197 // ```ts
198 // let document; try { document = parseJsonc(source); } catch (e) { throw new ConfigError(...); }
199 // ```
200 let document: JsoncValue = match parse_jsonc(source) {
201 Ok(parsed) => parsed,
202 Err(error) => {
203 return Err(ConfigError::new(
204 format!(
205 "JSONC syntax error at byte {}: {}",
206 error.offset, error.message
207 )
208 .as_str(),
209 ));
210 }
211 };
212 let Some(entries) = document.entries() else {
213 // `&document` lends the value to the diagnostic builder.
214 return Err(wrong_kind(&document, "", "an object"));
215 };
216 let keys: Vec<String> = member_keys(entries, "")?;
217 let mut config: CliGitConfig = CliGitConfig::defaults();
218 for (index, key) in keys.iter().enumerate() {
219 // `&entries[index].value` borrows the member value parallel to this key.
220 let value: &JsoncValue = &entries[index].value;
221 if key == "policies" {
222 config.policies = parse_policies(value)?;
223 } else if key == "hooks" || key == "indexLock" || key == "landing" {
224 config.concurrency = apply_concurrency(config.concurrency, key.as_str(), value)?;
225 } else {
226 return Err(unknown_top_level_key(key.as_str()));
227 }
228 }
229 return Ok(config);
230}
231
232/// Acceptance controls stay out of the release executable.
233#[cfg(test)]
234#[path = "config_parse_acceptance_tests.rs"]
235mod acceptance_tests;
236
237/// Structural rejection controls and the shared rejection helpers.
238#[cfg(test)]
239#[path = "config_parse_tests.rs"]
240mod tests;
241
242/// Invalid-value rejection controls.
243#[cfg(test)]
244#[path = "config_parse_value_tests.rs"]
245mod value_tests;