1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
// Copyright (c) 2022 vergen developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

use anyhow::{anyhow, Error, Result};
use derive_builder::Builder as DeriveBuilder;
use std::{
    env,
    path::PathBuf,
    process::{Command, Output, Stdio},
    str::FromStr,
};
use time::{
    format_description::{
        self,
        well_known::{Iso8601, Rfc3339},
    },
    OffsetDateTime, UtcOffset,
};
use vergen_lib::{
    add_default_map_entry, add_map_entry,
    constants::{
        GIT_BRANCH_NAME, GIT_COMMIT_AUTHOR_EMAIL, GIT_COMMIT_AUTHOR_NAME, GIT_COMMIT_COUNT,
        GIT_COMMIT_DATE_NAME, GIT_COMMIT_MESSAGE, GIT_COMMIT_TIMESTAMP_NAME, GIT_DESCRIBE_NAME,
        GIT_DIRTY_NAME, GIT_SHA_NAME,
    },
    AddEntries, CargoRerunIfChanged, CargoRustcEnvMap, CargoWarning, DefaultConfig, VergenKey,
};

// This funkiness allows the command to be output in the docs
macro_rules! branch_cmd {
    () => {
        "git rev-parse --abbrev-ref --symbolic-full-name HEAD"
    };
}
const BRANCH_CMD: &str = branch_cmd!();
macro_rules! author_email {
    () => {
        "git log -1 --pretty=format:'%ae'"
    };
}
const COMMIT_AUTHOR_EMAIL: &str = author_email!();
macro_rules! author_name {
    () => {
        "git log -1 --pretty=format:'%an'"
    };
}
const COMMIT_AUTHOR_NAME: &str = author_name!();
macro_rules! commit_count {
    () => {
        "git rev-list --count HEAD"
    };
}
const COMMIT_COUNT: &str = commit_count!();
macro_rules! commit_date {
    () => {
        "git log -1 --pretty=format:'%cs'"
    };
}
macro_rules! commit_message {
    () => {
        "git log -1 --format=%s"
    };
}
const COMMIT_MESSAGE: &str = commit_message!();
macro_rules! commit_timestamp {
    () => {
        "git log -1 --pretty=format:'%cI'"
    };
}
const COMMIT_TIMESTAMP: &str = commit_timestamp!();
macro_rules! describe {
    () => {
        "git describe --always"
    };
}
const DESCRIBE: &str = describe!();
macro_rules! sha {
    () => {
        "git rev-parse"
    };
}
const SHA: &str = sha!();
macro_rules! dirty {
    () => {
        "git status --porcelain"
    };
}
const DIRTY: &str = dirty!();

