vergen_git2/git2/
mod.rs

1// Copyright (c) 2022 pud developers
2//
3// Licensed under the Apache License, Version 2.0
4// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0> or the MIT
5// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. All files in the project carrying such notice may not be copied,
7// modified, or distributed except according to those terms.
8
9#[cfg(test)]
10use anyhow::anyhow;
11use anyhow::{Error, Result};
12use derive_builder::Builder as DeriveBuilder;
13use git2_rs::{
14    BranchType, Commit, DescribeFormatOptions, DescribeOptions, Reference, Repository,
15    StatusOptions,
16};
17use std::{
18    env::{self, VarError},
19    path::{Path, PathBuf},
20    str::FromStr,
21};
22use time::{
23    format_description::{self, well_known::Iso8601},
24    OffsetDateTime, UtcOffset,
25};
26use vergen_lib::{
27    add_default_map_entry, add_map_entry,
28    constants::{
29        GIT_BRANCH_NAME, GIT_COMMIT_AUTHOR_EMAIL, GIT_COMMIT_AUTHOR_NAME, GIT_COMMIT_COUNT,
30        GIT_COMMIT_DATE_NAME, GIT_COMMIT_MESSAGE, GIT_COMMIT_TIMESTAMP_NAME, GIT_DESCRIBE_NAME,
31        GIT_DIRTY_NAME, GIT_SHA_NAME,
32    },
33    AddEntries, CargoRerunIfChanged, CargoRustcEnvMap, CargoWarning, DefaultConfig, VergenKey,
34};
35
36/// The `VERGEN_GIT_*` configuration features
37///
38/// | Variable | Sample |
39/// | -------  | ------ |
40/// | `VERGEN_GIT_BRANCH` | feature/fun |
41/// | `VERGEN_GIT_COMMIT_AUTHOR_EMAIL` | janedoe@email.com |
42/// | `VERGEN_GIT_COMMIT_AUTHOR_NAME` | Jane Doe |
43/// | `VERGEN_GIT_COMMIT_COUNT` | 330 |
44/// | `VERGEN_GIT_COMMIT_DATE` | 2021-02-24 |
45/// | `VERGEN_GIT_COMMIT_MESSAGE` | feat: add commit messages |
46/// | `VERGEN_GIT_COMMIT_TIMESTAMP` | 2021-02-24T20:55:21+00:00 |
47/// | `VERGEN_GIT_DESCRIBE` | 5.0.0-2-gf49246c |
48/// | `VERGEN_GIT_SHA` | f49246ce334567bff9f950bfd0f3078184a2738a |
49/// | `VERGEN_GIT_DIRTY` | true |
50///
51/// # Example
52///
53/// ```
54/// # use anyhow::Result;
55/// # use vergen_git2::{Emitter, Git2Builder};
56/// #
57/// # fn main() -> Result<()> {
58/// let git2 = Git2Builder::all_git()?;
59/// Emitter::default().add_instructions(&git2)?.emit()?;
60/// #   Ok(())
61/// # }
62/// ```
63///
64/// Override output with your own value
65///
66/// ```
67/// # use anyhow::Result;
68/// # use vergen_git2::{Emitter, Git2Builder};
69/// #
70/// # fn main() -> Result<()> {
71/// temp_env::with_var("VERGEN_GIT_BRANCH", Some("this is the branch I want output"), || {
72///     let result = || -> Result<()> {
73///         let git2 = Git2Builder::all_git()?;
74///         Emitter::default().add_instructions(&git2)?.emit()?;
75///         Ok(())
76///     }();
77///     assert!(result.is_ok());
78/// });
79/// #   Ok(())
80/// # }
81/// ```
82///
83#[derive(Clone, Debug, DeriveBuilder, PartialEq)]
84#[allow(clippy::struct_excessive_bools)]
85pub struct Git2 {
86    /// An optional path to a repository.
87    #[builder(default = "None")]
88    repo_path: Option<PathBuf>,
89    /// Emit the current git branch
90    ///
91    /// ```text
92    /// cargo:rustc-env=VERGEN_GIT_BRANCH=<BRANCH_NAME>
93    /// ```
94    ///
95    #[builder(default = "false")]
96    branch: bool,
97    /// Emit the author email of the most recent commit
98    ///
99    /// ```text
100    /// cargo:rustc-env=VERGEN_GIT_COMMIT_AUTHOR_EMAIL=<AUTHOR_EMAIL>
101    /// ```
102    ///
103    #[builder(default = "false")]
104    commit_author_name: bool,
105    /// Emit the author name of the most recent commit
106    ///
107    /// ```text
108    /// cargo:rustc-env=VERGEN_GIT_COMMIT_AUTHOR_NAME=<AUTHOR_NAME>
109    /// ```
110    ///
111    #[builder(default = "false")]
112    commit_author_email: bool,
113    /// Emit the total commit count to HEAD
114    ///
115    /// ```text
116    /// cargo:rustc-env=VERGEN_GIT_COMMIT_COUNT=<COUNT>
117    /// ```
118    #[builder(default = "false")]
119    commit_count: bool,
120    /// Emit the commit message of the latest commit
121    ///
122    /// ```text
123    /// cargo:rustc-env=VERGEN_GIT_COMMIT_MESSAGE=<MESSAGE>
124    /// ```
125    ///
126    #[builder(default = "false")]
127    commit_message: bool,
128    /// Emit the commit date of the latest commit
129    ///
130    /// ```text
131    /// cargo:rustc-env=VERGEN_GIT_COMMIT_DATE=<YYYY-MM-DD>
132    /// ```
133    ///
134    #[builder(default = "false")]
135    commit_date: bool,
136    /// Emit the commit timestamp of the latest commit
137    ///
138    /// ```text
139    /// cargo:rustc-env=VERGEN_GIT_COMMIT_TIMESTAMP=<YYYY-MM-DDThh:mm:ssZ>
140    /// ```
141    ///
142    #[builder(default = "false")]
143    commit_timestamp: bool,
144    /// Emit the describe output
145    ///
146    /// ```text
147    /// cargo:rustc-env=VERGEN_GIT_DESCRIBE=<DESCRIBE>
148    /// ```
149    ///
150    /// Optionally, add the `dirty` or `tags` flag to describe.
151    /// See [`git describe`](https://git-scm.com/docs/git-describe#_options) for more details
152    ///
153    #[builder(default = "false", setter(custom))]
154    describe: bool,
155    /// Instead of using only the annotated tags, use any tag found in refs/tags namespace.
156    #[builder(default = "false", private)]
157    describe_tags: bool,
158    /// If the working tree has local modification "-dirty" is appended to it.
159    #[builder(default = "false", private)]
160    describe_dirty: bool,
161    /// Only consider tags matching the given glob pattern, excluding the "refs/tags/" prefix.
162    #[builder(default = "None", private)]
163    describe_match_pattern: Option<&'static str>,
164    /// Emit the SHA of the latest commit
165    ///
166    /// ```text
167    /// cargo:rustc-env=VERGEN_GIT_SHA=<SHA>
168    /// ```
169    ///
170    /// Optionally, add the `short` flag to rev-parse.
171    /// See [`git rev-parse`](https://git-scm.com/docs/git-rev-parse#_options_for_output) for more details.
172    ///
173    #[builder(default = "false", setter(custom))]
174    sha: bool,
175    /// Shortens the object name to a unique prefix
176    #[builder(default = "false", private)]
177    sha_short: bool,
178    /// Emit the dirty state of the git repository
179    /// ```text
180    /// cargo:rustc-env=VERGEN_GIT_DIRTY=(true|false)
181    /// ```
182    ///
183    /// Optionally, include untracked files when determining the dirty status of the repository.
184    ///
185    #[builder(default = "false", setter(custom))]
186    dirty: bool,
187    /// Should we include/ignore untracked files in deciding whether the repository is dirty.
188    #[builder(default = "false", private)]
189    dirty_include_untracked: bool,
190    /// Enable local offset date/timestamp output
191    #[builder(default = "false")]
192    use_local: bool,
193    #[cfg(test)]
194    /// Fail
195    #[builder(default = "false")]
196    fail: bool,
197}
198
199impl Git2Builder {
200    /// Emit all of the `VERGEN_GIT_*` instructions
201    ///
202    /// # Errors
203    /// The underlying build function can error
204    ///
205    pub fn all_git() -> Result<Git2> {
206        Self::default()
207            .branch(true)
208            .commit_author_email(true)
209            .commit_author_name(true)
210            .commit_count(true)
211            .commit_date(true)
212            .commit_message(true)
213            .commit_timestamp(true)
214            .describe(false, false, None)
215            .sha(false)
216            .dirty(false)
217            .build()
218            .map_err(Into::into)
219    }
220
221    /// Convenience method to setup the [`Git2Builder`] with all of the `VERGEN_GIT_*` instructions on
222    pub fn all(&mut self) -> &mut Self {
223        self.branch(true)
224            .commit_author_email(true)
225            .commit_author_name(true)
226            .commit_count(true)
227            .commit_date(true)
228            .commit_message(true)
229            .commit_timestamp(true)
230            .describe(false, false, None)
231            .sha(false)
232            .dirty(false)
233    }
234
235    /// Emit the describe output
236    ///
237    /// ```text
238    /// cargo:rustc-env=VERGEN_GIT_DESCRIBE=<DESCRIBE>
239    /// ```
240    ///
241    /// Optionally, add the `dirty` or `tags` flag to describe.
242    /// See [`git describe`](https://git-scm.com/docs/git-describe#_options) for more details
243    ///
244    pub fn describe(
245        &mut self,
246        tags: bool,
247        dirty: bool,
248        matches: Option<&'static str>,
249    ) -> &mut Self {
250        self.describe = Some(true);
251        let _ = self.describe_tags(tags);
252        let _ = self.describe_dirty(dirty);
253        let _ = self.describe_match_pattern(matches);
254        self
255    }
256
257    /// Emit the dirty state of the git repository
258    /// ```text
259    /// cargo:rustc-env=VERGEN_GIT_DIRTY=(true|false)
260    /// ```
261    ///
262    /// Optionally, include untracked files when determining the dirty status of the repository.
263    ///
264    pub fn dirty(&mut self, include_untracked: bool) -> &mut Self {
265        self.dirty = Some(true);
266        let _ = self.dirty_include_untracked(include_untracked);
267        self
268    }
269
270    /// Emit the SHA of the latest commit
271    ///
272    /// ```text
273    /// cargo:rustc-env=VERGEN_GIT_SHA=<SHA>
274    /// ```
275    ///
276    /// Optionally, add the `short` flag to rev-parse.
277    /// See [`git rev-parse`](https://git-scm.com/docs/git-rev-parse#_options_for_output) for more details.
278    ///
279    pub fn sha(&mut self, short: bool) -> &mut Self {
280        self.sha = Some(true);
281        let _ = self.sha_short(short);
282        self
283    }
284}
285
286impl Git2 {
287    fn any(&self) -> bool {
288        self.branch
289            || self.commit_author_email
290            || self.commit_author_name
291            || self.commit_count
292            || self.commit_date
293            || self.commit_message
294            || self.commit_timestamp
295            || self.describe
296            || self.sha
297            || self.dirty
298    }
299
300    /// Use the repository location at the given path to determine the git instruction output.
301    pub fn at_path(&mut self, path: PathBuf) -> &mut Self {
302        self.repo_path = Some(path);
303        self
304    }
305
306    #[cfg(test)]
307    pub(crate) fn fail(&mut self) -> &mut Self {
308        self.fail = true;
309        self
310    }
311
312    #[cfg(not(test))]
313    fn add_entries(
314        &self,
315        idempotent: bool,
316        cargo_rustc_env: &mut CargoRustcEnvMap,
317        cargo_rerun_if_changed: &mut CargoRerunIfChanged,
318        cargo_warning: &mut CargoWarning,
319    ) -> Result<()> {
320        self.inner_add_entries(
321            idempotent,
322            cargo_rustc_env,
323            cargo_rerun_if_changed,
324            cargo_warning,
325        )
326    }
327
328    #[cfg(test)]
329    fn add_entries(
330        &self,
331        idempotent: bool,
332        cargo_rustc_env: &mut CargoRustcEnvMap,
333        cargo_rerun_if_changed: &mut CargoRerunIfChanged,
334        cargo_warning: &mut CargoWarning,
335    ) -> Result<()> {
336        if self.fail {
337            return Err(anyhow!("failed to create entries"));
338        }
339        self.inner_add_entries(
340            idempotent,
341            cargo_rustc_env,
342            cargo_rerun_if_changed,
343            cargo_warning,
344        )
345    }
346
347    #[allow(clippy::too_many_lines)]
348    fn inner_add_entries(
349        &self,
350        idempotent: bool,
351        cargo_rustc_env: &mut CargoRustcEnvMap,
352        cargo_rerun_if_changed: &mut CargoRerunIfChanged,
353        cargo_warning: &mut CargoWarning,
354    ) -> Result<()> {
355        let repo_dir = if let Some(path) = &self.repo_path {
356            path.clone()
357        } else {
358            env::current_dir()?
359        };
360        let repo = Repository::discover(repo_dir)?;
361        let ref_head = repo.find_reference("HEAD")?;
362        let git_path = repo.path().to_path_buf();
363        let commit = ref_head.peel_to_commit()?;
364
365        if !idempotent && self.any() {
366            Self::add_rerun_if_changed(&ref_head, &git_path, cargo_rerun_if_changed);
367        }
368
369        if self.branch {
370            if let Ok(_value) = env::var(GIT_BRANCH_NAME) {
371                add_default_map_entry(VergenKey::GitBranch, cargo_rustc_env, cargo_warning);
372            } else {
373                Self::add_branch_name(false, &repo, cargo_rustc_env, cargo_warning)?;
374            }
375        }
376
377        if self.commit_author_email {
378            if let Ok(_value) = env::var(GIT_COMMIT_AUTHOR_EMAIL) {
379                add_default_map_entry(
380                    VergenKey::GitCommitAuthorEmail,
381                    cargo_rustc_env,
382                    cargo_warning,
383                );
384            } else {
385                Self::add_opt_value(
386                    commit.author().email(),
387                    VergenKey::GitCommitAuthorEmail,
388                    cargo_rustc_env,
389                    cargo_warning,
390                );
391            }
392        }
393
394        if self.commit_author_name {
395            if let Ok(_value) = env::var(GIT_COMMIT_AUTHOR_NAME) {
396                add_default_map_entry(
397                    VergenKey::GitCommitAuthorName,
398                    cargo_rustc_env,
399                    cargo_warning,
400                );
401            } else {
402                Self::add_opt_value(
403                    commit.author().name(),
404                    VergenKey::GitCommitAuthorName,
405                    cargo_rustc_env,
406                    cargo_warning,
407                );
408            }
409        }
410
411        if self.commit_count {
412            if let Ok(_value) = env::var(GIT_COMMIT_COUNT) {
413                add_default_map_entry(VergenKey::GitCommitCount, cargo_rustc_env, cargo_warning);
414            } else {
415                Self::add_commit_count(false, &repo, cargo_rustc_env, cargo_warning);
416            }
417        }
418
419        self.add_git_timestamp_entries(&commit, idempotent, cargo_rustc_env, cargo_warning)?;
420
421        if self.commit_message {
422            if let Ok(_value) = env::var(GIT_COMMIT_MESSAGE) {
423                add_default_map_entry(VergenKey::GitCommitMessage, cargo_rustc_env, cargo_warning);
424            } else {
425                Self::add_opt_value(
426                    commit.message(),
427                    VergenKey::GitCommitMessage,
428                    cargo_rustc_env,
429                    cargo_warning,
430                );
431            }
432        }
433
434        if self.sha {
435            if let Ok(_value) = env::var(GIT_SHA_NAME) {
436                add_default_map_entry(VergenKey::GitSha, cargo_rustc_env, cargo_warning);
437            } else if self.sha_short {
438                let obj = repo.revparse_single("HEAD")?;
439                Self::add_opt_value(
440                    obj.short_id()?.as_str(),
441                    VergenKey::GitSha,
442                    cargo_rustc_env,
443                    cargo_warning,
444                );
445            } else {
446                add_map_entry(VergenKey::GitSha, commit.id().to_string(), cargo_rustc_env);
447            }
448        }
449
450        if self.dirty {
451            if let Ok(_value) = env::var(GIT_DIRTY_NAME) {
452                add_default_map_entry(VergenKey::GitDirty, cargo_rustc_env, cargo_warning);
453            } else {
454                let mut status_options = StatusOptions::new();
455
456                _ = status_options.include_untracked(self.dirty_include_untracked);
457                let statuses = repo.statuses(Some(&mut status_options))?;
458
459                let n_dirty = statuses
460                    .iter()
461                    .filter(|each_status| !each_status.status().is_ignored())
462                    .count();
463
464                add_map_entry(
465                    VergenKey::GitDirty,
466                    format!("{}", n_dirty > 0),
467                    cargo_rustc_env,
468                );
469            }
470        }
471
472        if self.describe {
473            if let Ok(_value) = env::var(GIT_DESCRIBE_NAME) {
474                add_default_map_entry(VergenKey::GitDescribe, cargo_rustc_env, cargo_warning);
475            } else {
476                let mut describe_opts = DescribeOptions::new();
477                let mut format_opts = DescribeFormatOptions::new();
478
479                _ = describe_opts.show_commit_oid_as_fallback(true);
480
481                if self.describe_dirty {
482                    _ = format_opts.dirty_suffix("-dirty");
483                }
484
485                if self.describe_tags {
486                    _ = describe_opts.describe_tags();
487                }
488
489                if let Some(pattern) = self.describe_match_pattern {
490                    _ = describe_opts.pattern(pattern);
491                }
492
493                let describe = repo
494                    .describe(&describe_opts)
495                    .map(|x| x.format(Some(&format_opts)).map_err(Error::from))??;
496                add_map_entry(VergenKey::GitDescribe, describe, cargo_rustc_env);
497            }
498        }
499
500        Ok(())
501    }
502
503    fn add_rerun_if_changed(
504        ref_head: &Reference<'_>,
505        git_path: &Path,
506        cargo_rerun_if_changed: &mut CargoRerunIfChanged,
507    ) {
508        // Setup the head path
509        let mut head_path = git_path.to_path_buf();
510        head_path.push("HEAD");
511
512        // Check whether the path exists in the filesystem before emitting it
513        if head_path.exists() {
514            cargo_rerun_if_changed.push(format!("{}", head_path.display()));
515        }
516
517        if let Ok(resolved) = ref_head.resolve() {
518            if let Some(name) = resolved.name() {
519                let ref_path = git_path.to_path_buf();
520                let path = ref_path.join(name);
521                // Check whether the path exists in the filesystem before emitting it
522                if path.exists() {
523                    cargo_rerun_if_changed.push(format!("{}", path.display()));
524                }
525            }
526        }
527    }
528
529    fn add_branch_name(
530        add_default: bool,
531        repo: &Repository,
532        cargo_rustc_env: &mut CargoRustcEnvMap,
533        cargo_warning: &mut CargoWarning,
534    ) -> Result<()> {
535        if repo.head_detached()? {
536            if add_default {
537                add_default_map_entry(VergenKey::GitBranch, cargo_rustc_env, cargo_warning);
538            } else {
539                add_map_entry(VergenKey::GitBranch, "HEAD", cargo_rustc_env);
540            }
541        } else {
542            let locals = repo.branches(Some(BranchType::Local))?;
543            let mut found_head = false;
544            for (local, _bt) in locals.filter_map(std::result::Result::ok) {
545                if local.is_head() {
546                    if let Some(name) = local.name()? {
547                        add_map_entry(VergenKey::GitBranch, name, cargo_rustc_env);
548                        found_head = !add_default;
549                        break;
550                    }
551                }
552            }
553            if !found_head {
554                add_default_map_entry(VergenKey::GitBranch, cargo_rustc_env, cargo_warning);
555            }
556        }
557        Ok(())
558    }
559
560    #[allow(clippy::map_unwrap_or)]
561    fn add_opt_value(
562        value: Option<&str>,
563        key: VergenKey,
564        cargo_rustc_env: &mut CargoRustcEnvMap,
565        cargo_warning: &mut CargoWarning,
566    ) {
567        value
568            .map(|val| add_map_entry(key, val, cargo_rustc_env))
569            .unwrap_or_else(|| add_default_map_entry(key, cargo_rustc_env, cargo_warning));
570    }
571
572    fn add_commit_count(
573        add_default: bool,
574        repo: &Repository,
575        cargo_rustc_env: &mut CargoRustcEnvMap,
576        cargo_warning: &mut CargoWarning,
577    ) {
578        let key = VergenKey::GitCommitCount;
579        if !add_default {
580            if let Ok(mut revwalk) = repo.revwalk() {
581                if revwalk.push_head().is_ok() {
582                    add_map_entry(key, revwalk.count().to_string(), cargo_rustc_env);
583                    return;
584                }
585            }
586        }
587        add_default_map_entry(key, cargo_rustc_env, cargo_warning);
588    }
589
590    fn add_git_timestamp_entries(
591        &self,
592        commit: &Commit<'_>,
593        idempotent: bool,
594        cargo_rustc_env: &mut CargoRustcEnvMap,
595        cargo_warning: &mut CargoWarning,
596    ) -> Result<()> {
597        let (sde, ts) = match env::var("SOURCE_DATE_EPOCH") {
598            Ok(v) => (
599                true,
600                OffsetDateTime::from_unix_timestamp(i64::from_str(&v)?)?,
601            ),
602            Err(VarError::NotPresent) => self.compute_local_offset(commit)?,
603            Err(e) => return Err(e.into()),
604        };
605
606        if let Ok(_value) = env::var(GIT_COMMIT_DATE_NAME) {
607            add_default_map_entry(VergenKey::GitCommitDate, cargo_rustc_env, cargo_warning);
608        } else {
609            self.add_git_date_entry(idempotent, sde, &ts, cargo_rustc_env, cargo_warning)?;
610        }
611        if let Ok(_value) = env::var(GIT_COMMIT_TIMESTAMP_NAME) {
612            add_default_map_entry(
613                VergenKey::GitCommitTimestamp,
614                cargo_rustc_env,
615                cargo_warning,
616            );
617        } else {
618            self.add_git_timestamp_entry(idempotent, sde, &ts, cargo_rustc_env, cargo_warning)?;
619        }
620        Ok(())
621    }
622
623    #[cfg_attr(coverage_nightly, coverage(off))]
624    // this in not included in coverage, because on *nix the local offset is always unsafe
625    fn compute_local_offset(&self, commit: &Commit<'_>) -> Result<(bool, OffsetDateTime)> {
626        let no_offset = OffsetDateTime::from_unix_timestamp(commit.time().seconds())?;
627        if self.use_local {
628            let local = UtcOffset::local_offset_at(no_offset)?;
629            let local_offset = no_offset.checked_to_offset(local).unwrap_or(no_offset);
630            Ok((false, local_offset))
631        } else {
632            Ok((false, no_offset))
633        }
634    }
635
636    fn add_git_date_entry(
637        &self,
638        idempotent: bool,
639        source_date_epoch: bool,
640        ts: &OffsetDateTime,
641        cargo_rustc_env: &mut CargoRustcEnvMap,
642        cargo_warning: &mut CargoWarning,
643    ) -> Result<()> {
644        if self.commit_date {
645            if idempotent && !source_date_epoch {
646                add_default_map_entry(VergenKey::GitCommitDate, cargo_rustc_env, cargo_warning);
647            } else {
648                let format = format_description::parse("[year]-[month]-[day]")?;
649                add_map_entry(
650                    VergenKey::GitCommitDate,
651                    ts.format(&format)?,
652                    cargo_rustc_env,
653                );
654            }
655        }
656        Ok(())
657    }
658
659    fn add_git_timestamp_entry(
660        &self,
661        idempotent: bool,
662        source_date_epoch: bool,
663        ts: &OffsetDateTime,
664        cargo_rustc_env: &mut CargoRustcEnvMap,
665        cargo_warning: &mut CargoWarning,
666    ) -> Result<()> {
667        if self.commit_timestamp {
668            if idempotent && !source_date_epoch {
669                add_default_map_entry(
670                    VergenKey::GitCommitTimestamp,
671                    cargo_rustc_env,
672                    cargo_warning,
673                );
674            } else {
675                add_map_entry(
676                    VergenKey::GitCommitTimestamp,
677                    ts.format(&Iso8601::DEFAULT)?,
678                    cargo_rustc_env,
679                );
680            }
681        }
682        Ok(())
683    }
684}
685
686impl AddEntries for Git2 {
687    fn add_map_entries(
688        &self,
689        idempotent: bool,
690        cargo_rustc_env: &mut CargoRustcEnvMap,
691        cargo_rerun_if_changed: &mut CargoRerunIfChanged,
692        cargo_warning: &mut CargoWarning,
693    ) -> Result<()> {
694        if self.any() {
695            self.add_entries(
696                idempotent,
697                cargo_rustc_env,
698                cargo_rerun_if_changed,
699                cargo_warning,
700            )?;
701        }
702        Ok(())
703    }
704
705    fn add_default_entries(
706        &self,
707        config: &DefaultConfig,
708        cargo_rustc_env_map: &mut CargoRustcEnvMap,
709        cargo_rerun_if_changed: &mut CargoRerunIfChanged,
710        cargo_warning: &mut CargoWarning,
711    ) -> Result<()> {
712        if *config.fail_on_error() {
713            let error = Error::msg(format!("{}", config.error()));
714            Err(error)
715        } else {
716            // Clear any previous warnings.  This should be it.
717            cargo_warning.clear();
718            cargo_rerun_if_changed.clear();
719
720            cargo_warning.push(format!("{}", config.error()));
721
722            if self.branch {
723                add_default_map_entry(VergenKey::GitBranch, cargo_rustc_env_map, cargo_warning);
724            }
725            if self.commit_author_email {
726                add_default_map_entry(
727                    VergenKey::GitCommitAuthorEmail,
728                    cargo_rustc_env_map,
729                    cargo_warning,
730                );
731            }
732            if self.commit_author_name {
733                add_default_map_entry(
734                    VergenKey::GitCommitAuthorName,
735                    cargo_rustc_env_map,
736                    cargo_warning,
737                );
738            }
739            if self.commit_count {
740                add_default_map_entry(
741                    VergenKey::GitCommitCount,
742                    cargo_rustc_env_map,
743                    cargo_warning,
744                );
745            }
746            if self.commit_date {
747                add_default_map_entry(VergenKey::GitCommitDate, cargo_rustc_env_map, cargo_warning);
748            }
749            if self.commit_message {
750                add_default_map_entry(
751                    VergenKey::GitCommitMessage,
752                    cargo_rustc_env_map,
753                    cargo_warning,
754                );
755            }
756            if self.commit_timestamp {
757                add_default_map_entry(
758                    VergenKey::GitCommitTimestamp,
759                    cargo_rustc_env_map,
760                    cargo_warning,
761                );
762            }
763            if self.describe {
764                add_default_map_entry(VergenKey::GitDescribe, cargo_rustc_env_map, cargo_warning);
765            }
766            if self.sha {
767                add_default_map_entry(VergenKey::GitSha, cargo_rustc_env_map, cargo_warning);
768            }
769            if self.dirty {
770                add_default_map_entry(VergenKey::GitDirty, cargo_rustc_env_map, cargo_warning);
771            }
772            Ok(())
773        }
774    }
775}
776
777#[cfg(test)]
778mod test {
779    use super::{Git2, Git2Builder};
780    use anyhow::Result;
781    use git2_rs::Repository;
782    use serial_test::serial;
783    use std::{collections::BTreeMap, env::current_dir, io::Write};
784    use test_util::TestRepos;
785    use vergen::Emitter;
786    use vergen_lib::{count_idempotent, VergenKey};
787
788    #[test]
789    #[serial]
790    #[allow(clippy::clone_on_copy, clippy::redundant_clone)]
791    fn git2_clone_works() -> Result<()> {
792        let git2 = Git2Builder::all_git()?;
793        let another = git2.clone();
794        assert_eq!(another, git2);
795        Ok(())
796    }
797
798    #[test]
799    #[serial]
800    fn git2_debug_works() -> Result<()> {
801        let git2 = Git2Builder::all_git()?;
802        let mut buf = vec![];
803        write!(buf, "{git2:?}")?;
804        assert!(!buf.is_empty());
805        Ok(())
806    }
807
808    #[test]
809    #[serial]
810    fn git2_default() -> Result<()> {
811        let git2 = Git2Builder::default().build()?;
812        let emitter = Emitter::default().add_instructions(&git2)?.test_emit();
813        assert_eq!(0, emitter.cargo_rustc_env_map().len());
814        assert_eq!(0, count_idempotent(emitter.cargo_rustc_env_map()));
815        assert_eq!(0, emitter.cargo_warning().len());
816        Ok(())
817    }
818
819    #[test]
820    #[serial]
821    fn empty_email_is_default() -> Result<()> {
822        let mut cargo_rustc_env = BTreeMap::new();
823        let mut cargo_warning = vec![];
824        Git2::add_opt_value(
825            None,
826            VergenKey::GitCommitAuthorEmail,
827            &mut cargo_rustc_env,
828            &mut cargo_warning,
829        );
830        assert_eq!(1, cargo_rustc_env.len());
831        assert_eq!(1, cargo_warning.len());
832        Ok(())
833    }
834
835    #[test]
836    #[serial]
837    fn bad_revwalk_is_default() -> Result<()> {
838        let mut cargo_rustc_env = BTreeMap::new();
839        let mut cargo_warning = vec![];
840        let repo = Repository::discover(current_dir()?)?;
841        Git2::add_commit_count(true, &repo, &mut cargo_rustc_env, &mut cargo_warning);
842        assert_eq!(1, cargo_rustc_env.len());
843        assert_eq!(1, cargo_warning.len());
844        Ok(())
845    }
846
847    #[test]
848    #[serial]
849    fn head_not_found_is_default() -> Result<()> {
850        let test_repo = TestRepos::new(false, false, false)?;
851        let mut map = BTreeMap::new();
852        let mut cargo_warning = vec![];
853        let repo = Repository::discover(current_dir()?)?;
854        Git2::add_branch_name(true, &repo, &mut map, &mut cargo_warning)?;
855        assert_eq!(1, map.len());
856        assert_eq!(1, cargo_warning.len());
857        let mut map = BTreeMap::new();
858        let mut cargo_warning = vec![];
859        let repo = Repository::discover(test_repo.path())?;
860        Git2::add_branch_name(true, &repo, &mut map, &mut cargo_warning)?;
861        assert_eq!(1, map.len());
862        assert_eq!(1, cargo_warning.len());
863        Ok(())
864    }
865
866    #[test]
867    #[serial]
868    fn git_all_idempotent() -> Result<()> {
869        let git2 = Git2Builder::all_git()?;
870        let emitter = Emitter::default()
871            .idempotent()
872            .add_instructions(&git2)?
873            .test_emit();
874        assert_eq!(10, emitter.cargo_rustc_env_map().len());
875        assert_eq!(2, count_idempotent(emitter.cargo_rustc_env_map()));
876        assert_eq!(2, emitter.cargo_warning().len());
877        Ok(())
878    }
879
880    #[test]
881    #[serial]
882    fn git_all_shallow_clone() -> Result<()> {
883        let repo = TestRepos::new(false, false, true)?;
884        let mut git2 = Git2Builder::all_git()?;
885        let _ = git2.at_path(repo.path());
886        let emitter = Emitter::default().add_instructions(&git2)?.test_emit();
887        assert_eq!(10, emitter.cargo_rustc_env_map().len());
888        assert_eq!(0, count_idempotent(emitter.cargo_rustc_env_map()));
889        assert_eq!(0, emitter.cargo_warning().len());
890        Ok(())
891    }
892
893    #[test]
894    #[serial]
895    fn git_all_idempotent_no_warn() -> Result<()> {
896        let git2 = Git2Builder::all_git()?;
897        let emitter = Emitter::default()
898            .idempotent()
899            .quiet()
900            .add_instructions(&git2)?
901            .test_emit();
902
903        assert_eq!(10, emitter.cargo_rustc_env_map().len());
904        assert_eq!(2, count_idempotent(emitter.cargo_rustc_env_map()));
905        assert_eq!(2, emitter.cargo_warning().len());
906        Ok(())
907    }
908
909    #[test]
910    #[serial]
911    fn git_all() -> Result<()> {
912        let git2 = Git2Builder::all_git()?;
913        let emitter = Emitter::default().add_instructions(&git2)?.test_emit();
914        assert_eq!(10, emitter.cargo_rustc_env_map().len());
915        assert_eq!(0, count_idempotent(emitter.cargo_rustc_env_map()));
916        assert_eq!(0, emitter.cargo_warning().len());
917        Ok(())
918    }
919
920    #[test]
921    #[serial]
922    fn git_error_fails() -> Result<()> {
923        let mut git2 = Git2Builder::all_git()?;
924        let _ = git2.fail();
925        assert!(Emitter::default()
926            .fail_on_error()
927            .add_instructions(&git2)
928            .is_err());
929        Ok(())
930    }
931
932    #[test]
933    #[serial]
934    fn git_error_defaults() -> Result<()> {
935        let mut git2 = Git2Builder::all_git()?;
936        let _ = git2.fail();
937        let emitter = Emitter::default().add_instructions(&git2)?.test_emit();
938        assert_eq!(10, emitter.cargo_rustc_env_map().len());
939        assert_eq!(10, count_idempotent(emitter.cargo_rustc_env_map()));
940        assert_eq!(11, emitter.cargo_warning().len());
941        Ok(())
942    }
943
944    #[test]
945    #[serial]
946    fn source_date_epoch_works() {
947        temp_env::with_var("SOURCE_DATE_EPOCH", Some("1671809360"), || {
948            let result = || -> Result<()> {
949                let mut stdout_buf = vec![];
950                let gix = Git2Builder::default()
951                    .commit_date(true)
952                    .commit_timestamp(true)
953                    .build()?;
954                _ = Emitter::new()
955                    .idempotent()
956                    .add_instructions(&gix)?
957                    .emit_to(&mut stdout_buf)?;
958                let output = String::from_utf8_lossy(&stdout_buf);
959                for (idx, line) in output.lines().enumerate() {
960                    if idx == 0 {
961                        assert_eq!("cargo:rustc-env=VERGEN_GIT_COMMIT_DATE=2022-12-23", line);
962                    } else if idx == 1 {
963                        assert_eq!(
964                            "cargo:rustc-env=VERGEN_GIT_COMMIT_TIMESTAMP=2022-12-23T15:29:20.000000000Z",
965                            line
966                        );
967                    }
968                }
969                Ok(())
970            }();
971            assert!(result.is_ok());
972        });
973    }
974
975    #[test]
976    #[serial]
977    #[cfg(unix)]
978    fn bad_source_date_epoch_fails() {
979        use std::ffi::OsStr;
980        use std::os::unix::prelude::OsStrExt;
981
982        let source = [0x66, 0x6f, 0x80, 0x6f];
983        let os_str = OsStr::from_bytes(&source[..]);
984        temp_env::with_var("SOURCE_DATE_EPOCH", Some(os_str), || {
985            let result = || -> Result<bool> {
986                let mut stdout_buf = vec![];
987                let gix = Git2Builder::default().commit_date(true).build()?;
988                Emitter::new()
989                    .idempotent()
990                    .fail_on_error()
991                    .add_instructions(&gix)?
992                    .emit_to(&mut stdout_buf)
993            }();
994            assert!(result.is_err());
995        });
996    }
997
998    #[test]
999    #[serial]
1000    #[cfg(unix)]
1001    fn bad_source_date_epoch_defaults() {
1002        use std::ffi::OsStr;
1003        use std::os::unix::prelude::OsStrExt;
1004
1005        let source = [0x66, 0x6f, 0x80, 0x6f];
1006        let os_str = OsStr::from_bytes(&source[..]);
1007        temp_env::with_var("SOURCE_DATE_EPOCH", Some(os_str), || {
1008            let result = || -> Result<bool> {
1009                let mut stdout_buf = vec![];
1010                let gix = Git2Builder::default().commit_date(true).build()?;
1011                Emitter::new()
1012                    .idempotent()
1013                    .add_instructions(&gix)?
1014                    .emit_to(&mut stdout_buf)
1015            }();
1016            assert!(result.is_ok());
1017        });
1018    }
1019
1020    #[test]
1021    #[serial]
1022    #[cfg(windows)]
1023    fn bad_source_date_epoch_fails() {
1024        use std::ffi::OsString;
1025        use std::os::windows::prelude::OsStringExt;
1026
1027        let source = [0x0066, 0x006f, 0xD800, 0x006f];
1028        let os_string = OsString::from_wide(&source[..]);
1029        let os_str = os_string.as_os_str();
1030        temp_env::with_var("SOURCE_DATE_EPOCH", Some(os_str), || {
1031            let result = || -> Result<bool> {
1032                let mut stdout_buf = vec![];
1033                let gix = Git2Builder::default().commit_date(true).build()?;
1034                Emitter::new()
1035                    .fail_on_error()
1036                    .idempotent()
1037                    .add_instructions(&gix)?
1038                    .emit_to(&mut stdout_buf)
1039            }();
1040            assert!(result.is_err());
1041        });
1042    }
1043
1044    #[test]
1045    #[serial]
1046    #[cfg(windows)]
1047    fn bad_source_date_epoch_defaults() {
1048        use std::ffi::OsString;
1049        use std::os::windows::prelude::OsStringExt;
1050
1051        let source = [0x0066, 0x006f, 0xD800, 0x006f];
1052        let os_string = OsString::from_wide(&source[..]);
1053        let os_str = os_string.as_os_str();
1054        temp_env::with_var("SOURCE_DATE_EPOCH", Some(os_str), || {
1055            let result = || -> Result<bool> {
1056                let mut stdout_buf = vec![];
1057                let gix = Git2Builder::default().commit_date(true).build()?;
1058                Emitter::new()
1059                    .idempotent()
1060                    .add_instructions(&gix)?
1061                    .emit_to(&mut stdout_buf)
1062            }();
1063            assert!(result.is_ok());
1064        });
1065    }
1066}