Skip to main content

grit_lib/
ident_resolve.rs

1//! Git-compatible author/committer identity resolution (see upstream `ident.c`).
2//!
3//! This module keeps environment access injectable so callers can test identity resolution
4//! without mutating process-wide state.
5
6use std::ffi::OsString;
7
8use thiserror::Error;
9use time::OffsetDateTime;
10
11use crate::commit::assemble_identity;
12#[cfg(unix)]
13use crate::commit_encoding::decode_bytes;
14use crate::config::ConfigSet;
15use crate::ident::{parse_signature, Signature};
16use crate::ident_config::{env_user_name, ident_default_name};
17
18/// Environment access used for identity resolution.
19pub trait IdentityEnv {
20    /// Return a UTF-8 environment variable, if it exists and is valid Unicode.
21    fn var(&self, key: &str) -> Option<String>;
22
23    /// Return a raw environment variable value, preserving non-UTF-8 bytes on Unix.
24    fn var_os(&self, key: &str) -> Option<OsString>;
25}
26
27/// Whether `GIT_AUTHOR_NAME` / `GIT_COMMITTER_NAME` is unset vs set (possibly empty).
28///
29/// Git treats a set-but-empty value as an explicit override: it must not fall through
30/// to `user.name` or passwd/GECOS fallback (`t7518-ident-corner-cases`).
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub enum GitIdentityNameEnv {
33    /// Variable is not present in the environment.
34    Unset,
35    /// Present after trimming whitespace (may be `""`).
36    Set(String),
37}
38
39/// Author vs committer for `GIT_*` / `author.*` / `committer.*` lookup.
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub enum IdentRole {
42    /// Author identity.
43    Author,
44    /// Committer identity.
45    Committer,
46}
47
48impl IdentRole {
49    fn env_name_key(self) -> &'static str {
50        match self {
51            IdentRole::Author => "GIT_AUTHOR_NAME",
52            IdentRole::Committer => "GIT_COMMITTER_NAME",
53        }
54    }
55
56    fn env_email_key(self) -> &'static str {
57        match self {
58            IdentRole::Author => "GIT_AUTHOR_EMAIL",
59            IdentRole::Committer => "GIT_COMMITTER_EMAIL",
60        }
61    }
62
63    fn config_name_key(self) -> &'static str {
64        match self {
65            IdentRole::Author => "author.name",
66            IdentRole::Committer => "committer.name",
67        }
68    }
69
70    fn config_email_key(self) -> &'static str {
71        match self {
72            IdentRole::Author => "author.email",
73            IdentRole::Committer => "committer.email",
74        }
75    }
76
77    /// Environment variable that overrides this role's timestamp
78    /// (`GIT_AUTHOR_DATE` / `GIT_COMMITTER_DATE`).
79    #[must_use]
80    pub fn env_date_key(self) -> &'static str {
81        match self {
82            IdentRole::Author => "GIT_AUTHOR_DATE",
83            IdentRole::Committer => "GIT_COMMITTER_DATE",
84        }
85    }
86
87    /// Heading Git prints before identity setup advice.
88    #[must_use]
89    pub fn missing_email_hint(self) -> &'static str {
90        match self {
91            IdentRole::Author => "Author identity unknown",
92            IdentRole::Committer => "Committer identity unknown",
93        }
94    }
95}
96
97/// Errors returned by strict identity resolution.
98#[derive(Clone, Debug, Error, PartialEq, Eq)]
99#[non_exhaustive]
100pub enum IdentityError {
101    /// `user.useConfigOnly` disables email auto-detection and no config email was provided.
102    ///
103    /// The Display text here is a terse, functional description of the
104    /// condition. User-facing setup guidance is rendered by `grit-cli`.
105    #[error("email auto-detection is disabled (user.useConfigOnly) and no configured email is available")]
106    AutoDetectionDisabled {
107        /// Identity role being resolved.
108        role: IdentRole,
109    },
110    /// No configured or environment email is available and auto-detection is not allowed.
111    #[error("no configured email is available for auto-detection")]
112    MissingConfiguredEmail {
113        /// Identity role being resolved.
114        role: IdentRole,
115    },
116    /// Git rejects empty ident names.
117    #[error("empty ident name (for <{email}>) not allowed")]
118    EmptyName {
119        /// Email address associated with the attempted identity.
120        email: String,
121        /// Identity role being resolved.
122        role: IdentRole,
123    },
124    /// Git rejects names containing only "crud" characters.
125    #[error("invalid ident name: '{name}'")]
126    InvalidName {
127        /// Rejected name.
128        name: String,
129    },
130    /// The role's date override (`GIT_AUTHOR_DATE` / `GIT_COMMITTER_DATE`) is not a date Git accepts.
131    #[error("invalid date '{date}'")]
132    InvalidDate {
133        /// The rejected override value.
134        date: String,
135        /// Identity role being resolved.
136        role: IdentRole,
137    },
138    /// The resolved name or email cannot be written into an identity line.
139    #[error(transparent)]
140    InvalidSignature(#[from] crate::ident::SignatureError),
141}
142
143/// Read a `GIT_*_NAME` variable like Git's `getenv`: unset vs set, preserving explicit empty.
144#[must_use]
145pub fn read_git_identity_name_env_with<E: IdentityEnv>(env: &E, key: &str) -> GitIdentityNameEnv {
146    let Some(os) = env.var_os(key) else {
147        return GitIdentityNameEnv::Unset;
148    };
149    #[cfg(unix)]
150    {
151        use std::os::unix::ffi::OsStrExt;
152        let bytes = os.as_bytes();
153        let s = if std::str::from_utf8(bytes).is_ok() {
154            String::from_utf8_lossy(bytes).into_owned()
155        } else {
156            decode_bytes(Some("ISO8859-1"), bytes)
157        };
158        GitIdentityNameEnv::Set(s.trim().to_owned())
159    }
160    #[cfg(not(unix))]
161    {
162        let s = os.to_str().map(|t| t.trim().to_owned()).unwrap_or_default();
163        GitIdentityNameEnv::Set(s)
164    }
165}
166
167/// The value of a `GIT_*_NAME` variable when it is set (possibly to `""`).
168fn name_env_with<E: IdentityEnv>(env: &E, key: &str) -> Option<String> {
169    match read_git_identity_name_env_with(env, key) {
170        GitIdentityNameEnv::Set(name) => Some(name),
171        GitIdentityNameEnv::Unset => None,
172    }
173}
174
175/// `value` trimmed, or [`None`] when it is missing or blank.
176fn non_blank(value: Option<String>) -> Option<String> {
177    value.map(|v| v.trim().to_owned()).filter(|v| !v.is_empty())
178}
179
180fn use_config_only(config: &ConfigSet) -> bool {
181    config.bool_with_default("user.useConfigOnly", false)
182}
183
184fn config_mail_given(config: &ConfigSet) -> bool {
185    ["user.email", "author.email", "committer.email"]
186        .iter()
187        .any(|key| non_blank(config.value(key)).is_some())
188}
189
190fn ident_name_has_non_crud(name: &str) -> bool {
191    name.chars().any(|c| {
192        let o = c as u32;
193        !(o <= 32
194            || c == ','
195            || c == ':'
196            || c == ';'
197            || c == '<'
198            || c == '>'
199            || c == '"'
200            || c == '\\'
201            || c == '\'')
202    })
203}
204
205fn synthetic_email_with<E: IdentityEnv>(env: &E) -> String {
206    let user = env_user_name(env);
207    let host = env.var("HOSTNAME").unwrap_or_else(|| "unknown".to_owned());
208    let domain = if host.contains('.') {
209        host
210    } else {
211        format!("{host}.(none)")
212    };
213    format!("{user}@{domain}")
214}
215
216/// Resolve email for a role when creating commits (honors `user.useConfigOnly`).
217///
218/// Looks at `GIT_<ROLE>_EMAIL`, `<role>.email`, `user.email`, then (unless
219/// `user.useConfigOnly` is set without any configured email) `EMAIL`. Never synthesizes
220/// an address from the user and host names.
221///
222/// # Errors
223///
224/// [`IdentityError::AutoDetectionDisabled`] when `user.useConfigOnly` blocks the `EMAIL`
225/// fallback, [`IdentityError::MissingConfiguredEmail`] when no source provides an email.
226pub fn resolve_email_with<E: IdentityEnv>(
227    env: &E,
228    config: &ConfigSet,
229    role: IdentRole,
230) -> Result<String, IdentityError> {
231    let configured = non_blank(env.var(role.env_email_key()))
232        .or_else(|| non_blank(config.value(role.config_email_key())))
233        .or_else(|| non_blank(config.value("user.email")));
234    if let Some(email) = configured {
235        return Ok(email);
236    }
237    if use_config_only(config) && !config_mail_given(config) {
238        return Err(IdentityError::AutoDetectionDisabled { role });
239    }
240    non_blank(env.var("EMAIL")).ok_or(IdentityError::MissingConfiguredEmail { role })
241}
242
243/// Resolve name for a role when creating commits.
244///
245/// A set `GIT_<ROLE>_NAME` wins even when empty; otherwise `<role>.name`, then Git's
246/// default name (`user.name`, or the system user name).
247///
248/// # Errors
249///
250/// Fails like [`resolve_email_with`] when no email is available, with
251/// [`IdentityError::EmptyName`] for an empty name and [`IdentityError::InvalidName`] for a
252/// name made only of characters Git strips.
253pub fn resolve_name_with<E: IdentityEnv>(
254    env: &E,
255    config: &ConfigSet,
256    role: IdentRole,
257) -> Result<String, IdentityError> {
258    let email = resolve_email_with(env, config, role)?;
259
260    let name = name_env_with(env, role.env_name_key()).unwrap_or_else(|| {
261        non_blank(config.value(role.config_name_key()))
262            .unwrap_or_else(|| ident_default_name(config, env))
263    });
264
265    if name.is_empty() {
266        return Err(IdentityError::EmptyName { email, role });
267    }
268
269    if !ident_name_has_non_crud(&name) {
270        return Err(IdentityError::InvalidName { name });
271    }
272
273    Ok(name)
274}
275
276/// Resolve the full identity line (`Name <email> <epoch> <offset>`) for `role` when
277/// creating a commit, tag or notes commit.
278///
279/// Name and email come from [`resolve_name_with`] and [`resolve_email_with`], so this fails
280/// exactly when they do. The timestamp is the role's [`IdentRole::env_date_key`] variable
281/// when set and non-blank, otherwise `now`.
282///
283/// # Parameters
284///
285/// - `env`: environment supplying `GIT_*` identity and date variables.
286/// - `config`: configuration supplying `user.*`, `author.*` and `committer.*`.
287/// - `role`: whether to resolve the author or the committer.
288/// - `now`: timestamp (with its UTC offset) used when no date override is set.
289///
290/// # Errors
291///
292/// Returns [`IdentityError`] when no usable name or email is configured.
293pub fn resolve_identity_with<E: IdentityEnv>(
294    env: &E,
295    config: &ConfigSet,
296    role: IdentRole,
297    now: OffsetDateTime,
298) -> Result<String, IdentityError> {
299    let name = resolve_name_with(env, config, role)?;
300    let email = resolve_email_with(env, config, role)?;
301    let date = env
302        .var(role.env_date_key())
303        .filter(|d| !d.trim().is_empty());
304    Ok(assemble_identity(&name, &email, date.as_deref(), now))
305}
306
307/// Resolve the identity for `role` as a typed [`Signature`] when creating a commit, tag, stash,
308/// or notes commit.
309///
310/// Resolution is the same as [`resolve_identity_with`]; the date override must also be a date
311/// Git accepts, and the name and email must be writable into an object.
312///
313/// # Parameters
314///
315/// - `env`: environment supplying `GIT_*` identity and date variables.
316/// - `config`: configuration supplying `user.*`, `author.*` and `committer.*`.
317/// - `role`: whether to resolve the author or the committer.
318/// - `now`: timestamp (with its UTC offset) used when no date override is set.
319///
320/// # Errors
321///
322/// The [`resolve_identity_with`] errors, plus [`IdentityError::InvalidDate`] for an unparsable
323/// date override and [`IdentityError::InvalidSignature`] for a name or email holding `<`, `>`,
324/// or a control character.
325pub fn resolve_signature_with<E: IdentityEnv>(
326    env: &E,
327    config: &ConfigSet,
328    role: IdentRole,
329    now: OffsetDateTime,
330) -> Result<Signature, IdentityError> {
331    let name = resolve_name_with(env, config, role)?;
332    let email = resolve_email_with(env, config, role)?;
333    let date = env
334        .var(role.env_date_key())
335        .filter(|d| !d.trim().is_empty());
336    let line = assemble_identity(&name, &email, date.as_deref(), now);
337    let time = parse_signature(&line)
338        .ok_or_else(|| IdentityError::InvalidDate {
339            date: date.unwrap_or_default(),
340            role,
341        })?
342        .time;
343    Ok(Signature::new(name, email, time)?)
344}
345
346/// Best-effort committer identity line (`Name <email> <epoch> <offset>`) for reflog entries.
347///
348/// Never fails: the name comes from `GIT_COMMITTER_NAME` (or, when that is unset,
349/// `GIT_AUTHOR_NAME`), `committer.name`, `user.name`, the system user name, then
350/// `"Unknown"`; the email from `GIT_COMMITTER_EMAIL`, `GIT_AUTHOR_EMAIL`, `committer.email`,
351/// `user.email`, `EMAIL`, then a synthesized `user@host` address. It always stamps `now`
352/// (callers that want `GIT_COMMITTER_DATE` honoured fold it into `now`).
353///
354/// # Parameters
355///
356/// - `env`: environment supplying `GIT_*` identity variables.
357/// - `config`: configuration supplying `committer.*` and `user.*`.
358/// - `now`: timestamp (with its UTC offset) recorded on the line.
359#[must_use]
360pub fn resolve_loose_committer_identity_with<E: IdentityEnv>(
361    env: &E,
362    config: &ConfigSet,
363    now: OffsetDateTime,
364) -> String {
365    let name = name_env_with(env, "GIT_COMMITTER_NAME")
366        .or_else(|| name_env_with(env, "GIT_AUTHOR_NAME"))
367        .filter(|name| !name.is_empty())
368        .or_else(|| non_blank(config.value("committer.name")))
369        .or_else(|| non_blank(config.value("user.name")))
370        .or_else(|| Some(ident_default_name(config, env)).filter(|name| !name.is_empty()))
371        .unwrap_or_else(|| "Unknown".to_owned());
372    let email = non_blank(env.var("GIT_COMMITTER_EMAIL"))
373        .or_else(|| non_blank(env.var("GIT_AUTHOR_EMAIL")))
374        .or_else(|| non_blank(config.value("committer.email")))
375        .or_else(|| non_blank(config.value("user.email")))
376        .or_else(|| non_blank(env.var("EMAIL")))
377        .unwrap_or_else(|| synthetic_email_with(env));
378    assemble_identity(&name, &email, None, now)
379}
380
381#[cfg(test)]
382mod tests {
383    use std::collections::HashMap;
384    use std::ffi::OsString;
385
386    use super::*;
387
388    struct MapEnv(HashMap<String, String>);
389
390    impl IdentityEnv for MapEnv {
391        fn var(&self, key: &str) -> Option<String> {
392            self.0.get(key).cloned()
393        }
394
395        fn var_os(&self, key: &str) -> Option<OsString> {
396            self.var(key).map(OsString::from)
397        }
398    }
399
400    #[test]
401    fn strict_email_resolution_fails_without_configured_sources() {
402        let env = MapEnv(HashMap::from([("USER".to_owned(), "alice".to_owned())]));
403        let config = ConfigSet::default();
404        let err = resolve_email_with(&env, &config, IdentRole::Author).expect_err("strict");
405        assert_eq!(
406            err,
407            IdentityError::MissingConfiguredEmail {
408                role: IdentRole::Author
409            }
410        );
411    }
412
413    #[test]
414    fn strict_email_falls_back_to_email_env_unless_config_only() {
415        let env = vars(&[("EMAIL", " mail@example.com ")]);
416        let mut config = ConfigSet::default();
417        assert_eq!(
418            resolve_email_with(&env, &config, IdentRole::Author).expect("EMAIL"),
419            "mail@example.com"
420        );
421        config
422            .add_command_override("user.useConfigOnly", "true")
423            .expect("override");
424        assert_eq!(
425            resolve_email_with(&env, &config, IdentRole::Author).expect_err("config only"),
426            IdentityError::AutoDetectionDisabled {
427                role: IdentRole::Author
428            }
429        );
430        config
431            .add_command_override("author.email", "  ")
432            .expect("override");
433        config
434            .add_command_override("committer.email", "c@example.com")
435            .expect("override");
436        assert_eq!(
437            resolve_email_with(&env, &config, IdentRole::Author).expect("mail given"),
438            "mail@example.com",
439            "a configured email for any role re-enables the EMAIL fallback"
440        );
441    }
442
443    #[test]
444    fn strict_name_keeps_set_but_empty_env_override() {
445        let env = vars(&[("GIT_AUTHOR_NAME", "  "), ("GIT_AUTHOR_EMAIL", "a@b.c")]);
446        let mut config = ConfigSet::default();
447        config
448            .add_command_override("user.name", "Alice")
449            .expect("override");
450        assert_eq!(
451            resolve_name_with(&env, &config, IdentRole::Author).expect_err("empty"),
452            IdentityError::EmptyName {
453                email: "a@b.c".to_owned(),
454                role: IdentRole::Author
455            }
456        );
457        let env = vars(&[("GIT_AUTHOR_EMAIL", "a@b.c")]);
458        config
459            .add_command_override("author.name", " Author Name ")
460            .expect("override");
461        assert_eq!(
462            resolve_name_with(&env, &config, IdentRole::Author).expect("config"),
463            "Author Name"
464        );
465        assert_eq!(
466            resolve_name_with(
467                &vars(&[("GIT_AUTHOR_EMAIL", "a@b.c"), ("GIT_AUTHOR_NAME", ",;")]),
468                &config,
469                IdentRole::Author
470            )
471            .expect_err("crud"),
472            IdentityError::InvalidName {
473                name: ",;".to_owned()
474            }
475        );
476    }
477
478    #[test]
479    fn strict_email_honors_user_email_config() {
480        let env = MapEnv(HashMap::new());
481        let mut config = ConfigSet::default();
482        config
483            .add_command_override("user.email", "me@example.com")
484            .expect("override");
485        let email = resolve_email_with(&env, &config, IdentRole::Committer).expect("configured");
486        assert_eq!(email, "me@example.com");
487    }
488
489    fn vars(pairs: &[(&str, &str)]) -> MapEnv {
490        MapEnv(
491            pairs
492                .iter()
493                .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
494                .collect(),
495        )
496    }
497
498    fn fixed_now() -> OffsetDateTime {
499        OffsetDateTime::from_unix_timestamp(1_112_911_993)
500            .expect("epoch")
501            .to_offset(time::UtcOffset::from_hms(-7, 0, 0).expect("offset"))
502    }
503
504    #[test]
505    fn identity_line_uses_now_without_date_override() {
506        let env = vars(&[
507            ("GIT_AUTHOR_NAME", "A U Thor"),
508            ("GIT_AUTHOR_EMAIL", "author@example.com"),
509        ]);
510        let line =
511            resolve_identity_with(&env, &ConfigSet::default(), IdentRole::Author, fixed_now())
512                .expect("identity");
513        assert_eq!(line, "A U Thor <author@example.com> 1112911993 -0700");
514    }
515
516    #[test]
517    fn identity_line_honours_only_its_own_role_date() {
518        let env = vars(&[
519            ("GIT_AUTHOR_NAME", "A U Thor"),
520            ("GIT_AUTHOR_EMAIL", "author@example.com"),
521            ("GIT_COMMITTER_NAME", "C O Mitter"),
522            ("GIT_COMMITTER_EMAIL", "committer@example.com"),
523            ("GIT_COMMITTER_DATE", "@1234567890 +0100"),
524        ]);
525        let config = ConfigSet::default();
526        let committer = resolve_identity_with(&env, &config, IdentRole::Committer, fixed_now())
527            .expect("committer");
528        assert_eq!(
529            committer,
530            "C O Mitter <committer@example.com> 1234567890 +0100"
531        );
532        let author =
533            resolve_identity_with(&env, &config, IdentRole::Author, fixed_now()).expect("author");
534        assert_eq!(author, "A U Thor <author@example.com> 1112911993 -0700");
535    }
536
537    #[test]
538    fn identity_line_treats_blank_date_override_as_unset() {
539        let env = vars(&[
540            ("GIT_AUTHOR_NAME", "A U Thor"),
541            ("GIT_AUTHOR_EMAIL", "author@example.com"),
542            ("GIT_AUTHOR_DATE", "  "),
543        ]);
544        let line =
545            resolve_identity_with(&env, &ConfigSet::default(), IdentRole::Author, fixed_now())
546                .expect("identity");
547        assert_eq!(line, "A U Thor <author@example.com> 1112911993 -0700");
548    }
549
550    #[test]
551    fn identity_line_fails_like_strict_email_resolution() {
552        let env = vars(&[("USER", "alice"), ("GIT_AUTHOR_NAME", "Alice")]);
553        let err =
554            resolve_identity_with(&env, &ConfigSet::default(), IdentRole::Author, fixed_now())
555                .expect_err("no configured email");
556        assert_eq!(
557            err,
558            IdentityError::MissingConfiguredEmail {
559                role: IdentRole::Author
560            }
561        );
562    }
563
564    #[test]
565    fn signature_matches_identity_line_and_honours_role_date() {
566        let env = vars(&[
567            ("GIT_COMMITTER_NAME", "C O Mitter"),
568            ("GIT_COMMITTER_EMAIL", "committer@example.com"),
569            ("GIT_COMMITTER_DATE", "@1234567890 +0100"),
570        ]);
571        let config = ConfigSet::default();
572        let sig = resolve_signature_with(&env, &config, IdentRole::Committer, fixed_now())
573            .expect("signature");
574        assert_eq!(sig.name, "C O Mitter");
575        assert_eq!(sig.email, "committer@example.com");
576        assert_eq!(
577            sig.header_line(),
578            resolve_identity_with(&env, &config, IdentRole::Committer, fixed_now()).expect("line")
579        );
580    }
581
582    #[test]
583    fn signature_rejects_unparsable_date_and_unwritable_email() {
584        let env = vars(&[
585            ("GIT_AUTHOR_NAME", "A U Thor"),
586            ("GIT_AUTHOR_EMAIL", "author@example.com"),
587            ("GIT_AUTHOR_DATE", "not a date"),
588        ]);
589        assert_eq!(
590            resolve_signature_with(&env, &ConfigSet::default(), IdentRole::Author, fixed_now()),
591            Err(IdentityError::InvalidDate {
592                date: "not a date".to_owned(),
593                role: IdentRole::Author,
594            })
595        );
596        let env = vars(&[
597            ("GIT_AUTHOR_NAME", "A U Thor"),
598            ("GIT_AUTHOR_EMAIL", "a@b> x"),
599        ]);
600        assert!(matches!(
601            resolve_signature_with(&env, &ConfigSet::default(), IdentRole::Author, fixed_now()),
602            Err(IdentityError::InvalidSignature(_))
603        ));
604        let env = vars(&[("USER", "alice"), ("GIT_AUTHOR_NAME", "Alice")]);
605        assert_eq!(
606            resolve_signature_with(&env, &ConfigSet::default(), IdentRole::Author, fixed_now()),
607            Err(IdentityError::MissingConfiguredEmail {
608                role: IdentRole::Author
609            })
610        );
611    }
612
613    #[test]
614    fn loose_committer_identity_never_fails_and_ignores_date_override() {
615        let env = vars(&[
616            ("USER", "alice"),
617            ("HOSTNAME", "host.example"),
618            ("GIT_COMMITTER_DATE", "@1234567890 +0100"),
619        ]);
620        let mut config = ConfigSet::default();
621        config
622            .add_command_override("user.name", "Alice")
623            .expect("override");
624        let line = resolve_loose_committer_identity_with(&env, &config, fixed_now());
625        assert_eq!(line, "Alice <alice@host.example> 1112911993 -0700");
626    }
627
628    #[test]
629    fn loose_committer_identity_prefers_committer_then_author_env() {
630        let env = vars(&[
631            ("GIT_COMMITTER_NAME", "C O Mitter"),
632            ("GIT_AUTHOR_NAME", "A U Thor"),
633            ("GIT_COMMITTER_EMAIL", " "),
634            ("GIT_AUTHOR_EMAIL", "author@example.com"),
635        ]);
636        let line = resolve_loose_committer_identity_with(&env, &ConfigSet::default(), fixed_now());
637        assert_eq!(line, "C O Mitter <author@example.com> 1112911993 -0700");
638
639        let env = vars(&[("GIT_AUTHOR_NAME", "A U Thor"), ("EMAIL", "e@example.com")]);
640        let line = resolve_loose_committer_identity_with(&env, &ConfigSet::default(), fixed_now());
641        assert_eq!(line, "A U Thor <e@example.com> 1112911993 -0700");
642    }
643
644    #[test]
645    fn loose_committer_identity_empty_committer_name_skips_author_env() {
646        let env = vars(&[
647            ("GIT_COMMITTER_NAME", ""),
648            ("GIT_AUTHOR_NAME", "A U Thor"),
649            ("USER", "alice"),
650            ("HOSTNAME", "box"),
651        ]);
652        let mut config = ConfigSet::default();
653        config
654            .add_command_override("user.name", "User Name")
655            .expect("override");
656        config
657            .add_command_override("committer.name", " Committer Name ")
658            .expect("override");
659        config
660            .add_command_override("user.email", "user@example.com")
661            .expect("override");
662        let line = resolve_loose_committer_identity_with(&env, &config, fixed_now());
663        assert_eq!(line, "Committer Name <user@example.com> 1112911993 -0700");
664
665        let mut config = ConfigSet::default();
666        config
667            .add_command_override("user.name", "User Name")
668            .expect("override");
669        let line = resolve_loose_committer_identity_with(&env, &config, fixed_now());
670        assert_eq!(line, "User Name <alice@box.(none)> 1112911993 -0700");
671    }
672
673    #[test]
674    fn env_date_key_matches_role() {
675        assert_eq!(IdentRole::Author.env_date_key(), "GIT_AUTHOR_DATE");
676        assert_eq!(IdentRole::Committer.env_date_key(), "GIT_COMMITTER_DATE");
677    }
678}