/// The `VERGEN_GIT_*` configuration features
///
/// | Variable | Sample |
/// | -------  | ------ |
/// | `VERGEN_GIT_BRANCH` | feature/fun |
/// | `VERGEN_GIT_COMMIT_AUTHOR_EMAIL` | janedoe@email.com |
/// | `VERGEN_GIT_COMMIT_AUTHOR_NAME` | Jane Doe |
/// | `VERGEN_GIT_COMMIT_COUNT` | 330 |
/// | `VERGEN_GIT_COMMIT_DATE` | 2021-02-24 |
/// | `VERGEN_GIT_COMMIT_MESSAGE` | feat: add commit messages |
/// | `VERGEN_GIT_COMMIT_TIMESTAMP` | 2021-02-24T20:55:21+00:00 |
/// | `VERGEN_GIT_DESCRIBE` | 5.0.0-2-gf49246c |
/// | `VERGEN_GIT_SHA` | f49246ce334567bff9f950bfd0f3078184a2738a |
/// | `VERGEN_GIT_DIRTY` | true |
///
/// # Example
/// Emit all of the git instructions
///
/// ```
/// # use anyhow::Result;
/// # use vergen_gitcl::{Emitter, GitclBuilder};
/// #
/// # fn main() -> Result<()> {
/// let gitcl = GitclBuilder::all_git()?;
/// Emitter::default().add_instructions(&gitcl)?.emit()?;
/// #   Ok(())
/// # }
/// ```
///
/// Emit some of the git instructions
///
/// ```
/// # use anyhow::Result;
/// # use vergen_gitcl::{Emitter, GitclBuilder};
/// #
/// # fn main() -> Result<()> {
/// let gitcl = GitclBuilder::default().describe(true, false, None).build()?;
/// Emitter::default().add_instructions(&gitcl)?.emit()?;
/// #   Ok(())
/// # }
/// ```
///
/// Override output with your own value
///
/// ```
/// # use anyhow::Result;
/// # use vergen_gitcl::{Emitter, GitclBuilder};
/// #
/// # fn main() -> Result<()> {
/// temp_env::with_var("VERGEN_GIT_BRANCH", Some("this is the branch I want output"), || {
///     let result = || -> Result<()> {
///         let gitcl = GitclBuilder::all_git()?;
///         Emitter::default().add_instructions(&gitcl)?.emit()?;
///         Ok(())
///     }();
///     assert!(result.is_ok());
/// });
/// #   Ok(())
/// # }
/// ```
///
/// # Example
/// This feature can also be used in conjuction with the [`SOURCE_DATE_EPOCH`](https://reproducible-builds.org/docs/source-date-epoch/)
/// environment variable to generate deterministic timestamps based off the
/// last modification time of the source/package
///
/// ```
/// # use anyhow::Result;
/// # use vergen_gitcl::{Emitter, GitclBuilder};
/// #
/// # fn main() -> Result<()> {
/// temp_env::with_var("SOURCE_DATE_EPOCH", Some("1671809360"), || {
///     let result = || -> Result<()> {
///         let gitcl = GitclBuilder::all_git()?;
///         Emitter::default().add_instructions(&gitcl)?.emit()?;
///         Ok(())
///     }();
///     assert!(result.is_ok());
/// });
/// #   Ok(())
/// # }
/// ```
///
/// The above will always generate the following output for the timestamp
/// related instructions
///
/// ```text
/// ...
/// cargo:rustc-env=VERGEN_GIT_COMMIT_DATE=2022-12-23
/// ...
/// cargo:rustc-env=VERGEN_GIT_COMMIT_TIMESTAMP=2022-12-23T15:29:20.000000000Z
/// ...
/// ```
///
/// # Example
/// This feature also recognizes the idempotent flag.
///
/// **NOTE** - `SOURCE_DATE_EPOCH` takes precedence over the idempotent flag. If you
/// use both, the output will be based off `SOURCE_DATE_EPOCH`.  This would still be
/// deterministic.
///
/// # Example
/// ```
/// # use anyhow::Result;
/// # use vergen_gitcl::{Emitter, GitclBuilder};
/// #
/// # fn main() -> Result<()> {
/// let gitcl = GitclBuilder::all_git()?;
/// Emitter::default().idempotent().add_instructions(&gitcl)?.emit()?;
/// #   Ok(())
/// # }
/// ```
///
/// The above will always generate the following instructions
///
/// ```text
/// cargo:rustc-env=VERGEN_GIT_BRANCH=VERGEN_IDEMPOTENT_OUTPUT
/// cargo:rustc-env=VERGEN_GIT_COMMIT_AUTHOR_EMAIL=VERGEN_IDEMPOTENT_OUTPUT
/// cargo:rustc-env=VERGEN_GIT_COMMIT_AUTHOR_NAME=VERGEN_IDEMPOTENT_OUTPUT
/// cargo:rustc-env=VERGEN_GIT_COMMIT_COUNT=VERGEN_IDEMPOTENT_OUTPUT
/// cargo:rustc-env=VERGEN_GIT_COMMIT_DATE=VERGEN_IDEMPOTENT_OUTPUT
/// cargo:rustc-env=VERGEN_GIT_COMMIT_MESSAGE=VERGEN_IDEMPOTENT_OUTPUT
/// cargo:rustc-env=VERGEN_GIT_COMMIT_TIMESTAMP=VERGEN_IDEMPOTENT_OUTPUT
/// cargo:rustc-env=VERGEN_GIT_DESCRIBE=VERGEN_IDEMPOTENT_OUTPUT
/// cargo:rustc-env=VERGEN_GIT_SHA=VERGEN_IDEMPOTENT_OUTPUT
/// cargo:warning=VERGEN_GIT_BRANCH set to default
/// cargo:warning=VERGEN_GIT_COMMIT_AUTHOR_EMAIL set to default
/// cargo:warning=VERGEN_GIT_COMMIT_AUTHOR_NAME set to default
/// cargo:warning=VERGEN_GIT_COMMIT_COUNT set to default
/// cargo:warning=VERGEN_GIT_COMMIT_DATE set to default
/// cargo:warning=VERGEN_GIT_COMMIT_MESSAGE set to default
/// cargo:warning=VERGEN_GIT_COMMIT_TIMESTAMP set to default
/// cargo:warning=VERGEN_GIT_DESCRIBE set to default
/// cargo:warning=VERGEN_GIT_SHA set to default
/// cargo:rerun-if-changed=build.rs
/// cargo:rerun-if-env-changed=VERGEN_IDEMPOTENT
/// cargo:rerun-if-env-changed=SOURCE_DATE_EPOCH
/// ```
///
#[derive(Clone, Debug, DeriveBuilder, PartialEq)]
#[allow(clippy::struct_excessive_bools)]
pub struct Gitcl {
    /// An optional path to a repository.
    #[builder(default = "None")]
    repo_path: Option<PathBuf>,
    /// Emit the current git branch
    ///
    /// ```text
    /// cargo:rustc-env=VERGEN_GIT_BRANCH=<BRANCH_NAME>
    /// ```
    ///
    #[builder(default = "false")]
    branch: bool,
    /// Emit the author email of the most recent commit
    ///
    /// ```text
    /// cargo:rustc-env=VERGEN_GIT_COMMIT_AUTHOR_EMAIL=<AUTHOR_EMAIL>
    /// ```
    ///
    #[builder(default = "false")]
    commit_author_name: bool,
    /// Emit the author name of the most recent commit
    ///
    /// ```text
    /// cargo:rustc-env=VERGEN_GIT_COMMIT_AUTHOR_NAME=<AUTHOR_NAME>
    /// ```
    ///
    #[builder(default = "false")]
    commit_author_email: bool,
    /// Emit the total commit count to HEAD
    ///
    /// ```text
    /// cargo:rustc-env=VERGEN_GIT_COMMIT_COUNT=<COUNT>
    /// ```
    #[builder(default = "false")]
    commit_count: bool,
    /// Emit the commit message of the latest commit
    ///
    /// ```text
    /// cargo:rustc-env=VERGEN_GIT_COMMIT_MESSAGE=<MESSAGE>
    /// ```
    ///
    #[builder(default = "false")]
    commit_message: bool,
    /// Emit the commit date of the latest commit
    ///
    /// ```text
    /// cargo:rustc-env=VERGEN_GIT_COMMIT_DATE=<YYYY-MM-DD>
    /// ```
    ///
    /// The value is determined with the following command
    /// ```text
    #[doc = concat!(commit_date!())]
    /// ```
    #[builder(default = "false")]
    commit_date: bool,
    /// Emit the commit timestamp of the latest commit
    ///
    /// ```text
    /// cargo:rustc-env=VERGEN_GIT_COMMIT_TIMESTAMP=<YYYY-MM-DDThh:mm:ssZ>
    /// ```
    ///
    #[builder(default = "false")]
    commit_timestamp: bool,
    /// Emit the describe output
    ///
    /// ```text
    /// cargo:rustc-env=VERGEN_GIT_DESCRIBE=<DESCRIBE>
    /// ```
    ///
    /// Optionally, add the `dirty` or `tags` flag to describe.
    /// See [`git describe`](https://git-scm.com/docs/git-describe#_options) for more details
    ///
    #[builder(default = "false", setter(custom))]
    describe: bool,
    /// Instead of using only the annotated tags, use any tag found in refs/tags namespace.
    #[builder(default = "false", private)]
    describe_tags: bool,
    /// If the working tree has local modification "-dirty" is appended to it.
    #[builder(default = "false", private)]
    describe_dirty: bool,
    /// Only consider tags matching the given glob pattern, excluding the "refs/tags/" prefix.
    #[builder(default = "None", private)]
    describe_match_pattern: Option<&'static str>,
    /// Emit the SHA of the latest commit
    ///
    /// ```text
    /// cargo:rustc-env=VERGEN_GIT_SHA=<SHA>
    /// ```
    ///
    /// Optionally, add the `short` flag to rev-parse.
    /// See [`git rev-parse`](https://git-scm.com/docs/git-rev-parse#_options_for_output) for more details.
    ///
    #[builder(default = "false", setter(custom))]
    sha: bool,
    /// Shortens the object name to a unique prefix
    #[builder(default = "false", private)]
    sha_short: bool,
    /// Emit the dirty state of the git repository
    /// ```text
    /// cargo:rustc-env=VERGEN_GIT_DIRTY=(true|false)
    /// ```
    ///
    /// Optionally, include untracked files when determining the dirty status of the repository.
    ///
    #[builder(default = "false", setter(custom))]
    dirty: bool,
    /// Should we include/ignore untracked files in deciding whether the repository is dirty.
    #[builder(default = "false", private)]
    dirty_include_untracked: bool,
    /// Enable local offset date/timestamp output
    #[builder(default = "false")]
    use_local: bool,
    /// Specify the git cmd you wish to use, i.e. `/usr/bin/git`
    #[builder(default = "None")]
    git_cmd: Option<&'static str>,
}

