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(role: &str, config: &mut IdentityConfig<'_>) -> Option<(Vec<u8>, Vec<u8>)> {
258    let env_name = env::var_os(format!("GIT_{role}_NAME")).map(argv_bytes_from_os);
259    let env_email = env::var_os(format!("GIT_{role}_EMAIL")).map(argv_bytes_from_os);
260    let name = env_name
261        .or_else(|| {
262            identity_config_value_for_role(role, "name", config).map(String::into_bytes)
263        })
264        .or_else(|| identity_default_value("Git Rs", config).map(String::into_bytes));
265    let email = env_email
266        .or_else(|| {
267            identity_config_value_for_role(role, "email", config).map(String::into_bytes)
268        })
269        .or_else(|| {
270            identity_default_value("sley@example.invalid", config).map(String::into_bytes)
271        });
272    Some((name?, email?))
273}
274
275pub fn commit_identity_from_env(role: &str, effective_config: &GitConfig) -> Result<Vec<u8>> {
276    // Higher-precedence env/`-c`/repo sources are evaluated exactly as before;
277    // the global+system config layer is the fallback below repo config.
278    // The effective config is loaded at most once, and only when the env vars do
279    // not already supply both fields, so the common env-driven path is unchanged.
280    let mut config = if env::var_os(format!("GIT_{role}_NAME")).is_none()
281        || env::var_os(format!("GIT_{role}_EMAIL")).is_none()
282    {
283        IdentityConfig::Loaded(effective_config)
284    } else {
285        IdentityConfig::Skip
286    };
287    let Some((name, email)) = resolve_identity_fields(role, &mut config) else {
288        return identity_use_config_only_error();
289    };
290    validate_commit_identity_name(role, &name, &email)?;
291    let date = env::var(format!("GIT_{role}_DATE")).unwrap_or_else(|_| "@0 +0000".into());
292    let date = canonicalize_commit_date(&date);
293    format_commit_identity_bytes(&name, &email, &date)
294}
295
296/// Like [`commit_identity_from_env`] but with the date forced to `date_override`
297/// (any form [`canonicalize_commit_date`] accepts), keeping the env/config
298/// name+email resolution unchanged. Used by `git am
299/// --committer-date-is-author-date`, which keeps the environment committer
300/// name/email but substitutes the author date.
301pub fn commit_identity_from_env_with_date(
302    role: &str,
303    date_override: &str,
304    effective_config: &GitConfig,
305) -> Result<Vec<u8>> {
306    let mut config = if env::var_os(format!("GIT_{role}_NAME")).is_none()
307        || env::var_os(format!("GIT_{role}_EMAIL")).is_none()
308    {
309        IdentityConfig::Loaded(effective_config)
310    } else {
311        IdentityConfig::Skip
312    };
313    let Some((name, email)) = resolve_identity_fields(role, &mut config) else {
314        return identity_use_config_only_error();
315    };
316    validate_commit_identity_name(role, &name, &email)?;
317    let date = canonicalize_commit_date(date_override);
318    format_commit_identity_bytes(&name, &email, &date)
319}
320
321pub fn committer_identity_for_reflog(effective_config: &GitConfig) -> Result<Vec<u8>> {
322    let mut config = if env::var_os("GIT_COMMITTER_NAME").is_none()
323        || env::var_os("GIT_COMMITTER_EMAIL").is_none()
324    {
325        IdentityConfig::Loaded(effective_config)
326    } else {
327        IdentityConfig::Skip
328    };
329    let name = env::var_os("GIT_COMMITTER_NAME")
330        .map(argv_bytes_from_os)
331        .or_else(|| {
332            identity_config_value_for_role("COMMITTER", "name", &mut config).map(String::into_bytes)
333        })
334        .filter(|value| !value.is_empty())
335        .unwrap_or_else(|| b"Git Rs".to_vec());
336    let email = env::var_os("GIT_COMMITTER_EMAIL")
337        .map(argv_bytes_from_os)
338        .or_else(|| {
339            identity_config_value_for_role("COMMITTER", "email", &mut config).map(String::into_bytes)
340        })
341        .filter(|value| !value.is_empty())
342        .unwrap_or_else(|| b"sley@example.invalid".to_vec());
343    let date = env::var("GIT_COMMITTER_DATE").unwrap_or_else(|_| "@0 +0000".into());
344    let date = canonicalize_commit_date(&date);
345    format_commit_identity_bytes(&name, &email, &date)
346}
347
348pub fn commit_signoff_from_env(effective_config: &GitConfig) -> Result<Vec<u8>> {
349    // git's `--signoff` uses the committer identity, so resolve it with the same
350    // precedence as `commit_identity_from_env("COMMITTER")`.
351    let mut config = if env::var_os("GIT_COMMITTER_NAME").is_none()
352        || env::var_os("GIT_COMMITTER_EMAIL").is_none()
353    {
354        IdentityConfig::Loaded(effective_config)
355    } else {
356        IdentityConfig::Skip
357    };
358    let Some((name, email)) = resolve_identity_fields("COMMITTER", &mut config) else {
359        return identity_use_config_only_error();
360    };
361    validate_commit_identity_name("COMMITTER", &name, &email)?;
362    let date = env::var("GIT_COMMITTER_DATE").unwrap_or_else(|_| "@0 +0000".into());
363    let date = canonicalize_commit_date(&date);
364    format_commit_identity_bytes(&name, &email, &date)?;
365    let mut out = b"Signed-off-by: ".to_vec();
366    out.extend_from_slice(&name);
367    out.extend_from_slice(b" <");
368    out.extend_from_slice(&email);
369    out.push(b'>');
370    Ok(out)
371}
372
373pub fn commit_reflog_message(message: &[u8], amend: bool) -> Vec<u8> {
374    commit_reflog_message_with_initial(message, amend, false)
375}
376
377pub fn commit_reflog_message_with_initial(
378    message: &[u8],
379    amend: bool,
380    initial: bool,
381) -> Vec<u8> {
382    let subject = String::from_utf8_lossy(message)
383        .lines()
384        .next()
385        .unwrap_or("")
386        .to_string();
387    if amend {
388        format!("commit (amend): {subject}").into_bytes()
389    } else if initial {
390        format!("commit (initial): {subject}").into_bytes()
391    } else {
392        format!("commit: {subject}").into_bytes()
393    }
394}
395
396pub fn default_committer() -> Vec<u8> {
397    b"Git Rs <sley@example.invalid> 0 +0000".to_vec()
398}
399
400#[cfg(test)]
401mod tests {
402    use super::*;
403
404    #[test]
405    fn identity_formats_raw_git_date() {
406        let identity =
407            format_commit_identity("Example User", "example@example.invalid", "@0 +0000")
408                .expect("test operation should succeed");
409        assert_eq!(identity, b"Example User <example@example.invalid> 0 +0000");
410    }
411
412    #[test]
413    fn identity_rejects_control_bytes_and_bad_timezones() {
414        assert!(format_commit_identity_bytes(b"na\nme", b"x@y", "@0 +0000").is_err());
415        assert!(format_commit_identity_bytes(b"name", b"x@y", "not-a-date").is_err());
416        assert!(format_commit_identity_bytes(b"name", b"x@y", "@0 +000").is_err());
417        assert!(format_commit_identity_bytes(b"name", b"x@y", "@0 0000").is_err());
418        assert!(format_commit_identity_bytes(b"name", b"x@y", "@0 +0000 extra").is_err());
419    }
420
421    #[test]
422    fn canonicalize_accepts_the_raw_form_and_strips_the_at_sign() {
423        assert_eq!(
424            try_canonicalize_commit_date("@1234 +0530"),
425            Some("1234 +0530".to_string())
426        );
427        assert_eq!(try_canonicalize_commit_date("not a date"), None);
428    }
429
430    #[test]
431    fn canonicalizes_iso_dates_to_raw_seconds() {
432        assert_eq!(
433            canonicalize_commit_date("1970-01-01 00:00:00 +0000"),
434            "0 +0000"
435        );
436    }
437
438    #[test]
439    fn validates_ident_names_like_git() {
440        assert!(validate_commit_identity_name("AUTHOR", b"", b"x@y").is_err());
441        assert!(validate_commit_identity_name("AUTHOR", b"<<<", b"x@y").is_err());
442        assert!(validate_commit_identity_name("AUTHOR", b"A U Thor", b"x@y").is_ok());
443        assert!(commit_identity_name_crud(b'<'));
444        assert!(!commit_identity_name_crud(b'a'));
445    }
446
447    #[test]
448    fn reflog_messages_follow_git_subject_rules() {
449        assert_eq!(
450            commit_reflog_message(b"subject\n\nbody", false),
451            b"commit: subject".to_vec()
452        );
453        assert_eq!(
454            commit_reflog_message(b"subject", true),
455            b"commit (amend): subject".to_vec()
456        );
457        assert_eq!(
458            commit_reflog_message_with_initial(b"subject", false, true),
459            b"commit (initial): subject".to_vec()
460        );
461        assert_eq!(default_committer(), b"Git Rs <sley@example.invalid> 0 +0000");
462    }
463
464    #[test]
465    fn signoff_uses_committer_identity_shape() {
466        let config = GitConfig::default();
467        // Env-independent shape assertion: the runner may or may not carry
468        // GIT_COMMITTER_* variables, but the trailer format is fixed.
469        if let Ok(signoff) = commit_signoff_from_env(&config) {
470            let text = String::from_utf8_lossy(&signoff).into_owned();
471            assert!(text.starts_with("Signed-off-by: "), "{text}");
472            assert!(text.ends_with('>'), "{text}");
473        }
474    }
475}