Skip to main content

sley_object/
identity.rs

1//! Author/committer identity resolution from env and config (git's `ident.c`).
2//!
3//! Sunk out of the CLI so every engine path that authors objects resolves
4//! identities through the same precedence chain:
5//!
6//! 1. `GIT_{role}_NAME`/`GIT_{role}_EMAIL` env vars
7//! 2. `-c {author,committer}.name=` / `GIT_CONFIG_*` command-line overrides
8//! 3. effective config `{author,committer}.name/email`
9//! 4. effective config `user.name/email`
10//! 5. sley's built-in default identity
11
12use std::env;
13use std::ffi::OsString;
14
15use sley_config::GitConfig;
16use sley_core::date::approxidate::parse_commit_date;
17use sley_core::{GitError, Result};
18
19/// Canonicalise a `GIT_*_DATE`/`--date=` value to git's raw `<seconds> +HHMM`
20/// form so the sequencer's identity builder (which only accepts the raw form)
21/// stores the same bytes git would.
22///
23/// git's `commit-tree` / `commit` run author and committer dates through
24/// `parse_date` / `approxidate_careful`, accepting ISO-8601
25/// (`2005-04-07T22:13:13`), `<date> <time> <tz>`, RFC-2822, fuzzy approxidates,
26/// and the raw form. Values that do not parse are passed through verbatim so
27/// callers that only need best-effort conversion (env `GIT_*_DATE`) still get a
28/// diagnostic from the identity formatter; prefer [`try_canonicalize_commit_date`]
29/// when a hard reject with git's `invalid date format` message is required
30/// (`--date=`).
31pub fn canonicalize_commit_date(date: &str) -> String {
32    if date.is_empty() {
33        return default_commit_date();
34    }
35    match parse_commit_date(date) {
36        Some((seconds, tz)) => format!("{seconds} {tz}"),
37        None => date.to_string(),
38    }
39}
40
41/// Like [`canonicalize_commit_date`] but returns `None` when the value does not
42/// parse — used for `git commit --date=` so we can die with
43/// `fatal: invalid date format: …` matching git's `parse_force_date`.
44pub fn try_canonicalize_commit_date(date: &str) -> Option<String> {
45    if date.is_empty() {
46        return Some(default_commit_date());
47    }
48    parse_commit_date(date).map(|(seconds, tz)| format!("{seconds} {tz}"))
49}
50
51pub fn default_commit_date() -> String {
52    let seconds = std::time::SystemTime::now()
53        .duration_since(std::time::UNIX_EPOCH)
54        .map(|duration| duration.as_secs().min(i64::MAX as u64) as i64)
55        .unwrap_or(0);
56    format!("{seconds} +0000")
57}
58
59/// Format a name/email/date triple as git's raw ident line
60/// (`Name <email> <seconds> +HHMM`), rejecting control bytes in either
61/// component and anything but the raw date form.
62pub fn format_commit_identity(name: &str, email: &str, date: &str) -> Result<Vec<u8>> {
63    format_commit_identity_bytes(name.as_bytes(), email.as_bytes(), date)
64}
65
66pub fn format_commit_identity_bytes(name: &[u8], email: &[u8], date: &str) -> Result<Vec<u8>> {
67    validate_identity_component_bytes("name", name)?;
68    validate_identity_component_bytes("email", email)?;
69    let (seconds, timezone) = parse_raw_git_date(date)?;
70    let mut out = Vec::with_capacity(name.len() + email.len() + timezone.len() + 32);
71    out.extend_from_slice(name);
72    out.extend_from_slice(b" <");
73    out.extend_from_slice(email);
74    out.extend_from_slice(b"> ");
75    out.extend_from_slice(seconds.to_string().as_bytes());
76    out.push(b' ');
77    out.extend_from_slice(timezone.as_bytes());
78    Ok(out)
79}
80
81fn validate_identity_component_bytes(name: &str, value: &[u8]) -> Result<()> {
82    if value.iter().any(|byte| matches!(*byte, b'\n' | b'\r' | 0)) {
83        return Err(GitError::InvalidFormat(format!(
84            "commit identity {name} contains a control byte"
85        )));
86    }
87    Ok(())
88}
89
90fn parse_raw_git_date(date: &str) -> Result<(i64, String)> {
91    let mut parts = date.split_whitespace();
92    let seconds = parts
93        .next()
94        .ok_or_else(|| GitError::InvalidFormat("missing commit date seconds".into()))?;
95    let timezone = parts
96        .next()
97        .ok_or_else(|| GitError::InvalidFormat("missing commit date timezone".into()))?;
98    if parts.next().is_some() {
99        return Err(GitError::InvalidFormat(
100            "commit date has trailing fields".into(),
101        ));
102    }
103    let seconds = seconds.strip_prefix('@').unwrap_or(seconds);
104    let seconds = seconds
105        .parse::<i64>()
106        .map_err(|_| GitError::InvalidFormat("invalid commit date seconds".into()))?;
107    validate_timezone(timezone)?;
108    Ok((seconds, timezone.to_string()))
109}
110
111fn validate_timezone(timezone: &str) -> Result<()> {
112    let bytes = timezone.as_bytes();
113    if bytes.len() != 5
114        || !matches!(bytes[0], b'+' | b'-')
115        || !bytes[1..].iter().all(u8::is_ascii_digit)
116    {
117        return Err(GitError::InvalidFormat(format!(
118            "invalid commit timezone {timezone}"
119        )));
120    }
121    Ok(())
122}
123
124/// Explicit effective config used as the identity fallback. `Skip` means the
125/// caller already has both fields from the environment, so config lookup is
126/// unnecessary; `Loaded` borrows the invocation's already-resolved snapshot.
127pub enum IdentityConfig<'a> {
128    Skip,
129    Loaded(&'a GitConfig),
130}
131
132/// Look up a single injected (`-c`/`--config-env`/`GIT_CONFIG_COUNT`) override,
133/// mirroring git's highest-precedence command-line layer. Parse failures print
134/// git's two-line diagnostic exactly once per failing lookup; every other miss
135/// is silent.
136fn injected_config_value(key: &str) -> Option<String> {
137    let canonical = match sley_config::canonicalize_config_key(key) {
138        Ok(canonical) => canonical,
139        // The lookup key is a fixed internal key; if it fails to canonicalise
140        // there can be no matching override.
141        Err(_) => return None,
142    };
143    let parameters_env = sley_config::effective_config_parameters_env();
144    match sley_config::injected_config_parameters(parameters_env.as_deref()) {
145        Ok(parameters) => parameters
146            .iter()
147            .rev()
148            .find(|param| param.canonical_key.eq_ignore_ascii_case(&canonical))
149            .map(|param| match &param.value {
150                Some(value) => value.clone(),
151                None => "true".to_string(),
152            }),
153        Err(err) => {
154            eprintln!("error: {}", err.message());
155            eprintln!("fatal: unable to parse command-line config");
156            None
157        }
158    }
159}
160
161/// Resolve an identity config key (`user.name`/`user.email`) following git's
162/// precedence below the environment: `-c`/`GIT_CONFIG_*` command-line overrides
163/// first, then the effective config (repository, then global, then system).
164pub fn identity_config_value(key: &str, config: &mut IdentityConfig<'_>) -> Option<String> {
165    if let Some(value) = injected_config_value(key) {
166        return Some(value);
167    }
168    let (section, name) = key.split_once('.')?;
169    let loaded = match config {
170        IdentityConfig::Skip => return None,
171        IdentityConfig::Loaded(config) => *config,
172    };
173    loaded.get(section, None, name).map(str::to_string)
174}
175
176pub fn identity_config_value_for_role(
177    role: &str,
178    field: &str,
179    config: &mut IdentityConfig<'_>,
180) -> Option<String> {
181    let role_key = match role {
182        "AUTHOR" => Some(format!("author.{field}")),
183        "COMMITTER" => Some(format!("committer.{field}")),
184        _ => None,
185    };
186    role_key
187        .as_deref()
188        .and_then(|key| identity_config_value(key, config))
189        .or_else(|| identity_config_value(&format!("user.{field}"), config))
190}
191
192pub fn identity_default_value(value: &str, config: &mut IdentityConfig<'_>) -> Option<String> {
193    if identity_use_config_only(config) {
194        None
195    } else {
196        Some(value.to_string())
197    }
198}
199
200pub fn identity_use_config_only(config: &mut IdentityConfig<'_>) -> bool {
201    identity_config_value("user.useconfigonly", config)
202        .as_deref()
203        .and_then(sley_config::parse_config_bool)
204        .unwrap_or(false)
205}
206
207pub fn identity_use_config_only_error<T>() -> Result<T> {
208    eprintln!("fatal: no email was given and auto-detection is disabled");
209    Err(GitError::Exit(128))
210}
211
212pub fn validate_commit_identity_name(role: &str, name: &[u8], email: &[u8]) -> Result<()> {
213    if name.is_empty() {
214        print_identity_unknown_hint(role);
215        eprintln!(
216            "fatal: empty ident name (for <{}>) not allowed",
217            String::from_utf8_lossy(email)
218        );
219        return Err(GitError::Exit(128));
220    }
221    if !name.iter().any(|byte| !commit_identity_name_crud(*byte)) {
222        eprintln!(
223            "fatal: name consists only of disallowed characters: {}",
224            String::from_utf8_lossy(name)
225        );
226        return Err(GitError::Exit(128));
227    }
228    Ok(())
229}
230
231pub fn commit_identity_name_crud(byte: u8) -> bool {
232    matches!(
233        byte,
234        0..=32 | b',' | b':' | b';' | b'<' | b'>' | b'"' | b'\\' | b'\''
235    )
236}
237
238pub fn print_identity_unknown_hint(role: &str) {
239    match role {
240        "AUTHOR" => eprintln!("Author identity unknown"),
241        "COMMITTER" => eprintln!("Committer identity unknown"),
242        _ => {}
243    }
244}
245
246#[cfg(unix)]
247fn argv_bytes_from_os(value: OsString) -> Vec<u8> {
248    use std::os::unix::ffi::OsStrExt;
249    value.as_os_str().as_bytes().to_vec()
250}
251
252#[cfg(not(unix))]
253fn argv_bytes_from_os(value: OsString) -> Vec<u8> {
254    value.to_string_lossy().into_owned().into_bytes()
255}
256
257fn resolve_identity_fields(
258    role: &str,
259    config: &mut IdentityConfig<'_>,
260) -> Option<(Vec<u8>, Vec<u8>)> {
261    let env_name = env::var_os(format!("GIT_{role}_NAME")).map(argv_bytes_from_os);
262    let env_email = env::var_os(format!("GIT_{role}_EMAIL")).map(argv_bytes_from_os);
263    let name = env_name
264        .or_else(|| identity_config_value_for_role(role, "name", config).map(String::into_bytes))
265        .or_else(|| identity_default_value("Git Rs", config).map(String::into_bytes));
266    let email = env_email
267        .or_else(|| identity_config_value_for_role(role, "email", config).map(String::into_bytes))
268        .or_else(|| identity_default_value("sley@example.invalid", config).map(String::into_bytes));
269    Some((name?, email?))
270}
271
272pub fn commit_identity_from_env(role: &str, effective_config: &GitConfig) -> Result<Vec<u8>> {
273    // Higher-precedence env/`-c`/repo sources are evaluated exactly as before;
274    // the global+system config layer is the fallback below repo config.
275    // The effective config is loaded at most once, and only when the env vars do
276    // not already supply both fields, so the common env-driven path is unchanged.
277    let mut config = if env::var_os(format!("GIT_{role}_NAME")).is_none()
278        || env::var_os(format!("GIT_{role}_EMAIL")).is_none()
279    {
280        IdentityConfig::Loaded(effective_config)
281    } else {
282        IdentityConfig::Skip
283    };
284    let Some((name, email)) = resolve_identity_fields(role, &mut config) else {
285        return identity_use_config_only_error();
286    };
287    validate_commit_identity_name(role, &name, &email)?;
288    let date = env::var(format!("GIT_{role}_DATE")).unwrap_or_else(|_| "@0 +0000".into());
289    let date = canonicalize_commit_date(&date);
290    format_commit_identity_bytes(&name, &email, &date)
291}
292
293/// Like [`commit_identity_from_env`] but with the date forced to `date_override`
294/// (any form [`canonicalize_commit_date`] accepts), keeping the env/config
295/// name+email resolution unchanged. Used by `git am
296/// --committer-date-is-author-date`, which keeps the environment committer
297/// name/email but substitutes the author date.
298pub fn commit_identity_from_env_with_date(
299    role: &str,
300    date_override: &str,
301    effective_config: &GitConfig,
302) -> Result<Vec<u8>> {
303    let mut config = if env::var_os(format!("GIT_{role}_NAME")).is_none()
304        || env::var_os(format!("GIT_{role}_EMAIL")).is_none()
305    {
306        IdentityConfig::Loaded(effective_config)
307    } else {
308        IdentityConfig::Skip
309    };
310    let Some((name, email)) = resolve_identity_fields(role, &mut config) else {
311        return identity_use_config_only_error();
312    };
313    validate_commit_identity_name(role, &name, &email)?;
314    let date = canonicalize_commit_date(date_override);
315    format_commit_identity_bytes(&name, &email, &date)
316}
317
318pub fn committer_identity_for_reflog(effective_config: &GitConfig) -> Result<Vec<u8>> {
319    let mut config = if env::var_os("GIT_COMMITTER_NAME").is_none()
320        || env::var_os("GIT_COMMITTER_EMAIL").is_none()
321    {
322        IdentityConfig::Loaded(effective_config)
323    } else {
324        IdentityConfig::Skip
325    };
326    let name = env::var_os("GIT_COMMITTER_NAME")
327        .map(argv_bytes_from_os)
328        .or_else(|| {
329            identity_config_value_for_role("COMMITTER", "name", &mut config).map(String::into_bytes)
330        })
331        .filter(|value| !value.is_empty())
332        .unwrap_or_else(|| b"Git Rs".to_vec());
333    let email = env::var_os("GIT_COMMITTER_EMAIL")
334        .map(argv_bytes_from_os)
335        .or_else(|| {
336            identity_config_value_for_role("COMMITTER", "email", &mut config)
337                .map(String::into_bytes)
338        })
339        .filter(|value| !value.is_empty())
340        .unwrap_or_else(|| b"sley@example.invalid".to_vec());
341    let date = env::var("GIT_COMMITTER_DATE").unwrap_or_else(|_| "@0 +0000".into());
342    let date = canonicalize_commit_date(&date);
343    format_commit_identity_bytes(&name, &email, &date)
344}
345
346pub fn commit_signoff_from_env(effective_config: &GitConfig) -> Result<Vec<u8>> {
347    // git's `--signoff` uses the committer identity, so resolve it with the same
348    // precedence as `commit_identity_from_env("COMMITTER")`.
349    let mut config = if env::var_os("GIT_COMMITTER_NAME").is_none()
350        || env::var_os("GIT_COMMITTER_EMAIL").is_none()
351    {
352        IdentityConfig::Loaded(effective_config)
353    } else {
354        IdentityConfig::Skip
355    };
356    let Some((name, email)) = resolve_identity_fields("COMMITTER", &mut config) else {
357        return identity_use_config_only_error();
358    };
359    validate_commit_identity_name("COMMITTER", &name, &email)?;
360    let date = env::var("GIT_COMMITTER_DATE").unwrap_or_else(|_| "@0 +0000".into());
361    let date = canonicalize_commit_date(&date);
362    format_commit_identity_bytes(&name, &email, &date)?;
363    let mut out = b"Signed-off-by: ".to_vec();
364    out.extend_from_slice(&name);
365    out.extend_from_slice(b" <");
366    out.extend_from_slice(&email);
367    out.push(b'>');
368    Ok(out)
369}
370
371pub fn commit_reflog_message(message: &[u8], amend: bool) -> Vec<u8> {
372    commit_reflog_message_with_initial(message, amend, false)
373}
374
375pub fn commit_reflog_message_with_initial(message: &[u8], amend: bool, initial: bool) -> Vec<u8> {
376    let subject = String::from_utf8_lossy(message)
377        .lines()
378        .next()
379        .unwrap_or("")
380        .to_string();
381    if amend {
382        format!("commit (amend): {subject}").into_bytes()
383    } else if initial {
384        format!("commit (initial): {subject}").into_bytes()
385    } else {
386        format!("commit: {subject}").into_bytes()
387    }
388}
389
390pub fn default_committer() -> Vec<u8> {
391    b"Git Rs <sley@example.invalid> 0 +0000".to_vec()
392}
393
394#[cfg(test)]
395mod tests {
396    use super::*;
397
398    #[test]
399    fn identity_formats_raw_git_date() {
400        let identity =
401            format_commit_identity("Example User", "example@example.invalid", "@0 +0000")
402                .expect("test operation should succeed");
403        assert_eq!(identity, b"Example User <example@example.invalid> 0 +0000");
404    }
405
406    #[test]
407    fn identity_rejects_control_bytes_and_bad_timezones() {
408        assert!(format_commit_identity_bytes(b"na\nme", b"x@y", "@0 +0000").is_err());
409        assert!(format_commit_identity_bytes(b"name", b"x@y", "not-a-date").is_err());
410        assert!(format_commit_identity_bytes(b"name", b"x@y", "@0 +000").is_err());
411        assert!(format_commit_identity_bytes(b"name", b"x@y", "@0 0000").is_err());
412        assert!(format_commit_identity_bytes(b"name", b"x@y", "@0 +0000 extra").is_err());
413    }
414
415    #[test]
416    fn canonicalize_accepts_the_raw_form_and_strips_the_at_sign() {
417        assert_eq!(
418            try_canonicalize_commit_date("@1234 +0530"),
419            Some("1234 +0530".to_string())
420        );
421        assert_eq!(try_canonicalize_commit_date("not a date"), None);
422    }
423
424    #[test]
425    fn canonicalizes_iso_dates_to_raw_seconds() {
426        assert_eq!(
427            canonicalize_commit_date("1970-01-01 00:00:00 +0000"),
428            "0 +0000"
429        );
430    }
431
432    #[test]
433    fn validates_ident_names_like_git() {
434        assert!(validate_commit_identity_name("AUTHOR", b"", b"x@y").is_err());
435        assert!(validate_commit_identity_name("AUTHOR", b"<<<", b"x@y").is_err());
436        assert!(validate_commit_identity_name("AUTHOR", b"A U Thor", b"x@y").is_ok());
437        assert!(commit_identity_name_crud(b'<'));
438        assert!(!commit_identity_name_crud(b'a'));
439    }
440
441    #[test]
442    fn reflog_messages_follow_git_subject_rules() {
443        assert_eq!(
444            commit_reflog_message(b"subject\n\nbody", false),
445            b"commit: subject".to_vec()
446        );
447        assert_eq!(
448            commit_reflog_message(b"subject", true),
449            b"commit (amend): subject".to_vec()
450        );
451        assert_eq!(
452            commit_reflog_message_with_initial(b"subject", false, true),
453            b"commit (initial): subject".to_vec()
454        );
455        assert_eq!(
456            default_committer(),
457            b"Git Rs <sley@example.invalid> 0 +0000"
458        );
459    }
460
461    #[test]
462    fn signoff_uses_committer_identity_shape() {
463        let config = GitConfig::default();
464        // Env-independent shape assertion: the runner may or may not carry
465        // GIT_COMMITTER_* variables, but the trailer format is fixed.
466        if let Ok(signoff) = commit_signoff_from_env(&config) {
467            let text = String::from_utf8_lossy(&signoff).into_owned();
468            assert!(text.starts_with("Signed-off-by: "), "{text}");
469            assert!(text.ends_with('>'), "{text}");
470        }
471    }
472}