impl GitclBuilder {
    /// Emit all of the `VERGEN_GIT_*` instructions
    ///
    /// # Errors
    /// The underlying build function can error
    ///
    pub fn all_git() -> Result<Gitcl> {
        Self::default()
            .branch(true)
            .commit_author_email(true)
            .commit_author_name(true)
            .commit_count(true)
            .commit_date(true)
            .commit_message(true)
            .commit_timestamp(true)
            .describe(false, false, None)
            .sha(false)
            .dirty(false)
            .build()
            .map_err(Into::into)
    }

    /// Convenience method to setup the [`GitclBuilder`] with all of the `VERGEN_GIT_*` instructions on
    pub fn all(&mut self) -> &mut Self {
        self.branch(true)
            .commit_author_email(true)
            .commit_author_name(true)
            .commit_count(true)
            .commit_date(true)
            .commit_message(true)
            .commit_timestamp(true)
            .describe(false, false, None)
            .sha(false)
            .dirty(false)
    }

    /// Emit the describe output
    ///
    /// ```text
    /// cargo:rustc-env=VERGEN_GIT_DESCRIBE=<DESCRIBE>
    /// ```
    ///
    /// Optionally, add the `dirty` or `tags` flag to describe.
    /// See [`git describe`](https://git-scm.com/docs/git-describe#_options) for more details
    ///
    pub fn describe(
        &mut self,
        tags: bool,
        dirty: bool,
        matches: Option<&'static str>,
    ) -> &mut Self {
        self.describe = Some(true);
        let _ = self.describe_tags(tags);
        let _ = self.describe_dirty(dirty);
        let _ = self.describe_match_pattern(matches);
        self
    }

    /// Emit the dirty state of the git repository
    /// ```text
    /// cargo:rustc-env=VERGEN_GIT_DIRTY=(true|false)
    /// ```
    ///
    /// Optionally, include untracked files when determining the dirty status of the repository.
    ///
    pub fn dirty(&mut self, include_untracked: bool) -> &mut Self {
        self.dirty = Some(true);
        let _ = self.dirty_include_untracked(include_untracked);
        self
    }

    /// Emit the SHA of the latest commit
    ///
    /// ```text
    /// cargo:rustc-env=VERGEN_GIT_SHA=<SHA>
    /// ```
    ///
    /// Optionally, add the `short` flag to rev-parse.
    /// See [`git rev-parse`](https://git-scm.com/docs/git-rev-parse#_options_for_output) for more details.
    ///
    pub fn sha(&mut self, short: bool) -> &mut Self {
        self.sha = Some(true);
        let _ = self.sha_short(short);
        self
    }
}

impl Gitcl {
    fn any(&self) -> bool {
        self.branch
            || self.commit_author_email
            || self.commit_author_name
            || self.commit_count
            || self.commit_date
            || self.commit_message
            || self.commit_timestamp
            || self.describe
            || self.sha
            || self.dirty
    }

