worktree_tests.rs

   1use crate::{
   2    project_settings::ProjectSettings,
   3    worktree::{Event, Snapshot, WorktreeModelHandle},
   4    Entry, EntryKind, PathChange, Project, Worktree,
   5};
   6use anyhow::Result;
   7use client::Client;
   8use fs::{repository::GitFileStatus, FakeFs, Fs, RealFs, RemoveOptions};
   9use git::GITIGNORE;
  10use gpui::{executor::Deterministic, ModelContext, Task, TestAppContext};
  11use parking_lot::Mutex;
  12use postage::stream::Stream;
  13use pretty_assertions::assert_eq;
  14use rand::prelude::*;
  15use serde_json::json;
  16use settings::SettingsStore;
  17use std::{
  18    env,
  19    fmt::Write,
  20    mem,
  21    path::{Path, PathBuf},
  22    sync::Arc,
  23};
  24use util::{http::FakeHttpClient, test::temp_tree, ResultExt};
  25
  26#[gpui::test]
  27async fn test_traversal(cx: &mut TestAppContext) {
  28    init_test(cx);
  29    let fs = FakeFs::new(cx.background());
  30    fs.insert_tree(
  31        "/root",
  32        json!({
  33           ".gitignore": "a/b\n",
  34           "a": {
  35               "b": "",
  36               "c": "",
  37           }
  38        }),
  39    )
  40    .await;
  41
  42    let tree = Worktree::local(
  43        build_client(cx),
  44        Path::new("/root"),
  45        true,
  46        fs,
  47        Default::default(),
  48        &mut cx.to_async(),
  49    )
  50    .await
  51    .unwrap();
  52    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
  53        .await;
  54
  55    tree.read_with(cx, |tree, _| {
  56        assert_eq!(
  57            tree.entries(false)
  58                .map(|entry| entry.path.as_ref())
  59                .collect::<Vec<_>>(),
  60            vec![
  61                Path::new(""),
  62                Path::new(".gitignore"),
  63                Path::new("a"),
  64                Path::new("a/c"),
  65            ]
  66        );
  67        assert_eq!(
  68            tree.entries(true)
  69                .map(|entry| entry.path.as_ref())
  70                .collect::<Vec<_>>(),
  71            vec![
  72                Path::new(""),
  73                Path::new(".gitignore"),
  74                Path::new("a"),
  75                Path::new("a/b"),
  76                Path::new("a/c"),
  77            ]
  78        );
  79    })
  80}
  81
  82#[gpui::test]
  83async fn test_descendent_entries(cx: &mut TestAppContext) {
  84    init_test(cx);
  85    let fs = FakeFs::new(cx.background());
  86    fs.insert_tree(
  87        "/root",
  88        json!({
  89            "a": "",
  90            "b": {
  91               "c": {
  92                   "d": ""
  93               },
  94               "e": {}
  95            },
  96            "f": "",
  97            "g": {
  98                "h": {}
  99            },
 100            "i": {
 101                "j": {
 102                    "k": ""
 103                },
 104                "l": {
 105
 106                }
 107            },
 108            ".gitignore": "i/j\n",
 109        }),
 110    )
 111    .await;
 112
 113    let tree = Worktree::local(
 114        build_client(cx),
 115        Path::new("/root"),
 116        true,
 117        fs,
 118        Default::default(),
 119        &mut cx.to_async(),
 120    )
 121    .await
 122    .unwrap();
 123    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
 124        .await;
 125
 126    tree.read_with(cx, |tree, _| {
 127        assert_eq!(
 128            tree.descendent_entries(false, false, Path::new("b"))
 129                .map(|entry| entry.path.as_ref())
 130                .collect::<Vec<_>>(),
 131            vec![Path::new("b/c/d"),]
 132        );
 133        assert_eq!(
 134            tree.descendent_entries(true, false, Path::new("b"))
 135                .map(|entry| entry.path.as_ref())
 136                .collect::<Vec<_>>(),
 137            vec![
 138                Path::new("b"),
 139                Path::new("b/c"),
 140                Path::new("b/c/d"),
 141                Path::new("b/e"),
 142            ]
 143        );
 144
 145        assert_eq!(
 146            tree.descendent_entries(false, false, Path::new("g"))
 147                .map(|entry| entry.path.as_ref())
 148                .collect::<Vec<_>>(),
 149            Vec::<PathBuf>::new()
 150        );
 151        assert_eq!(
 152            tree.descendent_entries(true, false, Path::new("g"))
 153                .map(|entry| entry.path.as_ref())
 154                .collect::<Vec<_>>(),
 155            vec![Path::new("g"), Path::new("g/h"),]
 156        );
 157    });
 158
 159    // Expand gitignored directory.
 160    tree.read_with(cx, |tree, _| {
 161        tree.as_local()
 162            .unwrap()
 163            .refresh_entries_for_paths(vec![Path::new("i/j").into()])
 164    })
 165    .recv()
 166    .await;
 167
 168    tree.read_with(cx, |tree, _| {
 169        assert_eq!(
 170            tree.descendent_entries(false, false, Path::new("i"))
 171                .map(|entry| entry.path.as_ref())
 172                .collect::<Vec<_>>(),
 173            Vec::<PathBuf>::new()
 174        );
 175        assert_eq!(
 176            tree.descendent_entries(false, true, Path::new("i"))
 177                .map(|entry| entry.path.as_ref())
 178                .collect::<Vec<_>>(),
 179            vec![Path::new("i/j/k")]
 180        );
 181        assert_eq!(
 182            tree.descendent_entries(true, false, Path::new("i"))
 183                .map(|entry| entry.path.as_ref())
 184                .collect::<Vec<_>>(),
 185            vec![Path::new("i"), Path::new("i/l"),]
 186        );
 187    })
 188}
 189
 190#[gpui::test(iterations = 10)]
 191async fn test_circular_symlinks(executor: Arc<Deterministic>, cx: &mut TestAppContext) {
 192    init_test(cx);
 193    let fs = FakeFs::new(cx.background());
 194    fs.insert_tree(
 195        "/root",
 196        json!({
 197            "lib": {
 198                "a": {
 199                    "a.txt": ""
 200                },
 201                "b": {
 202                    "b.txt": ""
 203                }
 204            }
 205        }),
 206    )
 207    .await;
 208    fs.insert_symlink("/root/lib/a/lib", "..".into()).await;
 209    fs.insert_symlink("/root/lib/b/lib", "..".into()).await;
 210
 211    let tree = Worktree::local(
 212        build_client(cx),
 213        Path::new("/root"),
 214        true,
 215        fs.clone(),
 216        Default::default(),
 217        &mut cx.to_async(),
 218    )
 219    .await
 220    .unwrap();
 221
 222    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
 223        .await;
 224
 225    tree.read_with(cx, |tree, _| {
 226        assert_eq!(
 227            tree.entries(false)
 228                .map(|entry| entry.path.as_ref())
 229                .collect::<Vec<_>>(),
 230            vec![
 231                Path::new(""),
 232                Path::new("lib"),
 233                Path::new("lib/a"),
 234                Path::new("lib/a/a.txt"),
 235                Path::new("lib/a/lib"),
 236                Path::new("lib/b"),
 237                Path::new("lib/b/b.txt"),
 238                Path::new("lib/b/lib"),
 239            ]
 240        );
 241    });
 242
 243    fs.rename(
 244        Path::new("/root/lib/a/lib"),
 245        Path::new("/root/lib/a/lib-2"),
 246        Default::default(),
 247    )
 248    .await
 249    .unwrap();
 250    executor.run_until_parked();
 251    tree.read_with(cx, |tree, _| {
 252        assert_eq!(
 253            tree.entries(false)
 254                .map(|entry| entry.path.as_ref())
 255                .collect::<Vec<_>>(),
 256            vec![
 257                Path::new(""),
 258                Path::new("lib"),
 259                Path::new("lib/a"),
 260                Path::new("lib/a/a.txt"),
 261                Path::new("lib/a/lib-2"),
 262                Path::new("lib/b"),
 263                Path::new("lib/b/b.txt"),
 264                Path::new("lib/b/lib"),
 265            ]
 266        );
 267    });
 268}
 269
 270#[gpui::test]
 271async fn test_symlinks_pointing_outside(cx: &mut TestAppContext) {
 272    init_test(cx);
 273    let fs = FakeFs::new(cx.background());
 274    fs.insert_tree(
 275        "/root",
 276        json!({
 277            "dir1": {
 278                "deps": {
 279                    // symlinks here
 280                },
 281                "src": {
 282                    "a.rs": "",
 283                    "b.rs": "",
 284                },
 285            },
 286            "dir2": {
 287                "src": {
 288                    "c.rs": "",
 289                    "d.rs": "",
 290                }
 291            },
 292            "dir3": {
 293                "deps": {},
 294                "src": {
 295                    "e.rs": "",
 296                    "f.rs": "",
 297                },
 298            }
 299        }),
 300    )
 301    .await;
 302
 303    // These symlinks point to directories outside of the worktree's root, dir1.
 304    fs.insert_symlink("/root/dir1/deps/dep-dir2", "../../dir2".into())
 305        .await;
 306    fs.insert_symlink("/root/dir1/deps/dep-dir3", "../../dir3".into())
 307        .await;
 308
 309    let tree = Worktree::local(
 310        build_client(cx),
 311        Path::new("/root/dir1"),
 312        true,
 313        fs.clone(),
 314        Default::default(),
 315        &mut cx.to_async(),
 316    )
 317    .await
 318    .unwrap();
 319
 320    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
 321        .await;
 322
 323    let tree_updates = Arc::new(Mutex::new(Vec::new()));
 324    tree.update(cx, |_, cx| {
 325        let tree_updates = tree_updates.clone();
 326        cx.subscribe(&tree, move |_, _, event, _| {
 327            if let Event::UpdatedEntries(update) = event {
 328                tree_updates.lock().extend(
 329                    update
 330                        .iter()
 331                        .map(|(path, _, change)| (path.clone(), *change)),
 332                );
 333            }
 334        })
 335        .detach();
 336    });
 337
 338    // The symlinked directories are not scanned by default.
 339    tree.read_with(cx, |tree, _| {
 340        assert_eq!(
 341            tree.entries(true)
 342                .map(|entry| (entry.path.as_ref(), entry.is_external))
 343                .collect::<Vec<_>>(),
 344            vec![
 345                (Path::new(""), false),
 346                (Path::new("deps"), false),
 347                (Path::new("deps/dep-dir2"), true),
 348                (Path::new("deps/dep-dir3"), true),
 349                (Path::new("src"), false),
 350                (Path::new("src/a.rs"), false),
 351                (Path::new("src/b.rs"), false),
 352            ]
 353        );
 354
 355        assert_eq!(
 356            tree.entry_for_path("deps/dep-dir2").unwrap().kind,
 357            EntryKind::UnloadedDir
 358        );
 359    });
 360
 361    // Expand one of the symlinked directories.
 362    tree.read_with(cx, |tree, _| {
 363        tree.as_local()
 364            .unwrap()
 365            .refresh_entries_for_paths(vec![Path::new("deps/dep-dir3").into()])
 366    })
 367    .recv()
 368    .await;
 369
 370    // The expanded directory's contents are loaded. Subdirectories are
 371    // not scanned yet.
 372    tree.read_with(cx, |tree, _| {
 373        assert_eq!(
 374            tree.entries(true)
 375                .map(|entry| (entry.path.as_ref(), entry.is_external))
 376                .collect::<Vec<_>>(),
 377            vec![
 378                (Path::new(""), false),
 379                (Path::new("deps"), false),
 380                (Path::new("deps/dep-dir2"), true),
 381                (Path::new("deps/dep-dir3"), true),
 382                (Path::new("deps/dep-dir3/deps"), true),
 383                (Path::new("deps/dep-dir3/src"), true),
 384                (Path::new("src"), false),
 385                (Path::new("src/a.rs"), false),
 386                (Path::new("src/b.rs"), false),
 387            ]
 388        );
 389    });
 390    assert_eq!(
 391        mem::take(&mut *tree_updates.lock()),
 392        &[
 393            (Path::new("deps/dep-dir3").into(), PathChange::Loaded),
 394            (Path::new("deps/dep-dir3/deps").into(), PathChange::Loaded),
 395            (Path::new("deps/dep-dir3/src").into(), PathChange::Loaded)
 396        ]
 397    );
 398
 399    // Expand a subdirectory of one of the symlinked directories.
 400    tree.read_with(cx, |tree, _| {
 401        tree.as_local()
 402            .unwrap()
 403            .refresh_entries_for_paths(vec![Path::new("deps/dep-dir3/src").into()])
 404    })
 405    .recv()
 406    .await;
 407
 408    // The expanded subdirectory's contents are loaded.
 409    tree.read_with(cx, |tree, _| {
 410        assert_eq!(
 411            tree.entries(true)
 412                .map(|entry| (entry.path.as_ref(), entry.is_external))
 413                .collect::<Vec<_>>(),
 414            vec![
 415                (Path::new(""), false),
 416                (Path::new("deps"), false),
 417                (Path::new("deps/dep-dir2"), true),
 418                (Path::new("deps/dep-dir3"), true),
 419                (Path::new("deps/dep-dir3/deps"), true),
 420                (Path::new("deps/dep-dir3/src"), true),
 421                (Path::new("deps/dep-dir3/src/e.rs"), true),
 422                (Path::new("deps/dep-dir3/src/f.rs"), true),
 423                (Path::new("src"), false),
 424                (Path::new("src/a.rs"), false),
 425                (Path::new("src/b.rs"), false),
 426            ]
 427        );
 428    });
 429
 430    assert_eq!(
 431        mem::take(&mut *tree_updates.lock()),
 432        &[
 433            (Path::new("deps/dep-dir3/src").into(), PathChange::Loaded),
 434            (
 435                Path::new("deps/dep-dir3/src/e.rs").into(),
 436                PathChange::Loaded
 437            ),
 438            (
 439                Path::new("deps/dep-dir3/src/f.rs").into(),
 440                PathChange::Loaded
 441            )
 442        ]
 443    );
 444}
 445
 446#[gpui::test]
 447async fn test_open_gitignored_files(cx: &mut TestAppContext) {
 448    init_test(cx);
 449    let fs = FakeFs::new(cx.background());
 450    fs.insert_tree(
 451        "/root",
 452        json!({
 453            ".gitignore": "node_modules\n",
 454            "one": {
 455                "node_modules": {
 456                    "a": {
 457                        "a1.js": "a1",
 458                        "a2.js": "a2",
 459                    },
 460                    "b": {
 461                        "b1.js": "b1",
 462                        "b2.js": "b2",
 463                    },
 464                    "c": {
 465                        "c1.js": "c1",
 466                        "c2.js": "c2",
 467                    }
 468                },
 469            },
 470            "two": {
 471                "x.js": "",
 472                "y.js": "",
 473            },
 474        }),
 475    )
 476    .await;
 477
 478    let tree = Worktree::local(
 479        build_client(cx),
 480        Path::new("/root"),
 481        true,
 482        fs.clone(),
 483        Default::default(),
 484        &mut cx.to_async(),
 485    )
 486    .await
 487    .unwrap();
 488
 489    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
 490        .await;
 491
 492    tree.read_with(cx, |tree, _| {
 493        assert_eq!(
 494            tree.entries(true)
 495                .map(|entry| (entry.path.as_ref(), entry.is_ignored))
 496                .collect::<Vec<_>>(),
 497            vec![
 498                (Path::new(""), false),
 499                (Path::new(".gitignore"), false),
 500                (Path::new("one"), false),
 501                (Path::new("one/node_modules"), true),
 502                (Path::new("two"), false),
 503                (Path::new("two/x.js"), false),
 504                (Path::new("two/y.js"), false),
 505            ]
 506        );
 507    });
 508
 509    // Open a file that is nested inside of a gitignored directory that
 510    // has not yet been expanded.
 511    let prev_read_dir_count = fs.read_dir_call_count();
 512    let buffer = tree
 513        .update(cx, |tree, cx| {
 514            tree.as_local_mut()
 515                .unwrap()
 516                .load_buffer(0, "one/node_modules/b/b1.js".as_ref(), cx)
 517        })
 518        .await
 519        .unwrap();
 520
 521    tree.read_with(cx, |tree, cx| {
 522        assert_eq!(
 523            tree.entries(true)
 524                .map(|entry| (entry.path.as_ref(), entry.is_ignored))
 525                .collect::<Vec<_>>(),
 526            vec![
 527                (Path::new(""), false),
 528                (Path::new(".gitignore"), false),
 529                (Path::new("one"), false),
 530                (Path::new("one/node_modules"), true),
 531                (Path::new("one/node_modules/a"), true),
 532                (Path::new("one/node_modules/b"), true),
 533                (Path::new("one/node_modules/b/b1.js"), true),
 534                (Path::new("one/node_modules/b/b2.js"), true),
 535                (Path::new("one/node_modules/c"), true),
 536                (Path::new("two"), false),
 537                (Path::new("two/x.js"), false),
 538                (Path::new("two/y.js"), false),
 539            ]
 540        );
 541
 542        assert_eq!(
 543            buffer.read(cx).file().unwrap().path().as_ref(),
 544            Path::new("one/node_modules/b/b1.js")
 545        );
 546
 547        // Only the newly-expanded directories are scanned.
 548        assert_eq!(fs.read_dir_call_count() - prev_read_dir_count, 2);
 549    });
 550
 551    // Open another file in a different subdirectory of the same
 552    // gitignored directory.
 553    let prev_read_dir_count = fs.read_dir_call_count();
 554    let buffer = tree
 555        .update(cx, |tree, cx| {
 556            tree.as_local_mut()
 557                .unwrap()
 558                .load_buffer(0, "one/node_modules/a/a2.js".as_ref(), cx)
 559        })
 560        .await
 561        .unwrap();
 562
 563    tree.read_with(cx, |tree, cx| {
 564        assert_eq!(
 565            tree.entries(true)
 566                .map(|entry| (entry.path.as_ref(), entry.is_ignored))
 567                .collect::<Vec<_>>(),
 568            vec![
 569                (Path::new(""), false),
 570                (Path::new(".gitignore"), false),
 571                (Path::new("one"), false),
 572                (Path::new("one/node_modules"), true),
 573                (Path::new("one/node_modules/a"), true),
 574                (Path::new("one/node_modules/a/a1.js"), true),
 575                (Path::new("one/node_modules/a/a2.js"), true),
 576                (Path::new("one/node_modules/b"), true),
 577                (Path::new("one/node_modules/b/b1.js"), true),
 578                (Path::new("one/node_modules/b/b2.js"), true),
 579                (Path::new("one/node_modules/c"), true),
 580                (Path::new("two"), false),
 581                (Path::new("two/x.js"), false),
 582                (Path::new("two/y.js"), false),
 583            ]
 584        );
 585
 586        assert_eq!(
 587            buffer.read(cx).file().unwrap().path().as_ref(),
 588            Path::new("one/node_modules/a/a2.js")
 589        );
 590
 591        // Only the newly-expanded directory is scanned.
 592        assert_eq!(fs.read_dir_call_count() - prev_read_dir_count, 1);
 593    });
 594
 595    // No work happens when files and directories change within an unloaded directory.
 596    let prev_fs_call_count = fs.read_dir_call_count() + fs.metadata_call_count();
 597    fs.create_dir("/root/one/node_modules/c/lib".as_ref())
 598        .await
 599        .unwrap();
 600    cx.foreground().run_until_parked();
 601    assert_eq!(
 602        fs.read_dir_call_count() + fs.metadata_call_count() - prev_fs_call_count,
 603        0
 604    );
 605}
 606
 607#[gpui::test]
 608async fn test_dirs_no_longer_ignored(cx: &mut TestAppContext) {
 609    init_test(cx);
 610    let fs = FakeFs::new(cx.background());
 611    fs.insert_tree(
 612        "/root",
 613        json!({
 614            ".gitignore": "node_modules\n",
 615            "a": {
 616                "a.js": "",
 617            },
 618            "b": {
 619                "b.js": "",
 620            },
 621            "node_modules": {
 622                "c": {
 623                    "c.js": "",
 624                },
 625                "d": {
 626                    "d.js": "",
 627                    "e": {
 628                        "e1.js": "",
 629                        "e2.js": "",
 630                    },
 631                    "f": {
 632                        "f1.js": "",
 633                        "f2.js": "",
 634                    }
 635                },
 636            },
 637        }),
 638    )
 639    .await;
 640
 641    let tree = Worktree::local(
 642        build_client(cx),
 643        Path::new("/root"),
 644        true,
 645        fs.clone(),
 646        Default::default(),
 647        &mut cx.to_async(),
 648    )
 649    .await
 650    .unwrap();
 651
 652    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
 653        .await;
 654
 655    // Open a file within the gitignored directory, forcing some of its
 656    // subdirectories to be read, but not all.
 657    let read_dir_count_1 = fs.read_dir_call_count();
 658    tree.read_with(cx, |tree, _| {
 659        tree.as_local()
 660            .unwrap()
 661            .refresh_entries_for_paths(vec![Path::new("node_modules/d/d.js").into()])
 662    })
 663    .recv()
 664    .await;
 665
 666    // Those subdirectories are now loaded.
 667    tree.read_with(cx, |tree, _| {
 668        assert_eq!(
 669            tree.entries(true)
 670                .map(|e| (e.path.as_ref(), e.is_ignored))
 671                .collect::<Vec<_>>(),
 672            &[
 673                (Path::new(""), false),
 674                (Path::new(".gitignore"), false),
 675                (Path::new("a"), false),
 676                (Path::new("a/a.js"), false),
 677                (Path::new("b"), false),
 678                (Path::new("b/b.js"), false),
 679                (Path::new("node_modules"), true),
 680                (Path::new("node_modules/c"), true),
 681                (Path::new("node_modules/d"), true),
 682                (Path::new("node_modules/d/d.js"), true),
 683                (Path::new("node_modules/d/e"), true),
 684                (Path::new("node_modules/d/f"), true),
 685            ]
 686        );
 687    });
 688    let read_dir_count_2 = fs.read_dir_call_count();
 689    assert_eq!(read_dir_count_2 - read_dir_count_1, 2);
 690
 691    // Update the gitignore so that node_modules is no longer ignored,
 692    // but a subdirectory is ignored
 693    fs.save("/root/.gitignore".as_ref(), &"e".into(), Default::default())
 694        .await
 695        .unwrap();
 696    cx.foreground().run_until_parked();
 697
 698    // All of the directories that are no longer ignored are now loaded.
 699    tree.read_with(cx, |tree, _| {
 700        assert_eq!(
 701            tree.entries(true)
 702                .map(|e| (e.path.as_ref(), e.is_ignored))
 703                .collect::<Vec<_>>(),
 704            &[
 705                (Path::new(""), false),
 706                (Path::new(".gitignore"), false),
 707                (Path::new("a"), false),
 708                (Path::new("a/a.js"), false),
 709                (Path::new("b"), false),
 710                (Path::new("b/b.js"), false),
 711                // This directory is no longer ignored
 712                (Path::new("node_modules"), false),
 713                (Path::new("node_modules/c"), false),
 714                (Path::new("node_modules/c/c.js"), false),
 715                (Path::new("node_modules/d"), false),
 716                (Path::new("node_modules/d/d.js"), false),
 717                // This subdirectory is now ignored
 718                (Path::new("node_modules/d/e"), true),
 719                (Path::new("node_modules/d/f"), false),
 720                (Path::new("node_modules/d/f/f1.js"), false),
 721                (Path::new("node_modules/d/f/f2.js"), false),
 722            ]
 723        );
 724    });
 725
 726    // Each of the newly-loaded directories is scanned only once.
 727    let read_dir_count_3 = fs.read_dir_call_count();
 728    assert_eq!(read_dir_count_3 - read_dir_count_2, 2);
 729}
 730
 731#[gpui::test(iterations = 10)]
 732async fn test_rescan_with_gitignore(cx: &mut TestAppContext) {
 733    init_test(cx);
 734    let fs = FakeFs::new(cx.background());
 735    fs.insert_tree(
 736        "/root",
 737        json!({
 738            ".gitignore": "ancestor-ignored-file1\nancestor-ignored-file2\n",
 739            "tree": {
 740                ".git": {},
 741                ".gitignore": "ignored-dir\n",
 742                "tracked-dir": {
 743                    "tracked-file1": "",
 744                    "ancestor-ignored-file1": "",
 745                },
 746                "ignored-dir": {
 747                    "ignored-file1": ""
 748                }
 749            }
 750        }),
 751    )
 752    .await;
 753
 754    let tree = Worktree::local(
 755        build_client(cx),
 756        "/root/tree".as_ref(),
 757        true,
 758        fs.clone(),
 759        Default::default(),
 760        &mut cx.to_async(),
 761    )
 762    .await
 763    .unwrap();
 764    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
 765        .await;
 766
 767    tree.read_with(cx, |tree, _| {
 768        tree.as_local()
 769            .unwrap()
 770            .refresh_entries_for_paths(vec![Path::new("ignored-dir").into()])
 771    })
 772    .recv()
 773    .await;
 774
 775    cx.read(|cx| {
 776        let tree = tree.read(cx);
 777        assert!(
 778            !tree
 779                .entry_for_path("tracked-dir/tracked-file1")
 780                .unwrap()
 781                .is_ignored
 782        );
 783        assert!(
 784            tree.entry_for_path("tracked-dir/ancestor-ignored-file1")
 785                .unwrap()
 786                .is_ignored
 787        );
 788        assert!(
 789            tree.entry_for_path("ignored-dir/ignored-file1")
 790                .unwrap()
 791                .is_ignored
 792        );
 793    });
 794
 795    fs.create_file(
 796        "/root/tree/tracked-dir/tracked-file2".as_ref(),
 797        Default::default(),
 798    )
 799    .await
 800    .unwrap();
 801    fs.create_file(
 802        "/root/tree/tracked-dir/ancestor-ignored-file2".as_ref(),
 803        Default::default(),
 804    )
 805    .await
 806    .unwrap();
 807    fs.create_file(
 808        "/root/tree/ignored-dir/ignored-file2".as_ref(),
 809        Default::default(),
 810    )
 811    .await
 812    .unwrap();
 813
 814    cx.foreground().run_until_parked();
 815    cx.read(|cx| {
 816        let tree = tree.read(cx);
 817        assert!(
 818            !tree
 819                .entry_for_path("tracked-dir/tracked-file2")
 820                .unwrap()
 821                .is_ignored
 822        );
 823        assert!(
 824            tree.entry_for_path("tracked-dir/ancestor-ignored-file2")
 825                .unwrap()
 826                .is_ignored
 827        );
 828        assert!(
 829            tree.entry_for_path("ignored-dir/ignored-file2")
 830                .unwrap()
 831                .is_ignored
 832        );
 833        assert!(tree.entry_for_path(".git").unwrap().is_ignored);
 834    });
 835}
 836
 837#[gpui::test]
 838async fn test_write_file(cx: &mut TestAppContext) {
 839    init_test(cx);
 840    let dir = temp_tree(json!({
 841        ".git": {},
 842        ".gitignore": "ignored-dir\n",
 843        "tracked-dir": {},
 844        "ignored-dir": {}
 845    }));
 846
 847    let tree = Worktree::local(
 848        build_client(cx),
 849        dir.path(),
 850        true,
 851        Arc::new(RealFs),
 852        Default::default(),
 853        &mut cx.to_async(),
 854    )
 855    .await
 856    .unwrap();
 857    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
 858        .await;
 859    tree.flush_fs_events(cx).await;
 860
 861    tree.update(cx, |tree, cx| {
 862        tree.as_local().unwrap().write_file(
 863            Path::new("tracked-dir/file.txt"),
 864            "hello".into(),
 865            Default::default(),
 866            cx,
 867        )
 868    })
 869    .await
 870    .unwrap();
 871    tree.update(cx, |tree, cx| {
 872        tree.as_local().unwrap().write_file(
 873            Path::new("ignored-dir/file.txt"),
 874            "world".into(),
 875            Default::default(),
 876            cx,
 877        )
 878    })
 879    .await
 880    .unwrap();
 881
 882    tree.read_with(cx, |tree, _| {
 883        let tracked = tree.entry_for_path("tracked-dir/file.txt").unwrap();
 884        let ignored = tree.entry_for_path("ignored-dir/file.txt").unwrap();
 885        assert!(!tracked.is_ignored);
 886        assert!(ignored.is_ignored);
 887    });
 888}
 889
 890#[gpui::test]
 891async fn test_ignore_exclusions(cx: &mut TestAppContext) {
 892    init_test(cx);
 893    let dir = temp_tree(json!({
 894        ".gitignore": "**/target\n/node_modules\n",
 895        "target": {
 896            "index": "blah2"
 897        },
 898        "node_modules": {
 899            ".DS_Store": "",
 900            "prettier": {
 901                "package.json": "{}",
 902            },
 903        },
 904        "src": {
 905            ".DS_Store": "",
 906            "foo": {
 907                "foo.rs": "mod another;\n",
 908                "another.rs": "// another",
 909            },
 910            "bar": {
 911                "bar.rs": "// bar",
 912            },
 913            "lib.rs": "mod foo;\nmod bar;\n",
 914        },
 915        ".DS_Store": "",
 916    }));
 917    cx.update(|cx| {
 918        cx.update_global::<SettingsStore, _, _>(|store, cx| {
 919            store.update_user_settings::<ProjectSettings>(cx, |project_settings| {
 920                project_settings.scan_exclude_files =
 921                    Some(vec!["**/foo/**".to_string(), "**/.DS_Store".to_string()]);
 922            });
 923        });
 924    });
 925
 926    let tree = Worktree::local(
 927        build_client(cx),
 928        dir.path(),
 929        true,
 930        Arc::new(RealFs),
 931        Default::default(),
 932        &mut cx.to_async(),
 933    )
 934    .await
 935    .unwrap();
 936    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
 937        .await;
 938    tree.flush_fs_events(cx).await;
 939    tree.read_with(cx, |tree, _| {
 940        check_worktree_entries(
 941            tree,
 942            &[
 943                "src/foo/foo.rs",
 944                "src/foo/another.rs",
 945                "node_modules/.DS_Store",
 946                "src/.DS_Store",
 947                ".DS_Store",
 948            ],
 949            &["target/index", "node_modules/prettier/package.json"],
 950            &["src/lib.rs", "src/bar/bar.rs", ".gitignore"],
 951        )
 952    });
 953
 954    cx.update(|cx| {
 955        cx.update_global::<SettingsStore, _, _>(|store, cx| {
 956            store.update_user_settings::<ProjectSettings>(cx, |project_settings| {
 957                project_settings.scan_exclude_files = Some(vec!["**/node_modules/**".to_string()]);
 958            });
 959        });
 960    });
 961    tree.flush_fs_events(cx).await;
 962    cx.foreground().run_until_parked();
 963    tree.read_with(cx, |tree, _| {
 964        check_worktree_entries(
 965            tree,
 966            &[
 967                "node_modules/prettier/package.json",
 968                "node_modules/.DS_Store",
 969            ],
 970            &["target/index"],
 971            &[
 972                ".gitignore",
 973                "src/lib.rs",
 974                "src/bar/bar.rs",
 975                "src/foo/foo.rs",
 976                "src/foo/another.rs",
 977                "src/.DS_Store",
 978                ".DS_Store",
 979            ],
 980        )
 981    });
 982}
 983
 984#[gpui::test(iterations = 30)]
 985async fn test_create_directory_during_initial_scan(cx: &mut TestAppContext) {
 986    init_test(cx);
 987    let fs = FakeFs::new(cx.background());
 988    fs.insert_tree(
 989        "/root",
 990        json!({
 991            "b": {},
 992            "c": {},
 993            "d": {},
 994        }),
 995    )
 996    .await;
 997
 998    let tree = Worktree::local(
 999        build_client(cx),
1000        "/root".as_ref(),
1001        true,
1002        fs,
1003        Default::default(),
1004        &mut cx.to_async(),
1005    )
1006    .await
1007    .unwrap();
1008
1009    let snapshot1 = tree.update(cx, |tree, cx| {
1010        let tree = tree.as_local_mut().unwrap();
1011        let snapshot = Arc::new(Mutex::new(tree.snapshot()));
1012        let _ = tree.observe_updates(0, cx, {
1013            let snapshot = snapshot.clone();
1014            move |update| {
1015                snapshot.lock().apply_remote_update(update).unwrap();
1016                async { true }
1017            }
1018        });
1019        snapshot
1020    });
1021
1022    let entry = tree
1023        .update(cx, |tree, cx| {
1024            tree.as_local_mut()
1025                .unwrap()
1026                .create_entry("a/e".as_ref(), true, cx)
1027        })
1028        .await
1029        .unwrap();
1030    assert!(entry.is_dir());
1031
1032    cx.foreground().run_until_parked();
1033    tree.read_with(cx, |tree, _| {
1034        assert_eq!(tree.entry_for_path("a/e").unwrap().kind, EntryKind::Dir);
1035    });
1036
1037    let snapshot2 = tree.update(cx, |tree, _| tree.as_local().unwrap().snapshot());
1038    assert_eq!(
1039        snapshot1.lock().entries(true).collect::<Vec<_>>(),
1040        snapshot2.entries(true).collect::<Vec<_>>()
1041    );
1042}
1043
1044#[gpui::test]
1045async fn test_create_dir_all_on_create_entry(cx: &mut TestAppContext) {
1046    init_test(cx);
1047    let client_fake = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1048
1049    let fs_fake = FakeFs::new(cx.background());
1050    fs_fake
1051        .insert_tree(
1052            "/root",
1053            json!({
1054                "a": {},
1055            }),
1056        )
1057        .await;
1058
1059    let tree_fake = Worktree::local(
1060        client_fake,
1061        "/root".as_ref(),
1062        true,
1063        fs_fake,
1064        Default::default(),
1065        &mut cx.to_async(),
1066    )
1067    .await
1068    .unwrap();
1069
1070    let entry = tree_fake
1071        .update(cx, |tree, cx| {
1072            tree.as_local_mut()
1073                .unwrap()
1074                .create_entry("a/b/c/d.txt".as_ref(), false, cx)
1075        })
1076        .await
1077        .unwrap();
1078    assert!(entry.is_file());
1079
1080    cx.foreground().run_until_parked();
1081    tree_fake.read_with(cx, |tree, _| {
1082        assert!(tree.entry_for_path("a/b/c/d.txt").unwrap().is_file());
1083        assert!(tree.entry_for_path("a/b/c/").unwrap().is_dir());
1084        assert!(tree.entry_for_path("a/b/").unwrap().is_dir());
1085    });
1086
1087    let client_real = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1088
1089    let fs_real = Arc::new(RealFs);
1090    let temp_root = temp_tree(json!({
1091        "a": {}
1092    }));
1093
1094    let tree_real = Worktree::local(
1095        client_real,
1096        temp_root.path(),
1097        true,
1098        fs_real,
1099        Default::default(),
1100        &mut cx.to_async(),
1101    )
1102    .await
1103    .unwrap();
1104
1105    let entry = tree_real
1106        .update(cx, |tree, cx| {
1107            tree.as_local_mut()
1108                .unwrap()
1109                .create_entry("a/b/c/d.txt".as_ref(), false, cx)
1110        })
1111        .await
1112        .unwrap();
1113    assert!(entry.is_file());
1114
1115    cx.foreground().run_until_parked();
1116    tree_real.read_with(cx, |tree, _| {
1117        assert!(tree.entry_for_path("a/b/c/d.txt").unwrap().is_file());
1118        assert!(tree.entry_for_path("a/b/c/").unwrap().is_dir());
1119        assert!(tree.entry_for_path("a/b/").unwrap().is_dir());
1120    });
1121
1122    // Test smallest change
1123    let entry = tree_real
1124        .update(cx, |tree, cx| {
1125            tree.as_local_mut()
1126                .unwrap()
1127                .create_entry("a/b/c/e.txt".as_ref(), false, cx)
1128        })
1129        .await
1130        .unwrap();
1131    assert!(entry.is_file());
1132
1133    cx.foreground().run_until_parked();
1134    tree_real.read_with(cx, |tree, _| {
1135        assert!(tree.entry_for_path("a/b/c/e.txt").unwrap().is_file());
1136    });
1137
1138    // Test largest change
1139    let entry = tree_real
1140        .update(cx, |tree, cx| {
1141            tree.as_local_mut()
1142                .unwrap()
1143                .create_entry("d/e/f/g.txt".as_ref(), false, cx)
1144        })
1145        .await
1146        .unwrap();
1147    assert!(entry.is_file());
1148
1149    cx.foreground().run_until_parked();
1150    tree_real.read_with(cx, |tree, _| {
1151        assert!(tree.entry_for_path("d/e/f/g.txt").unwrap().is_file());
1152        assert!(tree.entry_for_path("d/e/f").unwrap().is_dir());
1153        assert!(tree.entry_for_path("d/e/").unwrap().is_dir());
1154        assert!(tree.entry_for_path("d/").unwrap().is_dir());
1155    });
1156}
1157
1158#[gpui::test(iterations = 100)]
1159async fn test_random_worktree_operations_during_initial_scan(
1160    cx: &mut TestAppContext,
1161    mut rng: StdRng,
1162) {
1163    init_test(cx);
1164    let operations = env::var("OPERATIONS")
1165        .map(|o| o.parse().unwrap())
1166        .unwrap_or(5);
1167    let initial_entries = env::var("INITIAL_ENTRIES")
1168        .map(|o| o.parse().unwrap())
1169        .unwrap_or(20);
1170
1171    let root_dir = Path::new("/test");
1172    let fs = FakeFs::new(cx.background()) as Arc<dyn Fs>;
1173    fs.as_fake().insert_tree(root_dir, json!({})).await;
1174    for _ in 0..initial_entries {
1175        randomly_mutate_fs(&fs, root_dir, 1.0, &mut rng).await;
1176    }
1177    log::info!("generated initial tree");
1178
1179    let worktree = Worktree::local(
1180        build_client(cx),
1181        root_dir,
1182        true,
1183        fs.clone(),
1184        Default::default(),
1185        &mut cx.to_async(),
1186    )
1187    .await
1188    .unwrap();
1189
1190    let mut snapshots = vec![worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot())];
1191    let updates = Arc::new(Mutex::new(Vec::new()));
1192    worktree.update(cx, |tree, cx| {
1193        check_worktree_change_events(tree, cx);
1194
1195        let _ = tree.as_local_mut().unwrap().observe_updates(0, cx, {
1196            let updates = updates.clone();
1197            move |update| {
1198                updates.lock().push(update);
1199                async { true }
1200            }
1201        });
1202    });
1203
1204    for _ in 0..operations {
1205        worktree
1206            .update(cx, |worktree, cx| {
1207                randomly_mutate_worktree(worktree, &mut rng, cx)
1208            })
1209            .await
1210            .log_err();
1211        worktree.read_with(cx, |tree, _| {
1212            tree.as_local().unwrap().snapshot().check_invariants(true)
1213        });
1214
1215        if rng.gen_bool(0.6) {
1216            snapshots.push(worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot()));
1217        }
1218    }
1219
1220    worktree
1221        .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
1222        .await;
1223
1224    cx.foreground().run_until_parked();
1225
1226    let final_snapshot = worktree.read_with(cx, |tree, _| {
1227        let tree = tree.as_local().unwrap();
1228        let snapshot = tree.snapshot();
1229        snapshot.check_invariants(true);
1230        snapshot
1231    });
1232
1233    for (i, snapshot) in snapshots.into_iter().enumerate().rev() {
1234        let mut updated_snapshot = snapshot.clone();
1235        for update in updates.lock().iter() {
1236            if update.scan_id >= updated_snapshot.scan_id() as u64 {
1237                updated_snapshot
1238                    .apply_remote_update(update.clone())
1239                    .unwrap();
1240            }
1241        }
1242
1243        assert_eq!(
1244            updated_snapshot.entries(true).collect::<Vec<_>>(),
1245            final_snapshot.entries(true).collect::<Vec<_>>(),
1246            "wrong updates after snapshot {i}: {snapshot:#?} {updates:#?}",
1247        );
1248    }
1249}
1250
1251#[gpui::test(iterations = 100)]
1252async fn test_random_worktree_changes(cx: &mut TestAppContext, mut rng: StdRng) {
1253    init_test(cx);
1254    let operations = env::var("OPERATIONS")
1255        .map(|o| o.parse().unwrap())
1256        .unwrap_or(40);
1257    let initial_entries = env::var("INITIAL_ENTRIES")
1258        .map(|o| o.parse().unwrap())
1259        .unwrap_or(20);
1260
1261    let root_dir = Path::new("/test");
1262    let fs = FakeFs::new(cx.background()) as Arc<dyn Fs>;
1263    fs.as_fake().insert_tree(root_dir, json!({})).await;
1264    for _ in 0..initial_entries {
1265        randomly_mutate_fs(&fs, root_dir, 1.0, &mut rng).await;
1266    }
1267    log::info!("generated initial tree");
1268
1269    let worktree = Worktree::local(
1270        build_client(cx),
1271        root_dir,
1272        true,
1273        fs.clone(),
1274        Default::default(),
1275        &mut cx.to_async(),
1276    )
1277    .await
1278    .unwrap();
1279
1280    let updates = Arc::new(Mutex::new(Vec::new()));
1281    worktree.update(cx, |tree, cx| {
1282        check_worktree_change_events(tree, cx);
1283
1284        let _ = tree.as_local_mut().unwrap().observe_updates(0, cx, {
1285            let updates = updates.clone();
1286            move |update| {
1287                updates.lock().push(update);
1288                async { true }
1289            }
1290        });
1291    });
1292
1293    worktree
1294        .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
1295        .await;
1296
1297    fs.as_fake().pause_events();
1298    let mut snapshots = Vec::new();
1299    let mut mutations_len = operations;
1300    while mutations_len > 1 {
1301        if rng.gen_bool(0.2) {
1302            worktree
1303                .update(cx, |worktree, cx| {
1304                    randomly_mutate_worktree(worktree, &mut rng, cx)
1305                })
1306                .await
1307                .log_err();
1308        } else {
1309            randomly_mutate_fs(&fs, root_dir, 1.0, &mut rng).await;
1310        }
1311
1312        let buffered_event_count = fs.as_fake().buffered_event_count();
1313        if buffered_event_count > 0 && rng.gen_bool(0.3) {
1314            let len = rng.gen_range(0..=buffered_event_count);
1315            log::info!("flushing {} events", len);
1316            fs.as_fake().flush_events(len);
1317        } else {
1318            randomly_mutate_fs(&fs, root_dir, 0.6, &mut rng).await;
1319            mutations_len -= 1;
1320        }
1321
1322        cx.foreground().run_until_parked();
1323        if rng.gen_bool(0.2) {
1324            log::info!("storing snapshot {}", snapshots.len());
1325            let snapshot = worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
1326            snapshots.push(snapshot);
1327        }
1328    }
1329
1330    log::info!("quiescing");
1331    fs.as_fake().flush_events(usize::MAX);
1332    cx.foreground().run_until_parked();
1333
1334    let snapshot = worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
1335    snapshot.check_invariants(true);
1336    let expanded_paths = snapshot
1337        .expanded_entries()
1338        .map(|e| e.path.clone())
1339        .collect::<Vec<_>>();
1340
1341    {
1342        let new_worktree = Worktree::local(
1343            build_client(cx),
1344            root_dir,
1345            true,
1346            fs.clone(),
1347            Default::default(),
1348            &mut cx.to_async(),
1349        )
1350        .await
1351        .unwrap();
1352        new_worktree
1353            .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
1354            .await;
1355        new_worktree
1356            .update(cx, |tree, _| {
1357                tree.as_local_mut()
1358                    .unwrap()
1359                    .refresh_entries_for_paths(expanded_paths)
1360            })
1361            .recv()
1362            .await;
1363        let new_snapshot =
1364            new_worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
1365        assert_eq!(
1366            snapshot.entries_without_ids(true),
1367            new_snapshot.entries_without_ids(true)
1368        );
1369    }
1370
1371    for (i, mut prev_snapshot) in snapshots.into_iter().enumerate().rev() {
1372        for update in updates.lock().iter() {
1373            if update.scan_id >= prev_snapshot.scan_id() as u64 {
1374                prev_snapshot.apply_remote_update(update.clone()).unwrap();
1375            }
1376        }
1377
1378        assert_eq!(
1379            prev_snapshot
1380                .entries(true)
1381                .map(ignore_pending_dir)
1382                .collect::<Vec<_>>(),
1383            snapshot
1384                .entries(true)
1385                .map(ignore_pending_dir)
1386                .collect::<Vec<_>>(),
1387            "wrong updates after snapshot {i}: {updates:#?}",
1388        );
1389    }
1390
1391    fn ignore_pending_dir(entry: &Entry) -> Entry {
1392        let mut entry = entry.clone();
1393        if entry.kind.is_dir() {
1394            entry.kind = EntryKind::Dir
1395        }
1396        entry
1397    }
1398}
1399
1400// The worktree's `UpdatedEntries` event can be used to follow along with
1401// all changes to the worktree's snapshot.
1402fn check_worktree_change_events(tree: &mut Worktree, cx: &mut ModelContext<Worktree>) {
1403    let mut entries = tree.entries(true).cloned().collect::<Vec<_>>();
1404    cx.subscribe(&cx.handle(), move |tree, _, event, _| {
1405        if let Event::UpdatedEntries(changes) = event {
1406            for (path, _, change_type) in changes.iter() {
1407                let entry = tree.entry_for_path(&path).cloned();
1408                let ix = match entries.binary_search_by_key(&path, |e| &e.path) {
1409                    Ok(ix) | Err(ix) => ix,
1410                };
1411                match change_type {
1412                    PathChange::Added => entries.insert(ix, entry.unwrap()),
1413                    PathChange::Removed => drop(entries.remove(ix)),
1414                    PathChange::Updated => {
1415                        let entry = entry.unwrap();
1416                        let existing_entry = entries.get_mut(ix).unwrap();
1417                        assert_eq!(existing_entry.path, entry.path);
1418                        *existing_entry = entry;
1419                    }
1420                    PathChange::AddedOrUpdated | PathChange::Loaded => {
1421                        let entry = entry.unwrap();
1422                        if entries.get(ix).map(|e| &e.path) == Some(&entry.path) {
1423                            *entries.get_mut(ix).unwrap() = entry;
1424                        } else {
1425                            entries.insert(ix, entry);
1426                        }
1427                    }
1428                }
1429            }
1430
1431            let new_entries = tree.entries(true).cloned().collect::<Vec<_>>();
1432            assert_eq!(entries, new_entries, "incorrect changes: {:?}", changes);
1433        }
1434    })
1435    .detach();
1436}
1437
1438fn randomly_mutate_worktree(
1439    worktree: &mut Worktree,
1440    rng: &mut impl Rng,
1441    cx: &mut ModelContext<Worktree>,
1442) -> Task<Result<()>> {
1443    log::info!("mutating worktree");
1444    let worktree = worktree.as_local_mut().unwrap();
1445    let snapshot = worktree.snapshot();
1446    let entry = snapshot.entries(false).choose(rng).unwrap();
1447
1448    match rng.gen_range(0_u32..100) {
1449        0..=33 if entry.path.as_ref() != Path::new("") => {
1450            log::info!("deleting entry {:?} ({})", entry.path, entry.id.0);
1451            worktree.delete_entry(entry.id, cx).unwrap()
1452        }
1453        ..=66 if entry.path.as_ref() != Path::new("") => {
1454            let other_entry = snapshot.entries(false).choose(rng).unwrap();
1455            let new_parent_path = if other_entry.is_dir() {
1456                other_entry.path.clone()
1457            } else {
1458                other_entry.path.parent().unwrap().into()
1459            };
1460            let mut new_path = new_parent_path.join(random_filename(rng));
1461            if new_path.starts_with(&entry.path) {
1462                new_path = random_filename(rng).into();
1463            }
1464
1465            log::info!(
1466                "renaming entry {:?} ({}) to {:?}",
1467                entry.path,
1468                entry.id.0,
1469                new_path
1470            );
1471            let task = worktree.rename_entry(entry.id, new_path, cx).unwrap();
1472            cx.foreground().spawn(async move {
1473                task.await?;
1474                Ok(())
1475            })
1476        }
1477        _ => {
1478            let task = if entry.is_dir() {
1479                let child_path = entry.path.join(random_filename(rng));
1480                let is_dir = rng.gen_bool(0.3);
1481                log::info!(
1482                    "creating {} at {:?}",
1483                    if is_dir { "dir" } else { "file" },
1484                    child_path,
1485                );
1486                worktree.create_entry(child_path, is_dir, cx)
1487            } else {
1488                log::info!("overwriting file {:?} ({})", entry.path, entry.id.0);
1489                worktree.write_file(entry.path.clone(), "".into(), Default::default(), cx)
1490            };
1491            cx.foreground().spawn(async move {
1492                task.await?;
1493                Ok(())
1494            })
1495        }
1496    }
1497}
1498
1499async fn randomly_mutate_fs(
1500    fs: &Arc<dyn Fs>,
1501    root_path: &Path,
1502    insertion_probability: f64,
1503    rng: &mut impl Rng,
1504) {
1505    log::info!("mutating fs");
1506    let mut files = Vec::new();
1507    let mut dirs = Vec::new();
1508    for path in fs.as_fake().paths(false) {
1509        if path.starts_with(root_path) {
1510            if fs.is_file(&path).await {
1511                files.push(path);
1512            } else {
1513                dirs.push(path);
1514            }
1515        }
1516    }
1517
1518    if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
1519        let path = dirs.choose(rng).unwrap();
1520        let new_path = path.join(random_filename(rng));
1521
1522        if rng.gen() {
1523            log::info!(
1524                "creating dir {:?}",
1525                new_path.strip_prefix(root_path).unwrap()
1526            );
1527            fs.create_dir(&new_path).await.unwrap();
1528        } else {
1529            log::info!(
1530                "creating file {:?}",
1531                new_path.strip_prefix(root_path).unwrap()
1532            );
1533            fs.create_file(&new_path, Default::default()).await.unwrap();
1534        }
1535    } else if rng.gen_bool(0.05) {
1536        let ignore_dir_path = dirs.choose(rng).unwrap();
1537        let ignore_path = ignore_dir_path.join(&*GITIGNORE);
1538
1539        let subdirs = dirs
1540            .iter()
1541            .filter(|d| d.starts_with(&ignore_dir_path))
1542            .cloned()
1543            .collect::<Vec<_>>();
1544        let subfiles = files
1545            .iter()
1546            .filter(|d| d.starts_with(&ignore_dir_path))
1547            .cloned()
1548            .collect::<Vec<_>>();
1549        let files_to_ignore = {
1550            let len = rng.gen_range(0..=subfiles.len());
1551            subfiles.choose_multiple(rng, len)
1552        };
1553        let dirs_to_ignore = {
1554            let len = rng.gen_range(0..subdirs.len());
1555            subdirs.choose_multiple(rng, len)
1556        };
1557
1558        let mut ignore_contents = String::new();
1559        for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
1560            writeln!(
1561                ignore_contents,
1562                "{}",
1563                path_to_ignore
1564                    .strip_prefix(&ignore_dir_path)
1565                    .unwrap()
1566                    .to_str()
1567                    .unwrap()
1568            )
1569            .unwrap();
1570        }
1571        log::info!(
1572            "creating gitignore {:?} with contents:\n{}",
1573            ignore_path.strip_prefix(&root_path).unwrap(),
1574            ignore_contents
1575        );
1576        fs.save(
1577            &ignore_path,
1578            &ignore_contents.as_str().into(),
1579            Default::default(),
1580        )
1581        .await
1582        .unwrap();
1583    } else {
1584        let old_path = {
1585            let file_path = files.choose(rng);
1586            let dir_path = dirs[1..].choose(rng);
1587            file_path.into_iter().chain(dir_path).choose(rng).unwrap()
1588        };
1589
1590        let is_rename = rng.gen();
1591        if is_rename {
1592            let new_path_parent = dirs
1593                .iter()
1594                .filter(|d| !d.starts_with(old_path))
1595                .choose(rng)
1596                .unwrap();
1597
1598            let overwrite_existing_dir =
1599                !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
1600            let new_path = if overwrite_existing_dir {
1601                fs.remove_dir(
1602                    &new_path_parent,
1603                    RemoveOptions {
1604                        recursive: true,
1605                        ignore_if_not_exists: true,
1606                    },
1607                )
1608                .await
1609                .unwrap();
1610                new_path_parent.to_path_buf()
1611            } else {
1612                new_path_parent.join(random_filename(rng))
1613            };
1614
1615            log::info!(
1616                "renaming {:?} to {}{:?}",
1617                old_path.strip_prefix(&root_path).unwrap(),
1618                if overwrite_existing_dir {
1619                    "overwrite "
1620                } else {
1621                    ""
1622                },
1623                new_path.strip_prefix(&root_path).unwrap()
1624            );
1625            fs.rename(
1626                &old_path,
1627                &new_path,
1628                fs::RenameOptions {
1629                    overwrite: true,
1630                    ignore_if_exists: true,
1631                },
1632            )
1633            .await
1634            .unwrap();
1635        } else if fs.is_file(&old_path).await {
1636            log::info!(
1637                "deleting file {:?}",
1638                old_path.strip_prefix(&root_path).unwrap()
1639            );
1640            fs.remove_file(old_path, Default::default()).await.unwrap();
1641        } else {
1642            log::info!(
1643                "deleting dir {:?}",
1644                old_path.strip_prefix(&root_path).unwrap()
1645            );
1646            fs.remove_dir(
1647                &old_path,
1648                RemoveOptions {
1649                    recursive: true,
1650                    ignore_if_not_exists: true,
1651                },
1652            )
1653            .await
1654            .unwrap();
1655        }
1656    }
1657}
1658
1659fn random_filename(rng: &mut impl Rng) -> String {
1660    (0..6)
1661        .map(|_| rng.sample(rand::distributions::Alphanumeric))
1662        .map(char::from)
1663        .collect()
1664}
1665
1666#[gpui::test]
1667async fn test_rename_work_directory(cx: &mut TestAppContext) {
1668    init_test(cx);
1669    let root = temp_tree(json!({
1670        "projects": {
1671            "project1": {
1672                "a": "",
1673                "b": "",
1674            }
1675        },
1676
1677    }));
1678    let root_path = root.path();
1679
1680    let tree = Worktree::local(
1681        build_client(cx),
1682        root_path,
1683        true,
1684        Arc::new(RealFs),
1685        Default::default(),
1686        &mut cx.to_async(),
1687    )
1688    .await
1689    .unwrap();
1690
1691    let repo = git_init(&root_path.join("projects/project1"));
1692    git_add("a", &repo);
1693    git_commit("init", &repo);
1694    std::fs::write(root_path.join("projects/project1/a"), "aa").ok();
1695
1696    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
1697        .await;
1698
1699    tree.flush_fs_events(cx).await;
1700
1701    cx.read(|cx| {
1702        let tree = tree.read(cx);
1703        let (work_dir, _) = tree.repositories().next().unwrap();
1704        assert_eq!(work_dir.as_ref(), Path::new("projects/project1"));
1705        assert_eq!(
1706            tree.status_for_file(Path::new("projects/project1/a")),
1707            Some(GitFileStatus::Modified)
1708        );
1709        assert_eq!(
1710            tree.status_for_file(Path::new("projects/project1/b")),
1711            Some(GitFileStatus::Added)
1712        );
1713    });
1714
1715    std::fs::rename(
1716        root_path.join("projects/project1"),
1717        root_path.join("projects/project2"),
1718    )
1719    .ok();
1720    tree.flush_fs_events(cx).await;
1721
1722    cx.read(|cx| {
1723        let tree = tree.read(cx);
1724        let (work_dir, _) = tree.repositories().next().unwrap();
1725        assert_eq!(work_dir.as_ref(), Path::new("projects/project2"));
1726        assert_eq!(
1727            tree.status_for_file(Path::new("projects/project2/a")),
1728            Some(GitFileStatus::Modified)
1729        );
1730        assert_eq!(
1731            tree.status_for_file(Path::new("projects/project2/b")),
1732            Some(GitFileStatus::Added)
1733        );
1734    });
1735}
1736
1737#[gpui::test]
1738async fn test_git_repository_for_path(cx: &mut TestAppContext) {
1739    init_test(cx);
1740    let root = temp_tree(json!({
1741        "c.txt": "",
1742        "dir1": {
1743            ".git": {},
1744            "deps": {
1745                "dep1": {
1746                    ".git": {},
1747                    "src": {
1748                        "a.txt": ""
1749                    }
1750                }
1751            },
1752            "src": {
1753                "b.txt": ""
1754            }
1755        },
1756    }));
1757
1758    let tree = Worktree::local(
1759        build_client(cx),
1760        root.path(),
1761        true,
1762        Arc::new(RealFs),
1763        Default::default(),
1764        &mut cx.to_async(),
1765    )
1766    .await
1767    .unwrap();
1768
1769    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
1770        .await;
1771    tree.flush_fs_events(cx).await;
1772
1773    tree.read_with(cx, |tree, _cx| {
1774        let tree = tree.as_local().unwrap();
1775
1776        assert!(tree.repository_for_path("c.txt".as_ref()).is_none());
1777
1778        let entry = tree.repository_for_path("dir1/src/b.txt".as_ref()).unwrap();
1779        assert_eq!(
1780            entry
1781                .work_directory(tree)
1782                .map(|directory| directory.as_ref().to_owned()),
1783            Some(Path::new("dir1").to_owned())
1784        );
1785
1786        let entry = tree
1787            .repository_for_path("dir1/deps/dep1/src/a.txt".as_ref())
1788            .unwrap();
1789        assert_eq!(
1790            entry
1791                .work_directory(tree)
1792                .map(|directory| directory.as_ref().to_owned()),
1793            Some(Path::new("dir1/deps/dep1").to_owned())
1794        );
1795
1796        let entries = tree.files(false, 0);
1797
1798        let paths_with_repos = tree
1799            .entries_with_repositories(entries)
1800            .map(|(entry, repo)| {
1801                (
1802                    entry.path.as_ref(),
1803                    repo.and_then(|repo| {
1804                        repo.work_directory(&tree)
1805                            .map(|work_directory| work_directory.0.to_path_buf())
1806                    }),
1807                )
1808            })
1809            .collect::<Vec<_>>();
1810
1811        assert_eq!(
1812            paths_with_repos,
1813            &[
1814                (Path::new("c.txt"), None),
1815                (
1816                    Path::new("dir1/deps/dep1/src/a.txt"),
1817                    Some(Path::new("dir1/deps/dep1").into())
1818                ),
1819                (Path::new("dir1/src/b.txt"), Some(Path::new("dir1").into())),
1820            ]
1821        );
1822    });
1823
1824    let repo_update_events = Arc::new(Mutex::new(vec![]));
1825    tree.update(cx, |_, cx| {
1826        let repo_update_events = repo_update_events.clone();
1827        cx.subscribe(&tree, move |_, _, event, _| {
1828            if let Event::UpdatedGitRepositories(update) = event {
1829                repo_update_events.lock().push(update.clone());
1830            }
1831        })
1832        .detach();
1833    });
1834
1835    std::fs::write(root.path().join("dir1/.git/random_new_file"), "hello").unwrap();
1836    tree.flush_fs_events(cx).await;
1837
1838    assert_eq!(
1839        repo_update_events.lock()[0]
1840            .iter()
1841            .map(|e| e.0.clone())
1842            .collect::<Vec<Arc<Path>>>(),
1843        vec![Path::new("dir1").into()]
1844    );
1845
1846    std::fs::remove_dir_all(root.path().join("dir1/.git")).unwrap();
1847    tree.flush_fs_events(cx).await;
1848
1849    tree.read_with(cx, |tree, _cx| {
1850        let tree = tree.as_local().unwrap();
1851
1852        assert!(tree
1853            .repository_for_path("dir1/src/b.txt".as_ref())
1854            .is_none());
1855    });
1856}
1857
1858#[gpui::test]
1859async fn test_git_status(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1860    init_test(cx);
1861    const IGNORE_RULE: &'static str = "**/target";
1862
1863    let root = temp_tree(json!({
1864        "project": {
1865            "a.txt": "a",
1866            "b.txt": "bb",
1867            "c": {
1868                "d": {
1869                    "e.txt": "eee"
1870                }
1871            },
1872            "f.txt": "ffff",
1873            "target": {
1874                "build_file": "???"
1875            },
1876            ".gitignore": IGNORE_RULE
1877        },
1878
1879    }));
1880
1881    const A_TXT: &'static str = "a.txt";
1882    const B_TXT: &'static str = "b.txt";
1883    const E_TXT: &'static str = "c/d/e.txt";
1884    const F_TXT: &'static str = "f.txt";
1885    const DOTGITIGNORE: &'static str = ".gitignore";
1886    const BUILD_FILE: &'static str = "target/build_file";
1887    let project_path = Path::new("project");
1888
1889    // Set up git repository before creating the worktree.
1890    let work_dir = root.path().join("project");
1891    let mut repo = git_init(work_dir.as_path());
1892    repo.add_ignore_rule(IGNORE_RULE).unwrap();
1893    git_add(A_TXT, &repo);
1894    git_add(E_TXT, &repo);
1895    git_add(DOTGITIGNORE, &repo);
1896    git_commit("Initial commit", &repo);
1897
1898    let tree = Worktree::local(
1899        build_client(cx),
1900        root.path(),
1901        true,
1902        Arc::new(RealFs),
1903        Default::default(),
1904        &mut cx.to_async(),
1905    )
1906    .await
1907    .unwrap();
1908
1909    tree.flush_fs_events(cx).await;
1910    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
1911        .await;
1912    deterministic.run_until_parked();
1913
1914    // Check that the right git state is observed on startup
1915    tree.read_with(cx, |tree, _cx| {
1916        let snapshot = tree.snapshot();
1917        assert_eq!(snapshot.repositories().count(), 1);
1918        let (dir, _) = snapshot.repositories().next().unwrap();
1919        assert_eq!(dir.as_ref(), Path::new("project"));
1920
1921        assert_eq!(
1922            snapshot.status_for_file(project_path.join(B_TXT)),
1923            Some(GitFileStatus::Added)
1924        );
1925        assert_eq!(
1926            snapshot.status_for_file(project_path.join(F_TXT)),
1927            Some(GitFileStatus::Added)
1928        );
1929    });
1930
1931    // Modify a file in the working copy.
1932    std::fs::write(work_dir.join(A_TXT), "aa").unwrap();
1933    tree.flush_fs_events(cx).await;
1934    deterministic.run_until_parked();
1935
1936    // The worktree detects that the file's git status has changed.
1937    tree.read_with(cx, |tree, _cx| {
1938        let snapshot = tree.snapshot();
1939        assert_eq!(
1940            snapshot.status_for_file(project_path.join(A_TXT)),
1941            Some(GitFileStatus::Modified)
1942        );
1943    });
1944
1945    // Create a commit in the git repository.
1946    git_add(A_TXT, &repo);
1947    git_add(B_TXT, &repo);
1948    git_commit("Committing modified and added", &repo);
1949    tree.flush_fs_events(cx).await;
1950    deterministic.run_until_parked();
1951
1952    // The worktree detects that the files' git status have changed.
1953    tree.read_with(cx, |tree, _cx| {
1954        let snapshot = tree.snapshot();
1955        assert_eq!(
1956            snapshot.status_for_file(project_path.join(F_TXT)),
1957            Some(GitFileStatus::Added)
1958        );
1959        assert_eq!(snapshot.status_for_file(project_path.join(B_TXT)), None);
1960        assert_eq!(snapshot.status_for_file(project_path.join(A_TXT)), None);
1961    });
1962
1963    // Modify files in the working copy and perform git operations on other files.
1964    git_reset(0, &repo);
1965    git_remove_index(Path::new(B_TXT), &repo);
1966    git_stash(&mut repo);
1967    std::fs::write(work_dir.join(E_TXT), "eeee").unwrap();
1968    std::fs::write(work_dir.join(BUILD_FILE), "this should be ignored").unwrap();
1969    tree.flush_fs_events(cx).await;
1970    deterministic.run_until_parked();
1971
1972    // Check that more complex repo changes are tracked
1973    tree.read_with(cx, |tree, _cx| {
1974        let snapshot = tree.snapshot();
1975
1976        assert_eq!(snapshot.status_for_file(project_path.join(A_TXT)), None);
1977        assert_eq!(
1978            snapshot.status_for_file(project_path.join(B_TXT)),
1979            Some(GitFileStatus::Added)
1980        );
1981        assert_eq!(
1982            snapshot.status_for_file(project_path.join(E_TXT)),
1983            Some(GitFileStatus::Modified)
1984        );
1985    });
1986
1987    std::fs::remove_file(work_dir.join(B_TXT)).unwrap();
1988    std::fs::remove_dir_all(work_dir.join("c")).unwrap();
1989    std::fs::write(
1990        work_dir.join(DOTGITIGNORE),
1991        [IGNORE_RULE, "f.txt"].join("\n"),
1992    )
1993    .unwrap();
1994
1995    git_add(Path::new(DOTGITIGNORE), &repo);
1996    git_commit("Committing modified git ignore", &repo);
1997
1998    tree.flush_fs_events(cx).await;
1999    deterministic.run_until_parked();
2000
2001    let mut renamed_dir_name = "first_directory/second_directory";
2002    const RENAMED_FILE: &'static str = "rf.txt";
2003
2004    std::fs::create_dir_all(work_dir.join(renamed_dir_name)).unwrap();
2005    std::fs::write(
2006        work_dir.join(renamed_dir_name).join(RENAMED_FILE),
2007        "new-contents",
2008    )
2009    .unwrap();
2010
2011    tree.flush_fs_events(cx).await;
2012    deterministic.run_until_parked();
2013
2014    tree.read_with(cx, |tree, _cx| {
2015        let snapshot = tree.snapshot();
2016        assert_eq!(
2017            snapshot.status_for_file(&project_path.join(renamed_dir_name).join(RENAMED_FILE)),
2018            Some(GitFileStatus::Added)
2019        );
2020    });
2021
2022    renamed_dir_name = "new_first_directory/second_directory";
2023
2024    std::fs::rename(
2025        work_dir.join("first_directory"),
2026        work_dir.join("new_first_directory"),
2027    )
2028    .unwrap();
2029
2030    tree.flush_fs_events(cx).await;
2031    deterministic.run_until_parked();
2032
2033    tree.read_with(cx, |tree, _cx| {
2034        let snapshot = tree.snapshot();
2035
2036        assert_eq!(
2037            snapshot.status_for_file(
2038                project_path
2039                    .join(Path::new(renamed_dir_name))
2040                    .join(RENAMED_FILE)
2041            ),
2042            Some(GitFileStatus::Added)
2043        );
2044    });
2045}
2046
2047#[gpui::test]
2048async fn test_propagate_git_statuses(cx: &mut TestAppContext) {
2049    init_test(cx);
2050    let fs = FakeFs::new(cx.background());
2051    fs.insert_tree(
2052        "/root",
2053        json!({
2054            ".git": {},
2055            "a": {
2056                "b": {
2057                    "c1.txt": "",
2058                    "c2.txt": "",
2059                },
2060                "d": {
2061                    "e1.txt": "",
2062                    "e2.txt": "",
2063                    "e3.txt": "",
2064                }
2065            },
2066            "f": {
2067                "no-status.txt": ""
2068            },
2069            "g": {
2070                "h1.txt": "",
2071                "h2.txt": ""
2072            },
2073
2074        }),
2075    )
2076    .await;
2077
2078    fs.set_status_for_repo_via_git_operation(
2079        &Path::new("/root/.git"),
2080        &[
2081            (Path::new("a/b/c1.txt"), GitFileStatus::Added),
2082            (Path::new("a/d/e2.txt"), GitFileStatus::Modified),
2083            (Path::new("g/h2.txt"), GitFileStatus::Conflict),
2084        ],
2085    );
2086
2087    let tree = Worktree::local(
2088        build_client(cx),
2089        Path::new("/root"),
2090        true,
2091        fs.clone(),
2092        Default::default(),
2093        &mut cx.to_async(),
2094    )
2095    .await
2096    .unwrap();
2097
2098    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2099        .await;
2100
2101    cx.foreground().run_until_parked();
2102    let snapshot = tree.read_with(cx, |tree, _| tree.snapshot());
2103
2104    check_propagated_statuses(
2105        &snapshot,
2106        &[
2107            (Path::new(""), Some(GitFileStatus::Conflict)),
2108            (Path::new("a"), Some(GitFileStatus::Modified)),
2109            (Path::new("a/b"), Some(GitFileStatus::Added)),
2110            (Path::new("a/b/c1.txt"), Some(GitFileStatus::Added)),
2111            (Path::new("a/b/c2.txt"), None),
2112            (Path::new("a/d"), Some(GitFileStatus::Modified)),
2113            (Path::new("a/d/e2.txt"), Some(GitFileStatus::Modified)),
2114            (Path::new("f"), None),
2115            (Path::new("f/no-status.txt"), None),
2116            (Path::new("g"), Some(GitFileStatus::Conflict)),
2117            (Path::new("g/h2.txt"), Some(GitFileStatus::Conflict)),
2118        ],
2119    );
2120
2121    check_propagated_statuses(
2122        &snapshot,
2123        &[
2124            (Path::new("a/b"), Some(GitFileStatus::Added)),
2125            (Path::new("a/b/c1.txt"), Some(GitFileStatus::Added)),
2126            (Path::new("a/b/c2.txt"), None),
2127            (Path::new("a/d"), Some(GitFileStatus::Modified)),
2128            (Path::new("a/d/e1.txt"), None),
2129            (Path::new("a/d/e2.txt"), Some(GitFileStatus::Modified)),
2130            (Path::new("f"), None),
2131            (Path::new("f/no-status.txt"), None),
2132            (Path::new("g"), Some(GitFileStatus::Conflict)),
2133        ],
2134    );
2135
2136    check_propagated_statuses(
2137        &snapshot,
2138        &[
2139            (Path::new("a/b/c1.txt"), Some(GitFileStatus::Added)),
2140            (Path::new("a/b/c2.txt"), None),
2141            (Path::new("a/d/e1.txt"), None),
2142            (Path::new("a/d/e2.txt"), Some(GitFileStatus::Modified)),
2143            (Path::new("f/no-status.txt"), None),
2144        ],
2145    );
2146
2147    #[track_caller]
2148    fn check_propagated_statuses(
2149        snapshot: &Snapshot,
2150        expected_statuses: &[(&Path, Option<GitFileStatus>)],
2151    ) {
2152        let mut entries = expected_statuses
2153            .iter()
2154            .map(|(path, _)| snapshot.entry_for_path(path).unwrap().clone())
2155            .collect::<Vec<_>>();
2156        snapshot.propagate_git_statuses(&mut entries);
2157        assert_eq!(
2158            entries
2159                .iter()
2160                .map(|e| (e.path.as_ref(), e.git_status))
2161                .collect::<Vec<_>>(),
2162            expected_statuses
2163        );
2164    }
2165}
2166
2167fn build_client(cx: &mut TestAppContext) -> Arc<Client> {
2168    let http_client = FakeHttpClient::with_404_response();
2169    cx.read(|cx| Client::new(http_client, cx))
2170}
2171
2172#[track_caller]
2173fn git_init(path: &Path) -> git2::Repository {
2174    git2::Repository::init(path).expect("Failed to initialize git repository")
2175}
2176
2177#[track_caller]
2178fn git_add<P: AsRef<Path>>(path: P, repo: &git2::Repository) {
2179    let path = path.as_ref();
2180    let mut index = repo.index().expect("Failed to get index");
2181    index.add_path(path).expect("Failed to add a.txt");
2182    index.write().expect("Failed to write index");
2183}
2184
2185#[track_caller]
2186fn git_remove_index(path: &Path, repo: &git2::Repository) {
2187    let mut index = repo.index().expect("Failed to get index");
2188    index.remove_path(path).expect("Failed to add a.txt");
2189    index.write().expect("Failed to write index");
2190}
2191
2192#[track_caller]
2193fn git_commit(msg: &'static str, repo: &git2::Repository) {
2194    use git2::Signature;
2195
2196    let signature = Signature::now("test", "test@zed.dev").unwrap();
2197    let oid = repo.index().unwrap().write_tree().unwrap();
2198    let tree = repo.find_tree(oid).unwrap();
2199    if let Some(head) = repo.head().ok() {
2200        let parent_obj = head.peel(git2::ObjectType::Commit).unwrap();
2201
2202        let parent_commit = parent_obj.as_commit().unwrap();
2203
2204        repo.commit(
2205            Some("HEAD"),
2206            &signature,
2207            &signature,
2208            msg,
2209            &tree,
2210            &[parent_commit],
2211        )
2212        .expect("Failed to commit with parent");
2213    } else {
2214        repo.commit(Some("HEAD"), &signature, &signature, msg, &tree, &[])
2215            .expect("Failed to commit");
2216    }
2217}
2218
2219#[track_caller]
2220fn git_stash(repo: &mut git2::Repository) {
2221    use git2::Signature;
2222
2223    let signature = Signature::now("test", "test@zed.dev").unwrap();
2224    repo.stash_save(&signature, "N/A", None)
2225        .expect("Failed to stash");
2226}
2227
2228#[track_caller]
2229fn git_reset(offset: usize, repo: &git2::Repository) {
2230    let head = repo.head().expect("Couldn't get repo head");
2231    let object = head.peel(git2::ObjectType::Commit).unwrap();
2232    let commit = object.as_commit().unwrap();
2233    let new_head = commit
2234        .parents()
2235        .inspect(|parnet| {
2236            parnet.message();
2237        })
2238        .skip(offset)
2239        .next()
2240        .expect("Not enough history");
2241    repo.reset(&new_head.as_object(), git2::ResetType::Soft, None)
2242        .expect("Could not reset");
2243}
2244
2245#[allow(dead_code)]
2246#[track_caller]
2247fn git_status(repo: &git2::Repository) -> collections::HashMap<String, git2::Status> {
2248    repo.statuses(None)
2249        .unwrap()
2250        .iter()
2251        .map(|status| (status.path().unwrap().to_string(), status.status()))
2252        .collect()
2253}
2254
2255#[track_caller]
2256fn check_worktree_entries(
2257    tree: &Worktree,
2258    expected_excluded_paths: &[&str],
2259    expected_ignored_paths: &[&str],
2260    expected_tracked_paths: &[&str],
2261) {
2262    for path in expected_excluded_paths {
2263        let entry = tree.entry_for_path(path);
2264        assert!(
2265            entry.is_none(),
2266            "expected path '{path}' to be excluded, but got entry: {entry:?}",
2267        );
2268    }
2269    for path in expected_ignored_paths {
2270        let entry = tree.entry_for_path(path).unwrap();
2271        assert!(
2272            entry.is_ignored,
2273            "expected path '{path}' to be ignored, but got entry: {entry:?}",
2274        );
2275    }
2276    for path in expected_tracked_paths {
2277        let entry = tree.entry_for_path(path).unwrap();
2278        assert!(
2279            !entry.is_ignored,
2280            "expected path '{path}' to be tracked, but got entry: {entry:?}",
2281        );
2282    }
2283}
2284
2285fn init_test(cx: &mut gpui::TestAppContext) {
2286    cx.update(|cx| {
2287        cx.set_global(SettingsStore::test(cx));
2288        Project::init_settings(cx);
2289    });
2290}