Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
2960 lines (2778 loc) · 118 KB
/
Copy pathlib.rs
File metadata and controls
2960 lines (2778 loc) · 118 KB
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
//! Utilities for testing `gitoxide` crates, many of which might be useful for testing programs that use `git` in general.
//!
//! ## Environment Variables
//!
//! ### `GIX_TEST_FIXTURE_HASH`
//!
//! Set this variable to control which hash function is used when creating or loading test fixtures.
//! Valid values are the names of hash functions supported by `gix_hash::Kind` (e.g., `sha1`, `sha256`).
//! If not set, the default hash function via `gix_hash::Kind::default()` is used.
//!
//! ### `GIX_TEST_FIXTURE_CACHE` and `GIX_TEST_FIXTURE_SOURCE_ROOT`
//!
//! Set both to absolute paths to share generated read-only scripted fixtures across equivalent source
//! snapshots within one owned test run.
//!
//! A source snapshot is a source tree kept at a fixed revision or working-tree state for testing, such
//! as a checkout or an exported copy of the workspace. It contains the crates, fixture scripts and their
//! inputs, not the generated fixtures. Equivalent snapshots can live at different absolute paths.
//!
//! - `GIX_TEST_FIXTURE_SOURCE_ROOT` names the current snapshot's workspace root, for example
//! `/tmp/qa-run-123/snapshot-a`, not a crate directory or its `tests/fixtures` directory.
//! An example fixture script would be at
//! `/tmp/qa-run-123/snapshot-a/gix-discover/tests/fixtures/make_nested_repos.sh`.
//! - `GIX_TEST_FIXTURE_CACHE` names the shared output directory, for example
//! `/tmp/qa-run-123/fixture-cache`. Use a fresh cache namespace for each owned test run.
//! When shared caching applies, that script's generated test files are under
//! `/tmp/qa-run-123/fixture-cache/<key>/fixture-<suffix>/`, including `.git/HEAD` and
//! `inner/.git/HEAD`. Here `<key>` is the fixture-identity hash and `<suffix>` is a random directory suffix.
//!
//! Tests in a second equivalent snapshot at `/tmp/qa-run-123/snapshot-b` use that path for
//! `GIX_TEST_FIXTURE_SOURCE_ROOT` but keep `GIX_TEST_FIXTURE_CACHE` pointing to the same
//! `/tmp/qa-run-123/fixture-cache`. Crate and script paths are keyed relative to the source root, allowing
//! equivalent requests from both snapshots to reuse a generated fixture despite their different roots.
//!
//! ## Script Isolation
//!
//! Fixture scripts and [`git()`] use `GIT_CONFIG_PARAMETERS` to disable signing and automatic maintenance
//! and set `init.defaultBranch=main` and `core.longpaths=true`. The latter lets Git for Windows use long paths
//! without depending on external configuration. A script's own `GIT_CONFIG_COUNT` entries coexist with this
//! configuration, with isolation taking precedence for shared keys. Explicit `git -c` options can override isolation.
//! Bash fixtures trace commands to a separate descriptor so redirected stderr baselines remain unchanged.
//! Bash older than 4.1 reports failed commands instead. Captured diagnostics are printed only on failure.
//!
//! ## Feature Flags
#![cfg_attr(
all(doc, feature = "document-features"),
doc = ::document_features::document_features!()
)]
#![cfg_attr(all(doc, feature = "document-features"), feature(doc_cfg))]
#![deny(missing_docs)]
use std::{
borrow::Cow,
collections::{BTreeMap, HashMap},
env,
ffi::{OsStr, OsString},
io::Read,
path::{Path, PathBuf},
str::FromStr,
time::Duration,
};
pub use bstr;
use bstr::ByteSlice;
use io_close::Close;
pub use is_ci;
use parking_lot::Mutex;
use std::sync::LazyLock;
pub use tempfile;
/// Shared setup for tests involving Git-compatible signatures.
pub mod signature;
/// Capture complete, stable repository state for integration-test assertions.
pub mod repository;
mod fixture_cache;
const ARCHIVE_DIR_NAME: &str = "generated-archives";
const BASH_FIXTURE_PRELUDE: &str = include_str!("scripted_fixture_prelude.sh");
/// A result type to allow using the try operator `?` in unit tests.
///
/// Use it like so:
///
/// ```no_run
/// use gix_testtools::TestResult;
///
/// #[test]
/// fn this() -> TestResult {
/// let x: usize = "42".parse()?;
/// Ok(())
///
/// }
/// ```
pub use gix_error::TestResult;
/// A result type for reusable test helpers.
pub type Result<T = ()> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
/// A result type for post-processing closures in `*_with_post` fixture functions.
///
/// The closure can return any value `T`, which will be returned alongside the fixture path.
/// This is useful for computing values based on the fixture contents.
pub type PostResult<T = ()> = Result<T>;
/// Rename `from` to `to`, replacing an existing file even if it is read-only.
///
/// On Windows, retry a permission-denied rename after clearing the destination's read-only flag.
/// On other platforms, this is equivalent to [`std::fs::rename()`], which can replace read-only files.
/// The replacement retains the source's permissions. If the retry fails, the destination's read-only
/// flag is not restored. Only use this on writable fixtures or during fixture initialization, and drop
/// any memory mappings before replacing their backing file.
pub fn rename(from: impl AsRef<Path>, to: impl AsRef<Path>) -> std::io::Result<()> {
let (from, to) = (from.as_ref(), to.as_ref());
let result = std::fs::rename(from, to);
#[cfg(windows)]
if result
.as_ref()
.is_err_and(|err| err.kind() == std::io::ErrorKind::PermissionDenied)
{
let mut permissions = std::fs::metadata(to)?.permissions();
if permissions.readonly() {
#[expect(clippy::permissions_set_readonly_false, reason = "this block only runs on Windows")]
permissions.set_readonly(false);
std::fs::set_permissions(to, permissions)?;
}
return std::fs::rename(from, to);
}
result
}
/// Build `example` from `package` and copy the executable to this test process' temporary target directory.
///
/// The returned executable path is stable for the lifetime of the test process and avoids races with other
/// concurrently running tests that may cause Cargo to update the shared example binary in `target/debug/examples`.
/// Build in the original workspace so relocated nextest runs reuse that same target directory.
pub fn build_example_for_test(package: &str, example: &str, target_tmpdir: impl Into<PathBuf>) -> PathBuf {
let mut cargo = std::process::Command::new(env::var_os("CARGO").unwrap_or_else(|| OsString::from(env!("CARGO"))));
let res = cargo
.current_dir(env!("CARGO_MANIFEST_DIR"))
.args(["build", "-p", package, "--example", example])
.status()
.expect("cargo should run fine");
assert!(res.success(), "cargo invocation should be successful");
let target_tmpdir = target_tmpdir.into();
let shared_path = target_tmpdir
.ancestors()
.nth(1)
.expect("first parent in target dir")
.join("debug")
.join("examples")
.join(format!("{example}{}", std::env::consts::EXE_SUFFIX));
let stable_path = target_tmpdir.join(format!(
"{example}-{}{}",
std::process::id(),
std::env::consts::EXE_SUFFIX
));
let mut last_err = None;
for _ in 0..10 {
match std::fs::copy(&shared_path, &stable_path) {
Ok(_) => return stable_path,
Err(err) => {
last_err = Some(err);
std::thread::sleep(Duration::from_millis(50));
}
}
}
panic!(
"driver at \"{}\" could be copied for stable test execution: {last_err:?}",
shared_path.display()
);
}
/// Indicates the state of a fixture when a closure is called.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FixtureState<'a> {
/// The fixture is newly created and needs post-processing.
///
/// The closure should perform any necessary modifications to the fixture
/// directory and compute its return value.
Uninitialized(&'a Path),
/// The fixture was already created (cached) and only needs to produce a return value.
///
/// The closure should NOT modify the fixture directory, but only compute
/// and return a value based on the existing contents.
Fresh(&'a Path),
}
impl FixtureState<'_> {
/// Returns the path of the fixture, which is always a directory.
pub fn path(&self) -> &Path {
match self {
FixtureState::Uninitialized(path) | FixtureState::Fresh(path) => path,
}
}
/// Returns true if the fixture is uninitialized and needs to be modified.
pub fn is_uninitialized(&self) -> bool {
matches!(self, FixtureState::Uninitialized(_))
}
}
/// Determines whether fixture generation should skip creating, updating, or overwriting a cached fixture archive.
///
/// In this module, an archive is the tar file under [`ARCHIVE_DIR_NAME`] that stores the output of a fixture
/// script or Rust fixture closure. The read-only fixture helpers unpack that archive when it already exists, and
/// [`create_archive_if_we_should()`] consults this trait before writing a new archive from the generated fixture
/// directory.
trait IsExcluded {
/// Return true if `archive` matches the configured exclusion source.
fn is_excluded(&self, archive: &Path) -> bool;
}
/// Checks whether `archive` matches `.gitignore`-style lines read by [`GitignoreExclusions`].
///
/// This is the fallback used when the `worktree-exclusions` feature is disabled, so the full `gix-worktree`
/// exclusion stack is not available. In that configuration, [`GitignoreExclusions::is_excluded()`] reads the
/// `.gitignore` next to the generated archive and delegates the line matching to this function.
#[cfg(not(feature = "worktree-exclusions"))]
fn is_excluded_by_lines(lines: &str, archive: &Path) -> bool {
let archive = archive.to_string_lossy().replace('\\', "/");
let filename = archive.rsplit('/').next().unwrap_or(&archive);
lines.lines().any(|line| {
let pattern = line.trim();
if pattern.is_empty() || pattern.starts_with('#') {
return false;
}
let pattern = pattern.trim_start_matches('/');
let candidate = if pattern.contains('/') {
archive.as_str()
} else {
filename
};
wildcard_match(pattern, candidate)
})
}
/// Matches `text` against the fallback exclusion pattern syntax.
///
/// The matcher understands literal characters and `*`, where `*` matches any byte sequence, including path
/// separators. Patterns are anchored to the full `text`; other `.gitignore` features such as `?`, character
/// classes, directory-only matches, and negation are not supported here.
///
/// For example, `*.tar` matches `fixture.tar`, `generated-archives/*.tar` matches
/// `generated-archives/fixture.tar`, and `generated-*/*.tar` matches `generated-archives/fixture.tar`.
#[cfg(not(feature = "worktree-exclusions"))]
fn wildcard_match(pattern: &str, text: &str) -> bool {
if !pattern.contains('*') {
return pattern == text;
}
let mut remainder = text;
let mut parts = pattern.split('*').peekable();
let first = parts.next().expect("split yields at least one item");
if !first.is_empty() {
let Some(stripped) = remainder.strip_prefix(first) else {
return false;
};
remainder = stripped;
}
while let Some(part) = parts.next() {
if part.is_empty() {
continue;
}
let Some(pos) = remainder.find(part) else {
return false;
};
remainder = &remainder[pos + part.len()..];
if parts.peek().is_none() && !pattern.ends_with('*') {
return remainder.is_empty();
}
}
pattern.ends_with('*') || remainder.is_empty()
}
/// A wrapper for a running git-daemon which is stopped automatically on drop.
///
/// Note that we will swallow any errors, assuming that the test would have failed if the daemon crashed.
pub struct GitDaemon {
process: GitDaemonProcess,
/// The base url under which all repositories are hosted, typically `git://127.0.0.1:port`.
pub url: String,
}
enum GitDaemonProcess {
#[cfg(not(unix))]
Child(std::process::Child),
#[cfg(unix)]
Inetd {
shutdown: std::sync::Arc<std::sync::atomic::AtomicBool>,
server_addr: std::net::SocketAddr,
listener_thread: Option<std::thread::JoinHandle<()>>,
},
}
impl Drop for GitDaemon {
fn drop(&mut self) {
match &mut self.process {
#[cfg(not(unix))]
GitDaemonProcess::Child(child) => {
child.kill().ok();
}
#[cfg(unix)]
GitDaemonProcess::Inetd {
shutdown,
server_addr,
listener_thread,
} => {
shutdown.store(true, std::sync::atomic::Ordering::SeqCst);
std::net::TcpStream::connect(*server_addr).ok();
if let Some(listener_thread) = listener_thread.take() {
listener_thread.join().ok();
}
}
}
}
}
static SCRIPT_IDENTITY: LazyLock<Mutex<BTreeMap<PathBuf, u32>>> = LazyLock::new(|| Mutex::new(BTreeMap::new()));
#[cfg(feature = "worktree-exclusions")]
type ExcludeCache = (gix_worktree::Stack, Option<gix_worktree::index::File>);
#[cfg(feature = "worktree-exclusions")]
static EXCLUDE_LUT: LazyLock<Mutex<Option<ExcludeCache>>> = LazyLock::new(|| {
let cache = (|| {
let (repo_path, _) = gix_discover::upwards(Path::new(".")).ok()?;
let (gix_dir, work_tree) = repo_path.into_repository_and_work_tree_directories();
let work_tree = work_tree?.canonicalize().ok()?;
let mut buf = Vec::with_capacity(512);
// Read the repository's case policy instead of creating filesystem probes in the source checkout.
let common_dir = gix_discover::path::from_plain_file_relative_to_file(&gix_dir.join("commondir"))
.transpose()
.ok()?
.unwrap_or_else(|| gix_dir.clone());
let mut config =
gix_config::File::from_path_no_includes(common_dir.join("config"), gix_config::Source::Local).ok()?;
if config
.boolean_by("extensions", None, "worktreeConfig")
.ok()?
.unwrap_or(false)
&& let Ok(worktree_config) =
gix_config::File::from_path_no_includes(gix_dir.join("config.worktree"), gix_config::Source::Worktree)
{
config.append(worktree_config).ok()?;
}
let ignore_case = config.boolean_by("core", None, "ignoreCase").ok()?.unwrap_or(false);
let object_hash = match config.string_by("extensions", None, "objectFormat") {
Some(format) => gix_hash::Kind::from_str(format.to_str().ok()?).ok()?,
None => gix_hash::Kind::from_str("sha1").ok()?,
};
let index =
gix_worktree::index::File::at_or_default(gix_dir.join("index"), object_hash, true, Default::default()).ok();
let case = if ignore_case {
gix_worktree::ignore::glob::pattern::Case::Fold
} else {
Default::default()
};
let state = gix_worktree::stack::State::IgnoreStack(gix_worktree::stack::state::Ignore::new(
Default::default(),
gix_worktree::ignore::Search::from_git_dir(
&gix_dir,
None,
&mut buf,
gix_worktree::stack::state::ignore::ParseIgnore {
support_precious: false,
},
)
.ok()?,
None,
gix_worktree::stack::state::ignore::Source::WorktreeThenIdMappingIfNotSkipped,
Default::default(),
));
let stack = gix_worktree::Stack::new(work_tree, state, case, buf, Default::default());
Some((stack, index))
})();
Mutex::new(cache)
});
#[cfg(feature = "worktree-exclusions")]
struct WorktreeExclusions;
#[cfg(feature = "worktree-exclusions")]
impl IsExcluded for WorktreeExclusions {
fn is_excluded(&self, archive: &Path) -> bool {
let mut lut = EXCLUDE_LUT.lock();
lut.as_mut()
.and_then(|(cache, index)| {
let archive = env::current_dir().ok()?.join(archive);
let relative_path = archive.strip_prefix(cache.base()).ok()?;
let git_path = gix_path::to_unix_separators_on_windows(gix_path::into_bstr(relative_path).ok()?);
if index
.as_ref()
.is_some_and(|index| index.entry_index_by_path(git_path.as_bstr()).is_ok())
{
return Some(false);
}
cache
.at_path(
relative_path,
Some(gix_worktree::index::entry::Mode::FILE),
&gix_worktree::object::find::Never,
)
.ok()?
.is_excluded()
.into()
})
.unwrap_or(false)
}
}
#[cfg(feature = "worktree-exclusions")]
fn default_excludes() -> &'static dyn IsExcluded {
static WORKTREE_EXCLUSIONS: WorktreeExclusions = WorktreeExclusions;
&WORKTREE_EXCLUSIONS
}
#[cfg(not(feature = "worktree-exclusions"))]
struct GitignoreExclusions;
#[cfg(not(feature = "worktree-exclusions"))]
impl IsExcluded for GitignoreExclusions {
fn is_excluded(&self, archive: &Path) -> bool {
let Some(parent) = archive.parent() else {
return false;
};
std::fs::read_to_string(parent.join(".gitignore")).is_ok_and(|lines| is_excluded_by_lines(&lines, archive))
}
}
#[cfg(not(feature = "worktree-exclusions"))]
fn default_excludes() -> &'static dyn IsExcluded {
static GITIGNORE_EXCLUSIONS: GitignoreExclusions = GitignoreExclusions;
&GITIGNORE_EXCLUSIONS
}
const ISOLATED_GIT_CONFIG: &[(&str, &str)] = &[
("commit.gpgsign", "false"),
("tag.gpgsign", "false"),
("init.defaultBranch", "main"),
("core.longpaths", "true"),
("protocol.file.allow", "always"),
("maintenance.auto", "false"),
("gc.auto", "0"),
];
static GIT_CORE_DIR: LazyLock<PathBuf> = LazyLock::new(|| {
let output = git_command(".")
.arg("--exec-path")
.output()
.expect("can execute `git --exec-path`");
assert!(output.status.success(), "`git --exec-path` failed");
output
.stdout
.strip_suffix(b"\n")
.expect("`git --exec-path` output to be well-formed")
.to_os_str()
.expect("no invalid UTF-8 in `--exec-path` except as OS allows")
.into()
});
/// The major, minor and patch level of the git version on the system.
pub static GIT_VERSION: LazyLock<(u8, u8, u8)> =
LazyLock::new(|| parse_git_version().expect("git version to be parsable"));
/// The major, minor and patch level of Git resolved inside [`bash_program()`], with fixture-script isolation.
///
/// Unlike [`GIT_VERSION`], this accounts for Git Bash adjusting `PATH` on Windows. Scripted fixture version gates
/// use this value. It assumes fixture scripts do not select a different Git themselves.
///
/// # Panics
///
/// If Bash or Git cannot be executed, or Git's version output cannot be parsed.
pub static GIT_BASH_VERSION: LazyLock<(u8, u8, u8)> =
LazyLock::new(|| parse_git_bash_version().expect("Git version inside fixture Bash to be parsable"));
/// Define how [`scripted_fixture_writable_with_args()`],
/// [`scripted_fixture_writable_with_args_with_git_version()`], and [`rust_fixture_writable()`]
/// produce the writable fixture.
pub enum Creation {
/// Run the code once and copy the data from its output to the writable location.
/// This is fast but won't work if absolute paths are produced by the script.
///
/// ### Limitation
///
/// Cannot handle symlinks currently. Waiting for [this PR](https://github.com/webdesus/fs_extra/pull/70).
CopyFromReadOnly,
/// Run the code in the writable location. That way, absolute paths match the location.
Execute,
}
/// Returns true if the given `major`, `minor` and `patch` is smaller than the actual git version on the system
/// to facilitate skipping a test on the caller.
/// Will never return true on CI which is expected to have a recent enough git version.
///
/// # Panics
///
/// If `git` cannot be executed or if its version output cannot be parsed.
pub fn should_skip_as_git_version_is_smaller_than(major: u8, minor: u8, patch: u8) -> bool {
if is_ci::cached() {
return false; // CI should be made to use a recent git version, it should run there.
}
*GIT_VERSION < (major, minor, patch)
}
fn parse_git_version() -> Result<(u8, u8, u8)> {
let output = git_command(".").arg("--version").output()?;
git_version_from_bytes(&output.stdout)
}
fn parse_git_bash_version() -> Result<(u8, u8, u8)> {
let mut cmd = command_with_environment_snapshot(bash_program());
let output = configure_git_environment(&mut cmd, ".")
.args(["-c", "git --version"])
.output()?;
if !output.status.success() {
return Err(format!(
"Failed to query Git version inside fixture Bash: {}: {}",
output.status,
output.stderr.as_bstr()
)
.into());
}
git_version_from_bytes(&output.stdout)
}
fn git_version_from_bytes(bytes: &[u8]) -> Result<(u8, u8, u8)> {
let mut numbers = bytes
.split(|b| *b == b' ' || *b == b'\n')
.nth(2)
.expect("git version <version>")
.split(|b| *b == b'.')
.take(3)
.map(|n| std::str::from_utf8(n).expect("valid utf8 in version number"))
.map(u8::from_str);
Ok((|| -> Result<_> {
Ok((
numbers.next().expect("major")?,
numbers.next().expect("minor")?,
numbers.next().expect("patch")?,
))
})()
.map_err(|err| {
format!(
"Could not parse version from output of 'git --version' ({:?}) with error: {}",
bytes.to_str_lossy(),
err
)
})?)
}
/// Set the current working dir to `new_cwd` and return a type that returns to the previous working dir on drop.
pub fn set_current_dir(new_cwd: impl AsRef<Path>) -> std::io::Result<AutoRevertToPreviousCWD> {
let cwd = env::current_dir()?;
env::set_current_dir(new_cwd)?;
Ok(AutoRevertToPreviousCWD(cwd))
}
/// A utility to set the current working dir to the given value, on drop.
///
/// # Panics
///
/// Note that this will panic if the CWD cannot be set on drop.
#[derive(Debug)]
#[must_use]
pub struct AutoRevertToPreviousCWD(PathBuf);
impl Drop for AutoRevertToPreviousCWD {
fn drop(&mut self) {
env::set_current_dir(&self.0).unwrap();
}
}
/// Run isolated `git` in `working_dir` with all provided `args`.
pub fn run_git(working_dir: &Path, args: &[&str]) -> std::io::Result<std::process::ExitStatus> {
git_command(working_dir).args(args).status()
}
/// Run `script` with [`bash_program()`] in `cwd`, with the same isolation as [`git_command()`].
///
/// Standard input is disconnected while standard output and error stay attached to the inherited
/// handles.
///
/// # Panics
///
/// This function expects the script to succeed and will panic otherwise.
pub fn invoke_bash(cwd: impl AsRef<Path>, script: &str) {
let mut cmd = command_with_environment_snapshot(bash_program());
let status = configure_git_environment(&mut cmd, cwd.as_ref())
.current_dir(cwd)
.arg("-c")
.arg(script)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::inherit())
.stderr(std::process::Stdio::inherit())
.status()
.expect("can run bash script");
assert!(status.success(), "bash script failed with {status}");
}
/// Spawn a git daemon to host all repositories at or below `working_dir`.
///
/// It runs in the background until the [`GitDaemon`] is dropped.
pub fn spawn_git_daemon(working_dir: impl AsRef<Path>) -> std::io::Result<GitDaemon> {
#[cfg(unix)]
{
spawn_git_daemon_inetd(working_dir)
}
#[cfg(not(unix))]
{
spawn_git_daemon_process(working_dir)
}
}
#[cfg(not(unix))]
fn spawn_git_daemon_process(working_dir: impl AsRef<Path>) -> std::io::Result<GitDaemon> {
let mut ports: Vec<_> = (9419u16..9419 + 100).collect();
fastrand::shuffle(&mut ports);
let addr_at = |port| std::net::SocketAddr::from(([127, 0, 0, 1], port));
let free_port = {
let listener = std::net::TcpListener::bind(ports.into_iter().map(addr_at).collect::<Vec<_>>().as_slice())?;
listener.local_addr().expect("listener address is available").port()
};
let child = {
let mut cmd = command_with_environment_snapshot(GIT_CORE_DIR.join(if cfg!(windows) {
"git-daemon.exe"
} else {
"git-daemon"
}));
configure_git_environment(&mut cmd, working_dir.as_ref())
.current_dir(working_dir)
.args(["--verbose", "--base-path=.", "--export-all", "--user-path"])
.arg(format!("--port={free_port}"))
.spawn()?
};
let server_addr = addr_at(free_port);
for time in gix_lock::backoff::Quadratic::default_with_random() {
std::thread::sleep(time);
if std::net::TcpStream::connect(server_addr).is_ok() {
break;
}
}
Ok(GitDaemon {
process: GitDaemonProcess::Child(child),
url: format!("git://{server_addr}"),
})
}
#[cfg(unix)]
fn spawn_git_daemon_inetd(working_dir: impl AsRef<Path>) -> std::io::Result<GitDaemon> {
use std::{
net::{TcpListener, TcpStream},
os::fd::{FromRawFd, IntoRawFd},
process::Stdio,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
};
fn stream_to_stdio(stream: TcpStream) -> Stdio {
// SAFETY: `into_raw_fd()` transfers ownership of the socket fd, and `Stdio`
// takes over closing it in the spawned child.
unsafe { Stdio::from_raw_fd(stream.into_raw_fd()) }
}
let working_dir = working_dir.as_ref().to_owned();
let listener = TcpListener::bind(("127.0.0.1", 0))?;
let server_addr = listener.local_addr()?;
let shutdown = Arc::new(AtomicBool::new(false));
let listener_thread = std::thread::spawn({
let shutdown = shutdown.clone();
move || {
for incoming in listener.incoming() {
let stream = match incoming {
Ok(stream) => stream,
Err(_) => break,
};
if shutdown.load(Ordering::SeqCst) {
break;
}
let peer_addr = stream.peer_addr().ok();
let stdin = match stream.try_clone() {
Ok(stream) => stream_to_stdio(stream),
Err(_) => continue,
};
let stdout = stream_to_stdio(stream);
let Ok(mut child) = git_command(&working_dir)
.args([
"-c",
"uploadpack.allowrefinwant",
"daemon",
"--inetd",
"--verbose",
"--base-path=.",
"--export-all",
"--user-path",
])
.current_dir(&working_dir)
.stdin(stdin)
.stdout(stdout)
.stderr(Stdio::null())
.envs(remote_env(peer_addr))
.spawn()
else {
continue;
};
std::thread::spawn(move || {
let _ = child.wait();
});
}
}
});
Ok(GitDaemon {
process: GitDaemonProcess::Inetd {
shutdown,
server_addr,
listener_thread: Some(listener_thread),
},
url: format!("git://{server_addr}"),
})
}
#[cfg(unix)]
fn remote_env(peer_addr: Option<std::net::SocketAddr>) -> Vec<(&'static str, String)> {
peer_addr
.map(|addr| {
vec![
("REMOTE_ADDR", addr.ip().to_string()),
("REMOTE_PORT", addr.port().to_string()),
]
})
.unwrap_or_default()
}
/// Don't add a suffix to the archive name as `args` are platform dependent, non-deterministic,
/// or otherwise don't influence the content of the archive.
/// Note that this also means that `args` won't be used to control the hash of the archive itself.
#[derive(Copy, Clone)]
enum ArgsInHash {
Yes,
No,
}
/// Controls whether a scripted fixture may use or must use its archive.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum ArchivePolicy {
/// Honor `GIX_TEST_IGNORE_ARCHIVES` and generate the fixture if no archive is used.
Normal,
/// Ignore `GIX_TEST_IGNORE_ARCHIVES`, preferring the archive but falling back to generation.
Prefer,
/// Ignore `GIX_TEST_IGNORE_ARCHIVES` and return no fixture if the archive is unavailable.
Require,
}
fn archive_policy_for_git_version(is_git_version_compatible: impl FnOnce((u8, u8, u8)) -> bool) -> ArchivePolicy {
if is_git_version_compatible(*GIT_BASH_VERSION) {
ArchivePolicy::Normal
} else {
ArchivePolicy::Require
}
}
impl ArchivePolicy {
/// Return the subdirectory used to keep this policy's extracted fixture separate.
/// This way fixtures extracted from a test that has a stricter policy will not accidentally
/// be reused by a test that has a weaker policy.
fn cache_variant(self) -> Option<&'static str> {
match self {
ArchivePolicy::Normal => None,
ArchivePolicy::Prefer => Some("archive"),
ArchivePolicy::Require => Some("required-archive"),
}
}
/// Return whether `GIX_TEST_IGNORE_ARCHIVES` must be ignored when extracting the fixture.
///
/// Preferred archives freeze otherwise unstable generated contents, while required archives
/// are the only valid source when the installed Git is incompatible. Allowing the environment
/// override in either case would defeat that guarantee.
fn ignores_archive_override(self) -> bool {
!matches!(self, ArchivePolicy::Normal)
}
/// Return whether the fixture script may run when no usable archive is available.
///
/// Generation is forbidden for [`ArchivePolicy::Require`] because that policy is selected when
/// the installed Git is incompatible; running the script would produce an unsupported fixture.
fn allows_generation(self) -> bool {
!matches!(self, ArchivePolicy::Require)
}
}
/// Return the path to the `<crate-root>/tests/fixtures/<path>` directory.
pub fn fixture_path(path: impl AsRef<Path>) -> PathBuf {
fixture_base().join(path.as_ref())
}
fn fixture_base() -> PathBuf {
PathBuf::from("tests").join("fixtures")
}
/// Load the fixture from `<crate-root>/tests/fixtures/<path>` and return its data, or _panic_.
pub fn fixture_bytes(path: impl AsRef<Path>) -> Vec<u8> {
match std::fs::read(fixture_path(path.as_ref())) {
Ok(res) => res,
Err(_) => panic!("File at \"{}\" not found", path.as_ref().display()),
}
}
/// Run the executable at `script_name`, like `make_repo.sh` or `my_setup.py` to produce a read-only directory to which
/// an absolute path is returned, regardless of whether it is generated, cached, or extracted from an archive.
/// Paths passed to post-processing closures are absolute as well. Making paths absolute does not resolve symlinks
/// or introduce Windows verbatim prefixes; callers needing canonical paths must opt into that separately.
///
/// Note that it persists and the script at `script_name` will only be executed once if it ran without error.
/// Inherited `GIT_TEMPLATE_DIR` is cleared; Git's installed templates remain available.
///
/// ### Automatic Archive Creation
///
/// In order to speed up CI and even local runs should the cache get purged, the result of each script run
/// is automatically placed into a compressed _tar_ archive.
/// If a script result doesn't exist, these will be checked first and extracted if present, which they are by default.
/// This behaviour can be prohibited by setting the `GIX_TEST_IGNORE_ARCHIVES` to any value.
///
/// To speed CI up, one can add these archives to the repository. Since LFS is not currently being used, it is
/// important to check their size first, though in most cases generated archives will not be very large.
///
/// #### Disable Archive Creation
///
/// If archives aren't useful, they can be disabled by using `.gitignore` specifications.
/// That way it's trivial to prevent creation of all archives with `generated-archives/*.tar{.xz}` in the root
/// or more specific `.gitignore` configurations in lower levels of the work tree.
///
/// The latter is useful if the script's output is platform specific.
/// With the `worktree-exclusions` feature, archives tracked in the source worktree's index remain eligible for
/// regeneration even when ignored or missing from disk.
///
/// ### Bash Symlink Preflight
///
/// Scripts with the `.sh` extension run in Bash with an injected `gix_testtools_require_symlinks`
/// function. Call it before creating fixture contents: it probes a link to an existing file in the
/// fixture filesystem, records the result, and exits the script successfully if symlink creation is
/// unavailable. Other setup errors still fail the script. Tests must call [`fixture_has_symlinks()`]
/// before accessing the resulting fixture, which may be incomplete when the preflight fails.
///
/// Ignore archives for these fixtures, as the preflight result is host-dependent. Prefer read-only
/// fixtures when tests only inspect their contents; record Git baselines in the script instead of
/// invoking Git again in Rust. Use [`Creation::Execute`] when tests must mutate the fixture:
/// [`Creation::CopyFromReadOnly`] does not preserve links.
/// The prelude is injected only into the Bash instance running the script, not into child shells
/// or non-shell fixture programs.
pub fn scripted_fixture_read_only(script_name: impl AsRef<Path>) -> Result<PathBuf> {
scripted_fixture_read_only_with_args(script_name, None::<String>)
}
/// Return whether a Bash fixture's `gix_testtools_require_symlinks` preflight succeeded.
///
/// Pass the fixture root, even if the script changed directories before running the preflight.
/// An unavailable preflight prints its diagnostic and returns `Ok(false)` so the test can return
/// early. Missing, malformed, or unreadable results are errors, not reasons to skip a test.
/// A missing result explains that the Bash script must call `gix_testtools_require_symlinks`.
/// A successful preflight is not a substitute for asserting that the fixture's actual links exist.
pub fn fixture_has_symlinks(fixture_root: impl AsRef<Path>) -> std::io::Result<bool> {
let marker = fixture_root.as_ref().join("__gix_testtools_symlinks__");
let result = std::fs::read_to_string(&marker).map_err(|err| {
if err.kind() == std::io::ErrorKind::NotFound {
std::io::Error::new(
err.kind(),
format!(
"Missing symlink preflight result at \"{}\": fixture_has_symlinks() requires the Bash fixture script to call gix_testtools_require_symlinks before creating fixture contents. Pass the fixture root, not a repository subdirectory.",
marker.display()
),
)
} else {
err
}
})?;
if result == "supported\n" {
return Ok(true);
}
if let Some(diagnostic) = result.strip_prefix("unsupported\n") {
eprintln!(
"Skipping fixture at \"{}\": symlink creation is unavailable: {}",
fixture_root.as_ref().display(),
diagnostic.trim()
);
return Ok(false);
}
Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Invalid symlink preflight result at \"{}\"", marker.display()),
))
}
/// Like [`scripted_fixture_read_only()`], but uses a matching existing archive even if
/// `GIX_TEST_IGNORE_ARCHIVES` is set.
///
/// Use this only for fixtures whose generated contents are not stable across
/// platforms or filesystems and must therefore be frozen by the checked-in
/// archive.
///
/// CI normally sets `GIX_TEST_IGNORE_ARCHIVES` so fixture scripts are rerun and
/// tracked archives are proven reproducible. This helper is the opt-out for
/// fixtures where rerunning the producer can legitimately change
/// without changing semantics, for example when Git writes entries in filesystem
/// traversal order.
/// For fixtures requiring a particular Git version, use [`scripted_fixture_read_only_with_git_version()`] instead.
pub fn scripted_fixture_read_only_needs_archive(script_name: impl AsRef<Path>) -> Result<PathBuf> {
scripted_fixture_read_only_with_args_inner::<fn(FixtureState<'_>) -> PostResult, ()>(
script_name,
None::<String>,
None,
ArgsInHash::Yes,
default_excludes(),
None::<(u32, _)>,
ArchivePolicy::Prefer,
)
.map(|fixture| fixture.expect("preferred archives fall back to generation").0)
}
/// Produce a read-only scripted fixture when the installed Git version is compatible, or extract it from a matching
/// archive otherwise.
///
/// `is_git_version_compatible` receives [`GIT_BASH_VERSION`]. If it returns `true`, this behaves like
/// [`scripted_fixture_read_only()`]. Otherwise, `GIX_TEST_IGNORE_ARCHIVES` is ignored and the fixture is only made
/// available by extracting an archive whose identity matches the fixture script. The script is never run with an
/// incompatible Git version, and `None` is returned if no matching archive is available.
pub fn scripted_fixture_read_only_with_git_version(
script_name: impl AsRef<Path>,
is_git_version_compatible: impl FnOnce((u8, u8, u8)) -> bool,
) -> Result<Option<PathBuf>> {
scripted_fixture_read_only_with_args_with_git_version(script_name, None::<String>, is_git_version_compatible)
}
/// Run the executable at `script_name`, like `make_repo.sh` to produce a writable directory to which
/// the tempdir is returned. It will be removed automatically, courtesy of [`tempfile::TempDir`].
///
/// Note that `script_name` is only executed once, so the data can be copied from its read-only location.
pub fn scripted_fixture_writable(script_name: impl AsRef<Path>) -> Result<tempfile::TempDir> {
scripted_fixture_writable_with_args(script_name, None::<String>, Creation::CopyFromReadOnly)
}
/// Produce a writable scripted fixture when the installed Git version is compatible, or extract it from a matching
/// archive otherwise.
///
/// This is the writable equivalent of [`scripted_fixture_read_only_with_git_version()`]. It returns `None` when Git is
/// incompatible and no matching archive is available.
pub fn scripted_fixture_writable_with_git_version(
script_name: impl AsRef<Path>,
is_git_version_compatible: impl FnOnce((u8, u8, u8)) -> bool,
) -> Result<Option<tempfile::TempDir>> {
scripted_fixture_writable_with_args_with_git_version(
script_name,
None::<String>,
Creation::CopyFromReadOnly,
is_git_version_compatible,
)
}
/// Like [`scripted_fixture_writable()`], but passes `args` to `script_name` while providing control over
/// the way files are created with `mode`.
pub fn scripted_fixture_writable_with_args(
script_name: impl AsRef<Path>,
args: impl IntoIterator<Item = impl Into<String>>,
mode: Creation,
) -> Result<tempfile::TempDir> {
scripted_fixture_writable_with_args_inner::<fn(FixtureState<'_>) -> PostResult, ()>(
script_name,
args,
mode,
ArgsInHash::Yes,
default_excludes(),
None::<(u32, _)>,
ArchivePolicy::Normal,
)
.map(|fixture| fixture.expect("normal fixtures fall back to generation").0)
}
/// Like [`scripted_fixture_writable_with_git_version()`], but passes `args` to `script_name` while providing control
/// over the way files are created with `mode`.
pub fn scripted_fixture_writable_with_args_with_git_version(
script_name: impl AsRef<Path>,
args: impl IntoIterator<Item = impl Into<String>>,