    ///
    pub fn at_path(&mut self, path: PathBuf) -> &mut Self {
        self.repo_path = Some(path);
        self
    }

    // #[cfg(test)]
    // pub(crate) fn fail(&mut self) -> &mut Self {
    //     self.fail = true;
    //     self
    // }

    /// Set the command used to test if git exists on the path.
    /// Defaults to `git --version` if not set explicitly.
    pub fn git_cmd(&mut self, cmd: Option<&'static str>) -> &mut Self {
        self.git_cmd = cmd;
        self
    }

    fn check_git(cmd: &str) -> Result<()> {
        if Self::git_cmd_exists(cmd) {
            Ok(())
        } else {
            Err(anyhow!("no suitable 'git' command found!"))
        }
    }

    fn check_inside_git_worktree(path: &Option<PathBuf>) -> Result<()> {
        if Self::inside_git_worktree(path) {
            Ok(())
        } else {
            Err(anyhow!("not within a suitable 'git' worktree!"))
        }
    }

    fn git_cmd_exists(cmd: &str) -> bool {
        Self::run_cmd(cmd, &None)
            .map(|output| output.status.success())
            .unwrap_or(false)
    }

    fn inside_git_worktree(path: &Option<PathBuf>) -> bool {
        Self::run_cmd("git rev-parse --is-inside-work-tree", path)
            .map(|output| {
                let stdout = String::from_utf8_lossy(&output.stdout);
                output.status.success() && stdout.trim() == "true"
            })
            .unwrap_or(false)
    }

    #[cfg(not(target_env = "msvc"))]
    fn run_cmd(command: &str, path_opt: &Option<PathBuf>) -> Result<Output> {
        let shell = if let Some(shell_path) = env::var_os("SHELL") {
            shell_path.to_string_lossy().into_owned()
        } else {
            // Fallback to sh if SHELL not defined
            "sh".to_string()
        };
        let mut cmd = Command::new(shell);
        if let Some(path) = path_opt {
            _ = cmd.current_dir(path);
        }
        _ = cmd.arg("-c");
        _ = cmd.arg(command);
        _ = cmd.stdout(Stdio::piped());
        _ = cmd.stderr(Stdio::piped());
        Ok(cmd.output()?)
    }

    #[cfg(target_env = "msvc")]
    fn run_cmd(command: &str, path_opt: &Option<PathBuf>) -> Result<Output> {
        let mut cmd = Command::new("cmd");
        if let Some(path) = path_opt {
            _ = cmd.current_dir(path);
        }
        _ = cmd.arg("/c");
        _ = cmd.arg(command);
        _ = cmd.stdout(Stdio::piped());
        _ = cmd.stderr(Stdio::piped());
        Ok(cmd.output()?)
    }

    #[allow(clippy::too_many_lines)]
    fn inner_add_git_map_entries(
        &self,
        idempotent: bool,
        cargo_rustc_env: &mut CargoRustcEnvMap,
        cargo_rerun_if_changed: &mut CargoRerunIfChanged,
        cargo_warning: &mut CargoWarning,
    ) -> Result<()> {
        if !idempotent && self.any() {
            Self::add_rerun_if_changed(cargo_rerun_if_changed, &self.repo_path)?;
        }

        if self.branch {
            if let Ok(_value) = env::var(GIT_BRANCH_NAME) {
                add_default_map_entry(VergenKey::GitBranch, cargo_rustc_env, cargo_warning);
            } else {
                Self::add_git_cmd_entry(
                    BRANCH_CMD,
                    &self.repo_path,
                    VergenKey::GitBranch,
                    cargo_rustc_env,
                )?;
            }
        }

        if self.commit_author_email {
            if let Ok(_value) = env::var(GIT_COMMIT_AUTHOR_EMAIL) {
                add_default_map_entry(
                    VergenKey::GitCommitAuthorEmail,
                    cargo_rustc_env,
                    cargo_warning,
                );
            } else {
                Self::add_git_cmd_entry(
                    COMMIT_AUTHOR_EMAIL,
                    &self.repo_path,
                    VergenKey::GitCommitAuthorEmail,
                    cargo_rustc_env,
                )?;
            }
        }

        if self.commit_author_name {
            if let Ok(_value) = env::var(GIT_COMMIT_AUTHOR_NAME) {
                add_default_map_entry(
                    VergenKey::GitCommitAuthorName,
                    cargo_rustc_env,
                    cargo_warning,
                );
            } else {
                Self::add_git_cmd_entry(
                    COMMIT_AUTHOR_NAME,
                    &self.repo_path,
                    VergenKey::GitCommitAuthorName,
                    cargo_rustc_env,
                )?;
            }
        }

        if self.commit_count {
            if let Ok(_value) = env::var(GIT_COMMIT_COUNT) {
                add_default_map_entry(VergenKey::GitCommitCount, cargo_rustc_env, cargo_warning);
            } else {
                Self::add_git_cmd_entry(
                    COMMIT_COUNT,
                    &self.repo_path,
                    VergenKey::GitCommitCount,
                    cargo_rustc_env,
                )?;
            }
        }

        self.add_git_timestamp_entries(
            COMMIT_TIMESTAMP,
            &self.repo_path,
            idempotent,
            cargo_rustc_env,
            cargo_warning,
        )?;

        if self.commit_message {
            if let Ok(_value) = env::var(GIT_COMMIT_MESSAGE) {
                add_default_map_entry(VergenKey::GitCommitMessage, cargo_rustc_env, cargo_warning);
            } else {
                Self::add_git_cmd_entry(
                    COMMIT_MESSAGE,
                    &self.repo_path,
                    VergenKey::GitCommitMessage,
                    cargo_rustc_env,
                )?;
            }
        }

        if self.describe {
            if let Ok(_value) = env::var(GIT_DESCRIBE_NAME) {
                add_default_map_entry(VergenKey::GitDescribe, cargo_rustc_env, cargo_warning);
            } else {
                let mut describe_cmd = String::from(DESCRIBE);
                if self.describe_dirty {
                    describe_cmd.push_str(" --dirty");
                }
                if self.describe_tags {
                    describe_cmd.push_str(" --tags");
                }
                if let Some(pattern) = self.describe_match_pattern {
                    describe_cmd.push_str(" --match \"");
                    describe_cmd.push_str(pattern);
                    describe_cmd.push('\"');
                }
                Self::add_git_cmd_entry(
                    &describe_cmd,
                    &self.repo_path,
                    VergenKey::GitDescribe,
                    cargo_rustc_env,
                )?;
            }
        }

        if self.sha {
            if let Ok(_value) = env::var(GIT_SHA_NAME) {
                add_default_map_entry(VergenKey::GitSha, cargo_rustc_env, cargo_warning);
            } else {
                let mut sha_cmd = String::from(SHA);
                if self.sha_short {
                    sha_cmd.push_str(" --short");
                }
                sha_cmd.push_str(" HEAD");
                Self::add_git_cmd_entry(
                    &sha_cmd,
                    &self.repo_path,
                    VergenKey::GitSha,
                    cargo_rustc_env,
                )?;
            }
        }

        if self.dirty {
            if let Ok(_value) = env::var(GIT_DIRTY_NAME) {
                add_default_map_entry(VergenKey::GitDirty, cargo_rustc_env, cargo_warning);
            } else {
                let mut dirty_cmd = String::from(DIRTY);
                if !self.dirty_include_untracked {
                    dirty_cmd.push_str(" --untracked-files=no");
                }
                let output = Self::run_cmd(&dirty_cmd, &self.repo_path)?;
                if output.stdout.is_empty() {
                    add_map_entry(VergenKey::GitDirty, "false", cargo_rustc_env);
                } else {
                    add_map_entry(VergenKey::GitDirty, "true", cargo_rustc_env);
                }
            }
        }

        Ok(())
    }

    fn add_rerun_if_changed(
        rerun_if_changed: &mut Vec<String>,
        path: &Option<PathBuf>,
    ) -> Result<()> {
        let git_path = Self::run_cmd("git rev-parse --git-dir", path)?;
        if git_path.status.success() {
            let git_path_str = String::from_utf8_lossy(&git_path.stdout).trim().to_string();
            let git_path = PathBuf::from(&git_path_str);

            // Setup the head path
            let mut head_path = git_path.clone();
            head_path.push("HEAD");

            if head_path.exists() {
                rerun_if_changed.push(format!("{}", head_path.display()));
            }

            // Setup the ref path
            let refp = Self::setup_ref_path(path)?;
            if refp.status.success() {
                let ref_path_str = String::from_utf8_lossy(&refp.stdout).trim().to_string();
                let mut ref_path = git_path;
                ref_path.push(ref_path_str);
                if ref_path.exists() {
                    rerun_if_changed.push(format!("{}", ref_path.display()));
                }
            }
        }
        Ok(())
    }

    #[cfg(not(test))]
    fn setup_ref_path(path: &Option<PathBuf>) -> Result<Output> {
        Self::run_cmd("git symbolic-ref HEAD", path)
    }

    #[cfg(all(test, not(target_os = "windows")))]
    fn setup_ref_path(path: &Option<PathBuf>) -> Result<Output> {
        Self::run_cmd("pwd", path)
    }

    #[cfg(all(test, target_os = "windows"))]
    fn setup_ref_path(path: &Option<PathBuf>) -> Result<Output> {
        Self::run_cmd("cd", path)
    }

    fn add_git_cmd_entry(
        cmd: &str,
        path: &Option<PathBuf>,
        key: VergenKey,
        cargo_rustc_env: &mut CargoRustcEnvMap,
    ) -> Result<()> {
        let output = Self::run_cmd(cmd, path)?;
        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout)
                .trim()
                .trim_matches('\'')
                .to_string();
            add_map_entry(key, stdout, cargo_rustc_env);
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(anyhow!("Failed to run '{cmd}'!  {stderr}"));
        }
        Ok(())
    }

    fn add_git_timestamp_entries(
        &self,
        cmd: &str,
        path: &Option<PathBuf>,
        idempotent: bool,
        cargo_rustc_env: &mut CargoRustcEnvMap,
        cargo_warning: &mut CargoWarning,
    ) -> Result<()> {
        let mut date_override = false;
        if let Ok(_value) = env::var(GIT_COMMIT_DATE_NAME) {
            add_default_map_entry(VergenKey::GitCommitDate, cargo_rustc_env, cargo_warning);
            date_override = true;
        }

        let mut timestamp_override = false;
        if let Ok(_value) = env::var(GIT_COMMIT_TIMESTAMP_NAME) {
            add_default_map_entry(
                VergenKey::GitCommitTimestamp,
                cargo_rustc_env,
                cargo_warning,
            );
            timestamp_override = true;
        }

        let output = Self::run_cmd(cmd, path)?;
        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout)
                .lines()
                .last()
                .ok_or_else(|| anyhow!("invalid 'git log' output"))?
                .trim()
                .trim_matches('\'')
                .to_string();

            let (sde, ts) = match env::var("SOURCE_DATE_EPOCH") {
                Ok(v) => (
                    true,
                    OffsetDateTime::from_unix_timestamp(i64::from_str(&v)?)?,
                ),
                Err(std::env::VarError::NotPresent) => self.compute_local_offset(&stdout)?,
                Err(e) => return Err(e.into()),
            };

            if idempotent && !sde {
                if self.commit_date && !date_override {
                    add_default_map_entry(VergenKey::GitCommitDate, cargo_rustc_env, cargo_warning);
                }

                if self.commit_timestamp && !timestamp_override {
                    add_default_map_entry(
                        VergenKey::GitCommitTimestamp,
                        cargo_rustc_env,
                        cargo_warning,
                    );
                }
            } else {
                if self.commit_date && !date_override {
                    let format = format_description::parse("[year]-[month]-[day]")?;
                    add_map_entry(
                        VergenKey::GitCommitDate,
                        ts.format(&format)?,
                        cargo_rustc_env,
                    );
                }

                if self.commit_timestamp && !timestamp_override {
                    add_map_entry(
                        VergenKey::GitCommitTimestamp,
                        ts.format(&Iso8601::DEFAULT)?,
                        cargo_rustc_env,
                    );
                }
            }
        } else {
            if self.commit_date && !date_override {
                add_default_map_entry(VergenKey::GitCommitDate, cargo_rustc_env, cargo_warning);
            }

            if self.commit_timestamp && !timestamp_override {
                add_default_map_entry(
                    VergenKey::GitCommitTimestamp,
                    cargo_rustc_env,
                    cargo_warning,
                );
            }
        }

        Ok(())
    }

    #[cfg_attr(coverage_nightly, coverage(off))]
    // this in not included in coverage, because on *nix the local offset is always unsafe
    fn compute_local_offset(&self, stdout: &str) -> Result<(bool, OffsetDateTime)> {
        let no_offset = OffsetDateTime::parse(stdout, &Rfc3339)?;
        if self.use_local {
            let local = UtcOffset::local_offset_at(no_offset)?;
            let local_offset = no_offset.checked_to_offset(local).unwrap_or(no_offset);
            Ok((false, local_offset))
        } else {
            Ok((false, no_offset))
        }
    }
}

impl AddEntries for Gitcl {
    fn add_map_entries(
        &self,
        idempotent: bool,
        cargo_rustc_env: &mut CargoRustcEnvMap,
        cargo_rerun_if_changed: &mut CargoRerunIfChanged,
        cargo_warning: &mut CargoWarning,
    ) -> Result<()> {
        if self.any() {
            let git_cmd = if let Some(cmd) = self.git_cmd {
                cmd
            } else {
                "git --version"
            };
            Self::check_git(git_cmd)
                .and_then(|()| Self::check_inside_git_worktree(&self.repo_path))?;
            self.inner_add_git_map_entries(
                idempotent,
                cargo_rustc_env,
                cargo_rerun_if_changed,
                cargo_warning,
            )?;
        }
        Ok(())
    }

    fn add_default_entries(
        &self,
        config: &DefaultConfig,
        cargo_rustc_env_map: &mut CargoRustcEnvMap,
        cargo_rerun_if_changed: &mut CargoRerunIfChanged,
        cargo_warning: &mut CargoWarning,
    ) -> Result<()> {
        if *config.fail_on_error() {
            let error = Error::msg(format!("{}", config.error()));
            Err(error)
        } else {
            // Clear any previous data.  We are re-populating
            // map isn't cleared because keys will overwrite.
            cargo_warning.clear();
            cargo_rerun_if_changed.clear();

            cargo_warning.push(format!("{}", config.error()));

            if self.branch {
                add_default_map_entry(VergenKey::GitBranch, cargo_rustc_env_map, cargo_warning);
            }
            if self.commit_author_email {
                add_default_map_entry(
                    VergenKey::GitCommitAuthorEmail,
                    cargo_rustc_env_map,
                    cargo_warning,
                );
            }
            if self.commit_author_name {
                add_default_map_entry(
                    VergenKey::GitCommitAuthorName,
                    cargo_rustc_env_map,
                    cargo_warning,
                );
            }
            if self.commit_count {
                add_default_map_entry(
                    VergenKey::GitCommitCount,
                    cargo_rustc_env_map,
                    cargo_warning,
                );
            }
            if self.commit_date {
                add_default_map_entry(VergenKey::GitCommitDate, cargo_rustc_env_map, cargo_warning);
            }
            if self.commit_message {
                add_default_map_entry(
                    VergenKey::GitCommitMessage,
                    cargo_rustc_env_map,
                    cargo_warning,
                );
            }
            if self.commit_timestamp {
                add_default_map_entry(
                    VergenKey::GitCommitTimestamp,
                    cargo_rustc_env_map,
                    cargo_warning,
                );
            }
            if self.describe {
                add_default_map_entry(VergenKey::GitDescribe, cargo_rustc_env_map, cargo_warning);
            }
            if self.sha {
                add_default_map_entry(VergenKey::GitSha, cargo_rustc_env_map, cargo_warning);
            }
            if self.dirty {
                add_default_map_entry(VergenKey::GitDirty, cargo_rustc_env_map, cargo_warning);
            }
            Ok(())
        }
    }
}

#[cfg(test)]
mod test {
    use super::{Gitcl, GitclBuilder};
    use anyhow::Result;
    use serial_test::serial;
    use std::{collections::BTreeMap, env::temp_dir, io::Write};
    use test_util::TestRepos;
    use vergen::Emitter;
    use vergen_lib::{count_idempotent, VergenKey};

    #[test]
    #[serial]
    #[allow(clippy::clone_on_copy, clippy::redundant_clone)]
    fn gitcl_clone_works() -> Result<()> {
        let gitcl = GitclBuilder::all_git()?;
        let another = gitcl.clone();
        assert_eq!(another, gitcl);
        Ok(())
    }

    #[test]
    #[serial]
    fn gitcl_debug_works() -> Result<()> {
        let gitcl = GitclBuilder::all_git()?;
        let mut buf = vec![];
        write!(buf, "{gitcl:?}")?;
        assert!(!buf.is_empty());
        Ok(())
    }

    #[test]
    #[serial]
    fn gix_default() -> Result<()> {
        let gitcl = GitclBuilder::default().build()?;
        let emitter = Emitter::default().add_instructions(&gitcl)?.test_emit();
        assert_eq!(0, emitter.cargo_rustc_env_map().len());
        assert_eq!(0, count_idempotent(emitter.cargo_rustc_env_map()));
        assert_eq!(0, emitter.cargo_warning().len());
        Ok(())
    }

    #[test]
    #[serial]
    fn bad_command_is_error() -> Result<()> {
        let mut map = BTreeMap::new();
        assert!(Gitcl::add_git_cmd_entry(
            "such_a_terrible_cmd",
            &None,
            VergenKey::GitCommitMessage,
            &mut map
        )
        .is_err());
        Ok(())
    }

    #[test]
    #[serial]
    fn non_working_tree_is_error() -> Result<()> {
        assert!(Gitcl::check_inside_git_worktree(&Some(temp_dir())).is_err());
        Ok(())
    }

    #[test]
    #[serial]
    fn invalid_git_is_error() -> Result<()> {
        assert!(Gitcl::check_git("such_a_terrible_cmd -v").is_err());
        Ok(())
    }

    #[cfg(not(target_family = "windows"))]
    #[test]
    #[serial]
    fn shell_env_works() -> Result<()> {
        temp_env::with_var("SHELL", Some("bash"), || {
            let mut map = BTreeMap::new();
            assert!(Gitcl::add_git_cmd_entry(
                "git -v",
                &None,
                VergenKey::GitCommitMessage,
                &mut map
            )
            .is_ok());
        });
        Ok(())
    }

    #[test]
    #[serial]
    fn git_all_idempotent() -> Result<()> {
        let gitcl = GitclBuilder::all_git()?;
        let emitter = Emitter::default()
            .idempotent()
            .add_instructions(&gitcl)?
            .test_emit();
        assert_eq!(10, emitter.cargo_rustc_env_map().len());
        assert_eq!(2, count_idempotent(emitter.cargo_rustc_env_map()));
        assert_eq!(2, emitter.cargo_warning().len());
        Ok(())
    }

    #[test]
    #[serial]
    fn git_all_idempotent_no_warn() -> Result<()> {
        let gitcl = GitclBuilder::all_git()?;
        let emitter = Emitter::default()
            .idempotent()
            .quiet()
            .add_instructions(&gitcl)?
            .test_emit();
        assert_eq!(10, emitter.cargo_rustc_env_map().len());
        assert_eq!(2, count_idempotent(emitter.cargo_rustc_env_map()));
        assert_eq!(2, emitter.cargo_warning().len());
        Ok(())
    }

    #[test]
    #[serial]
    fn git_all_at_path() -> Result<()> {
        let repo = TestRepos::new(false, false, false)?;
        let mut gitcl = GitclBuilder::all_git()?;
        let _ = gitcl.at_path(repo.path());
        let emitter = Emitter::default().add_instructions(&gitcl)?.test_emit();
        assert_eq!(10, emitter.cargo_rustc_env_map().len());
        assert_eq!(0, count_idempotent(emitter.cargo_rustc_env_map()));
        assert_eq!(0, emitter.cargo_warning().len());
        Ok(())
    }

    #[test]
    #[serial]
    fn git_all() -> Result<()> {
        let gitcl = GitclBuilder::all_git()?;
        let emitter = Emitter::default().add_instructions(&gitcl)?.test_emit();
        assert_eq!(10, emitter.cargo_rustc_env_map().len());
        assert_eq!(0, count_idempotent(emitter.cargo_rustc_env_map()));
        assert_eq!(0, emitter.cargo_warning().len());
        Ok(())
    }

    #[test]
    #[serial]
    fn git_all_shallow_clone() -> Result<()> {
        let repo = TestRepos::new(false, false, true)?;
        let mut gitcl = GitclBuilder::all_git()?;
        let _ = gitcl.at_path(repo.path());
        let emitter = Emitter::default().add_instructions(&gitcl)?.test_emit();
        assert_eq!(10, emitter.cargo_rustc_env_map().len());
        assert_eq!(0, count_idempotent(emitter.cargo_rustc_env_map()));
        assert_eq!(0, emitter.cargo_warning().len());
        Ok(())
    }

    #[test]
    #[serial]
    fn git_all_dirty_tags_short() -> Result<()> {
        let gitcl = GitclBuilder::default()
            .all()
            .describe(true, true, None)
            .sha(true)
            .build()?;
        let emitter = Emitter::default().add_instructions(&gitcl)?.test_emit();
        assert_eq!(10, emitter.cargo_rustc_env_map().len());
        assert_eq!(0, count_idempotent(emitter.cargo_rustc_env_map()));
        assert_eq!(0, emitter.cargo_warning().len());
        Ok(())
    }

    #[test]
    #[serial]
    fn fails_on_bad_git_command() -> Result<()> {
        let mut gitcl = GitclBuilder::all_git()?;
        let _ = gitcl.git_cmd(Some("this_is_not_a_git_cmd"));
        assert!(Emitter::default()
            .fail_on_error()
            .add_instructions(&gitcl)
            .is_err());
        Ok(())
    }

    #[test]
    #[serial]
    fn defaults_on_bad_git_command() -> Result<()> {
        let mut gitcl = GitclBuilder::all_git()?;
        let _ = gitcl.git_cmd(Some("this_is_not_a_git_cmd"));
        let emitter = Emitter::default().add_instructions(&gitcl)?.test_emit();
        assert_eq!(10, emitter.cargo_rustc_env_map().len());
        assert_eq!(10, count_idempotent(emitter.cargo_rustc_env_map()));
        assert_eq!(11, emitter.cargo_warning().len());
        Ok(())
    }

    #[test]
    #[serial]
    fn bad_timestamp_defaults() -> Result<()> {
        let mut map = BTreeMap::new();
        let mut warnings = vec![];
        let gitcl = GitclBuilder::all_git()?;
        assert!(gitcl
            .add_git_timestamp_entries(
                "this_is_not_a_git_cmd",
                &None,
                false,
                &mut map,
                &mut warnings
            )
            .is_ok());
        assert_eq!(2, map.len());
        assert_eq!(2, warnings.len());
        Ok(())
    }

    #[test]
    #[serial]
    fn source_date_epoch_works() {
        temp_env::with_var("SOURCE_DATE_EPOCH", Some("1671809360"), || {
            let result = || -> Result<()> {
                let mut stdout_buf = vec![];
                let gitcl = GitclBuilder::default()
                    .commit_date(true)
                    .commit_timestamp(true)
                    .build()?;
                _ = Emitter::new()
                    .idempotent()
                    .add_instructions(&gitcl)?
                    .emit_to(&mut stdout_buf)?;
                let output = String::from_utf8_lossy(&stdout_buf);
                for (idx, line) in output.lines().enumerate() {
                    if idx == 0 {
                        assert_eq!("cargo:rustc-env=VERGEN_GIT_COMMIT_DATE=2022-12-23", line);
                    } else if idx == 1 {
                        assert_eq!(
                            "cargo:rustc-env=VERGEN_GIT_COMMIT_TIMESTAMP=2022-12-23T15:29:20.000000000Z",
                            line
                        );
                    }
                }
                Ok(())
            }();
            assert!(result.is_ok());
        });
    }

    #[test]
    #[serial]
    #[cfg(unix)]
    fn bad_source_date_epoch_fails() {
        use std::ffi::OsStr;
        use std::os::unix::prelude::OsStrExt;

        let source = [0x66, 0x6f, 0x80, 0x6f];
        let os_str = OsStr::from_bytes(&source[..]);
        temp_env::with_var("SOURCE_DATE_EPOCH", Some(os_str), || {
            let result = || -> Result<bool> {
                let mut stdout_buf = vec![];
                let gitcl = GitclBuilder::default().commit_date(true).build()?;
                Emitter::new()
                    .idempotent()
                    .fail_on_error()
                    .add_instructions(&gitcl)?
                    .emit_to(&mut stdout_buf)
            }();
            assert!(result.is_err());
        });
    }

    #[test]
    #[serial]
    #[cfg(unix)]
    fn bad_source_date_epoch_defaults() {
        use std::ffi::OsStr;
        use std::os::unix::prelude::OsStrExt;

        let source = [0x66, 0x6f, 0x80, 0x6f];
        let os_str = OsStr::from_bytes(&source[..]);
        temp_env::with_var("SOURCE_DATE_EPOCH", Some(os_str), || {
            let result = || -> Result<bool> {
                let mut stdout_buf = vec![];
                let gitcl = GitclBuilder::default().commit_date(true).build()?;
                Emitter::new()
                    .idempotent()
                    .add_instructions(&gitcl)?
                    .emit_to(&mut stdout_buf)
            }();
            assert!(result.is_ok());
        });
    }

    #[test]
    #[serial]
    #[cfg(windows)]
    fn bad_source_date_epoch_fails() {
        use std::ffi::OsString;
        use std::os::windows::prelude::OsStringExt;

        let source = [0x0066, 0x006f, 0xD800, 0x006f];
        let os_string = OsString::from_wide(&source[..]);
        let os_str = os_string.as_os_str();
        temp_env::with_var("SOURCE_DATE_EPOCH", Some(os_str), || {
            let result = || -> Result<bool> {
                let mut stdout_buf = vec![];
                let gitcl = GitclBuilder::default().commit_date(true).build()?;
                Emitter::new()
                    .idempotent()
                    .add_instructions(&gitcl)?
                    .emit_to(&mut stdout_buf)
            }();
            assert!(result.is_err());
        });
    }

    #[test]
    #[serial]
    #[cfg(windows)]
    fn bad_source_date_epoch_defaults() {
        use std::ffi::OsString;
        use std::os::windows::prelude::OsStringExt;

        let source = [0x0066, 0x006f, 0xD800, 0x006f];
        let os_string = OsString::from_wide(&source[..]);
        let os_str = os_string.as_os_str();
        temp_env::with_var("SOURCE_DATE_EPOCH", Some(os_str), || {
            let result = || -> Result<bool> {
                let mut stdout_buf = vec![];
                let gitcl = GitclBuilder::default().commit_date(true).build()?;
                Emitter::new()
                    .idempotent()
                    .add_instructions(&gitcl)?
                    .emit_to(&mut stdout_buf)
            }();
            assert!(result.is_ok());
        });
    }
}