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    cx.update(|cx| {
 735        cx.update_global::<SettingsStore, _, _>(|store, cx| {
 736            store.update_user_settings::<ProjectSettings>(cx, |project_settings| {
 737                project_settings.file_scan_exclusions = Some(Vec::new());
 738            });
 739        });
 740    });
 741    let fs = FakeFs::new(cx.background());
 742    fs.insert_tree(
 743        "/root",
 744        json!({
 745            ".gitignore": "ancestor-ignored-file1\nancestor-ignored-file2\n",
 746            "tree": {
 747                ".git": {},
 748                ".gitignore": "ignored-dir\n",
 749                "tracked-dir": {
 750                    "tracked-file1": "",
 751                    "ancestor-ignored-file1": "",
 752                },
 753                "ignored-dir": {
 754                    "ignored-file1": ""
 755                }
 756            }
 757        }),
 758    )
 759    .await;
 760
 761    let tree = Worktree::local(
 762        build_client(cx),
 763        "/root/tree".as_ref(),
 764        true,
 765        fs.clone(),
 766        Default::default(),
 767        &mut cx.to_async(),
 768    )
 769    .await
 770    .unwrap();
 771    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
 772        .await;
 773
 774    tree.read_with(cx, |tree, _| {
 775        tree.as_local()
 776            .unwrap()
 777            .refresh_entries_for_paths(vec![Path::new("ignored-dir").into()])
 778    })
 779    .recv()
 780    .await;
 781
 782    cx.read(|cx| {
 783        let tree = tree.read(cx);
 784        assert!(
 785            !tree
 786                .entry_for_path("tracked-dir/tracked-file1")
 787                .unwrap()
 788                .is_ignored
 789        );
 790        assert!(
 791            tree.entry_for_path("tracked-dir/ancestor-ignored-file1")
 792                .unwrap()
 793                .is_ignored
 794        );
 795        assert!(
 796            tree.entry_for_path("ignored-dir/ignored-file1")
 797                .unwrap()
 798                .is_ignored
 799        );
 800    });
 801
 802    fs.create_file(
 803        "/root/tree/tracked-dir/tracked-file2".as_ref(),
 804        Default::default(),
 805    )
 806    .await
 807    .unwrap();
 808    fs.create_file(
 809        "/root/tree/tracked-dir/ancestor-ignored-file2".as_ref(),
 810        Default::default(),
 811    )
 812    .await
 813    .unwrap();
 814    fs.create_file(
 815        "/root/tree/ignored-dir/ignored-file2".as_ref(),
 816        Default::default(),
 817    )
 818    .await
 819    .unwrap();
 820
 821    cx.foreground().run_until_parked();
 822    cx.read(|cx| {
 823        let tree = tree.read(cx);
 824        assert!(
 825            !tree
 826                .entry_for_path("tracked-dir/tracked-file2")
 827                .unwrap()
 828                .is_ignored
 829        );
 830        assert!(
 831            tree.entry_for_path("tracked-dir/ancestor-ignored-file2")
 832                .unwrap()
 833                .is_ignored
 834        );
 835        assert!(
 836            tree.entry_for_path("ignored-dir/ignored-file2")
 837                .unwrap()
 838                .is_ignored
 839        );
 840        assert!(tree.entry_for_path(".git").unwrap().is_ignored);
 841    });
 842}
 843
 844#[gpui::test]
 845async fn test_write_file(cx: &mut TestAppContext) {
 846    init_test(cx);
 847    let dir = temp_tree(json!({
 848        ".git": {},
 849        ".gitignore": "ignored-dir\n",
 850        "tracked-dir": {},
 851        "ignored-dir": {}
 852    }));
 853
 854    let tree = Worktree::local(
 855        build_client(cx),
 856        dir.path(),
 857        true,
 858        Arc::new(RealFs),
 859        Default::default(),
 860        &mut cx.to_async(),
 861    )
 862    .await
 863    .unwrap();
 864    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
 865        .await;
 866    tree.flush_fs_events(cx).await;
 867
 868    tree.update(cx, |tree, cx| {
 869        tree.as_local().unwrap().write_file(
 870            Path::new("tracked-dir/file.txt"),
 871            "hello".into(),
 872            Default::default(),
 873            cx,
 874        )
 875    })
 876    .await
 877    .unwrap();
 878    tree.update(cx, |tree, cx| {
 879        tree.as_local().unwrap().write_file(
 880            Path::new("ignored-dir/file.txt"),
 881            "world".into(),
 882            Default::default(),
 883            cx,
 884        )
 885    })
 886    .await
 887    .unwrap();
 888
 889    tree.read_with(cx, |tree, _| {
 890        let tracked = tree.entry_for_path("tracked-dir/file.txt").unwrap();
 891        let ignored = tree.entry_for_path("ignored-dir/file.txt").unwrap();
 892        assert!(!tracked.is_ignored);
 893        assert!(ignored.is_ignored);
 894    });
 895}
 896
 897#[gpui::test]
 898async fn test_file_scan_exclusions(cx: &mut TestAppContext) {
 899    init_test(cx);
 900    let dir = temp_tree(json!({
 901        ".gitignore": "**/target\n/node_modules\n",
 902        "target": {
 903            "index": "blah2"
 904        },
 905        "node_modules": {
 906            ".DS_Store": "",
 907            "prettier": {
 908                "package.json": "{}",
 909            },
 910        },
 911        "src": {
 912            ".DS_Store": "",
 913            "foo": {
 914                "foo.rs": "mod another;\n",
 915                "another.rs": "// another",
 916            },
 917            "bar": {
 918                "bar.rs": "// bar",
 919            },
 920            "lib.rs": "mod foo;\nmod bar;\n",
 921        },
 922        ".DS_Store": "",
 923    }));
 924    cx.update(|cx| {
 925        cx.update_global::<SettingsStore, _, _>(|store, cx| {
 926            store.update_user_settings::<ProjectSettings>(cx, |project_settings| {
 927                project_settings.file_scan_exclusions =
 928                    Some(vec!["**/foo/**".to_string(), "**/.DS_Store".to_string()]);
 929            });
 930        });
 931    });
 932
 933    let tree = Worktree::local(
 934        build_client(cx),
 935        dir.path(),
 936        true,
 937        Arc::new(RealFs),
 938        Default::default(),
 939        &mut cx.to_async(),
 940    )
 941    .await
 942    .unwrap();
 943    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
 944        .await;
 945    tree.flush_fs_events(cx).await;
 946    tree.read_with(cx, |tree, _| {
 947        check_worktree_entries(
 948            tree,
 949            &[
 950                "src/foo/foo.rs",
 951                "src/foo/another.rs",
 952                "node_modules/.DS_Store",
 953                "src/.DS_Store",
 954                ".DS_Store",
 955            ],
 956            &["target", "node_modules"],
 957            &["src/lib.rs", "src/bar/bar.rs", ".gitignore"],
 958        )
 959    });
 960
 961    cx.update(|cx| {
 962        cx.update_global::<SettingsStore, _, _>(|store, cx| {
 963            store.update_user_settings::<ProjectSettings>(cx, |project_settings| {
 964                project_settings.file_scan_exclusions =
 965                    Some(vec!["**/node_modules/**".to_string()]);
 966            });
 967        });
 968    });
 969    tree.flush_fs_events(cx).await;
 970    cx.foreground().run_until_parked();
 971    tree.read_with(cx, |tree, _| {
 972        check_worktree_entries(
 973            tree,
 974            &[
 975                "node_modules/prettier/package.json",
 976                "node_modules/.DS_Store",
 977                "node_modules",
 978            ],
 979            &["target"],
 980            &[
 981                ".gitignore",
 982                "src/lib.rs",
 983                "src/bar/bar.rs",
 984                "src/foo/foo.rs",
 985                "src/foo/another.rs",
 986                "src/.DS_Store",
 987                ".DS_Store",
 988            ],
 989        )
 990    });
 991}
 992
 993#[gpui::test(iterations = 30)]
 994async fn test_create_directory_during_initial_scan(cx: &mut TestAppContext) {
 995    init_test(cx);
 996    let fs = FakeFs::new(cx.background());
 997    fs.insert_tree(
 998        "/root",
 999        json!({
1000            "b": {},
1001            "c": {},
1002            "d": {},
1003        }),
1004    )
1005    .await;
1006
1007    let tree = Worktree::local(
1008        build_client(cx),
1009        "/root".as_ref(),
1010        true,
1011        fs,
1012        Default::default(),
1013        &mut cx.to_async(),
1014    )
1015    .await
1016    .unwrap();
1017
1018    let snapshot1 = tree.update(cx, |tree, cx| {
1019        let tree = tree.as_local_mut().unwrap();
1020        let snapshot = Arc::new(Mutex::new(tree.snapshot()));
1021        let _ = tree.observe_updates(0, cx, {
1022            let snapshot = snapshot.clone();
1023            move |update| {
1024                snapshot.lock().apply_remote_update(update).unwrap();
1025                async { true }
1026            }
1027        });
1028        snapshot
1029    });
1030
1031    let entry = tree
1032        .update(cx, |tree, cx| {
1033            tree.as_local_mut()
1034                .unwrap()
1035                .create_entry("a/e".as_ref(), true, cx)
1036        })
1037        .await
1038        .unwrap();
1039    assert!(entry.is_dir());
1040
1041    cx.foreground().run_until_parked();
1042    tree.read_with(cx, |tree, _| {
1043        assert_eq!(tree.entry_for_path("a/e").unwrap().kind, EntryKind::Dir);
1044    });
1045
1046    let snapshot2 = tree.update(cx, |tree, _| tree.as_local().unwrap().snapshot());
1047    assert_eq!(
1048        snapshot1.lock().entries(true).collect::<Vec<_>>(),
1049        snapshot2.entries(true).collect::<Vec<_>>()
1050    );
1051}
1052
1053#[gpui::test]
1054async fn test_create_dir_all_on_create_entry(cx: &mut TestAppContext) {
1055    init_test(cx);
1056    let client_fake = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1057
1058    let fs_fake = FakeFs::new(cx.background());
1059    fs_fake
1060        .insert_tree(
1061            "/root",
1062            json!({
1063                "a": {},
1064            }),
1065        )
1066        .await;
1067
1068    let tree_fake = Worktree::local(
1069        client_fake,
1070        "/root".as_ref(),
1071        true,
1072        fs_fake,
1073        Default::default(),
1074        &mut cx.to_async(),
1075    )
1076    .await
1077    .unwrap();
1078
1079    let entry = tree_fake
1080        .update(cx, |tree, cx| {
1081            tree.as_local_mut()
1082                .unwrap()
1083                .create_entry("a/b/c/d.txt".as_ref(), false, cx)
1084        })
1085        .await
1086        .unwrap();
1087    assert!(entry.is_file());
1088
1089    cx.foreground().run_until_parked();
1090    tree_fake.read_with(cx, |tree, _| {
1091        assert!(tree.entry_for_path("a/b/c/d.txt").unwrap().is_file());
1092        assert!(tree.entry_for_path("a/b/c/").unwrap().is_dir());
1093        assert!(tree.entry_for_path("a/b/").unwrap().is_dir());
1094    });
1095
1096    let client_real = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1097
1098    let fs_real = Arc::new(RealFs);
1099    let temp_root = temp_tree(json!({
1100        "a": {}
1101    }));
1102
1103    let tree_real = Worktree::local(
1104        client_real,
1105        temp_root.path(),
1106        true,
1107        fs_real,
1108        Default::default(),
1109        &mut cx.to_async(),
1110    )
1111    .await
1112    .unwrap();
1113
1114    let entry = tree_real
1115        .update(cx, |tree, cx| {
1116            tree.as_local_mut()
1117                .unwrap()
1118                .create_entry("a/b/c/d.txt".as_ref(), false, cx)
1119        })
1120        .await
1121        .unwrap();
1122    assert!(entry.is_file());
1123
1124    cx.foreground().run_until_parked();
1125    tree_real.read_with(cx, |tree, _| {
1126        assert!(tree.entry_for_path("a/b/c/d.txt").unwrap().is_file());
1127        assert!(tree.entry_for_path("a/b/c/").unwrap().is_dir());
1128        assert!(tree.entry_for_path("a/b/").unwrap().is_dir());
1129    });
1130
1131    // Test smallest change
1132    let entry = tree_real
1133        .update(cx, |tree, cx| {
1134            tree.as_local_mut()
1135                .unwrap()
1136                .create_entry("a/b/c/e.txt".as_ref(), false, cx)
1137        })
1138        .await
1139        .unwrap();
1140    assert!(entry.is_file());
1141
1142    cx.foreground().run_until_parked();
1143    tree_real.read_with(cx, |tree, _| {
1144        assert!(tree.entry_for_path("a/b/c/e.txt").unwrap().is_file());
1145    });
1146
1147    // Test largest change
1148    let entry = tree_real
1149        .update(cx, |tree, cx| {
1150            tree.as_local_mut()
1151                .unwrap()
1152                .create_entry("d/e/f/g.txt".as_ref(), false, cx)
1153        })
1154        .await
1155        .unwrap();
1156    assert!(entry.is_file());
1157
1158    cx.foreground().run_until_parked();
1159    tree_real.read_with(cx, |tree, _| {
1160        assert!(tree.entry_for_path("d/e/f/g.txt").unwrap().is_file());
1161        assert!(tree.entry_for_path("d/e/f").unwrap().is_dir());
1162        assert!(tree.entry_for_path("d/e/").unwrap().is_dir());
1163        assert!(tree.entry_for_path("d/").unwrap().is_dir());
1164    });
1165}
1166
1167#[gpui::test(iterations = 100)]
1168async fn test_random_worktree_operations_during_initial_scan(
1169    cx: &mut TestAppContext,
1170    mut rng: StdRng,
1171) {
1172    init_test(cx);
1173    let operations = env::var("OPERATIONS")
1174        .map(|o| o.parse().unwrap())
1175        .unwrap_or(5);
1176    let initial_entries = env::var("INITIAL_ENTRIES")
1177        .map(|o| o.parse().unwrap())
1178        .unwrap_or(20);
1179
1180    let root_dir = Path::new("/test");
1181    let fs = FakeFs::new(cx.background()) as Arc<dyn Fs>;
1182    fs.as_fake().insert_tree(root_dir, json!({})).await;
1183    for _ in 0..initial_entries {
1184        randomly_mutate_fs(&fs, root_dir, 1.0, &mut rng).await;
1185    }
1186    log::info!("generated initial tree");
1187
1188    let worktree = Worktree::local(
1189        build_client(cx),
1190        root_dir,
1191        true,
1192        fs.clone(),
1193        Default::default(),
1194        &mut cx.to_async(),
1195    )
1196    .await
1197    .unwrap();
1198
1199    let mut snapshots = vec![worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot())];
1200    let updates = Arc::new(Mutex::new(Vec::new()));
1201    worktree.update(cx, |tree, cx| {
1202        check_worktree_change_events(tree, cx);
1203
1204        let _ = tree.as_local_mut().unwrap().observe_updates(0, cx, {
1205            let updates = updates.clone();
1206            move |update| {
1207                updates.lock().push(update);
1208                async { true }
1209            }
1210        });
1211    });
1212
1213    for _ in 0..operations {
1214        worktree
1215            .update(cx, |worktree, cx| {
1216                randomly_mutate_worktree(worktree, &mut rng, cx)
1217            })
1218            .await
1219            .log_err();
1220        worktree.read_with(cx, |tree, _| {
1221            tree.as_local().unwrap().snapshot().check_invariants(true)
1222        });
1223
1224        if rng.gen_bool(0.6) {
1225            snapshots.push(worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot()));
1226        }
1227    }
1228
1229    worktree
1230        .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
1231        .await;
1232
1233    cx.foreground().run_until_parked();
1234
1235    let final_snapshot = worktree.read_with(cx, |tree, _| {
1236        let tree = tree.as_local().unwrap();
1237        let snapshot = tree.snapshot();
1238        snapshot.check_invariants(true);
1239        snapshot
1240    });
1241
1242    for (i, snapshot) in snapshots.into_iter().enumerate().rev() {
1243        let mut updated_snapshot = snapshot.clone();
1244        for update in updates.lock().iter() {
1245            if update.scan_id >= updated_snapshot.scan_id() as u64 {
1246                updated_snapshot
1247                    .apply_remote_update(update.clone())
1248                    .unwrap();
1249            }
1250        }
1251
1252        assert_eq!(
1253            updated_snapshot.entries(true).collect::<Vec<_>>(),
1254            final_snapshot.entries(true).collect::<Vec<_>>(),
1255            "wrong updates after snapshot {i}: {snapshot:#?} {updates:#?}",
1256        );
1257    }
1258}
1259
1260#[gpui::test(iterations = 100)]
1261async fn test_random_worktree_changes(cx: &mut TestAppContext, mut rng: StdRng) {
1262    init_test(cx);
1263    let operations = env::var("OPERATIONS")
1264        .map(|o| o.parse().unwrap())
1265        .unwrap_or(40);
1266    let initial_entries = env::var("INITIAL_ENTRIES")
1267        .map(|o| o.parse().unwrap())
1268        .unwrap_or(20);
1269
1270    let root_dir = Path::new("/test");
1271    let fs = FakeFs::new(cx.background()) as Arc<dyn Fs>;
1272    fs.as_fake().insert_tree(root_dir, json!({})).await;
1273    for _ in 0..initial_entries {
1274        randomly_mutate_fs(&fs, root_dir, 1.0, &mut rng).await;
1275    }
1276    log::info!("generated initial tree");
1277
1278    let worktree = Worktree::local(
1279        build_client(cx),
1280        root_dir,
1281        true,
1282        fs.clone(),
1283        Default::default(),
1284        &mut cx.to_async(),
1285    )
1286    .await
1287    .unwrap();
1288
1289    let updates = Arc::new(Mutex::new(Vec::new()));
1290    worktree.update(cx, |tree, cx| {
1291        check_worktree_change_events(tree, cx);
1292
1293        let _ = tree.as_local_mut().unwrap().observe_updates(0, cx, {
1294            let updates = updates.clone();
1295            move |update| {
1296                updates.lock().push(update);
1297                async { true }
1298            }
1299        });
1300    });
1301
1302    worktree
1303        .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
1304        .await;
1305
1306    fs.as_fake().pause_events();
1307    let mut snapshots = Vec::new();
1308    let mut mutations_len = operations;
1309    while mutations_len > 1 {
1310        if rng.gen_bool(0.2) {
1311            worktree
1312                .update(cx, |worktree, cx| {
1313                    randomly_mutate_worktree(worktree, &mut rng, cx)
1314                })
1315                .await
1316                .log_err();
1317        } else {
1318            randomly_mutate_fs(&fs, root_dir, 1.0, &mut rng).await;
1319        }
1320
1321        let buffered_event_count = fs.as_fake().buffered_event_count();
1322        if buffered_event_count > 0 && rng.gen_bool(0.3) {
1323            let len = rng.gen_range(0..=buffered_event_count);
1324            log::info!("flushing {} events", len);
1325            fs.as_fake().flush_events(len);
1326        } else {
1327            randomly_mutate_fs(&fs, root_dir, 0.6, &mut rng).await;
1328            mutations_len -= 1;
1329        }
1330
1331        cx.foreground().run_until_parked();
1332        if rng.gen_bool(0.2) {
1333            log::info!("storing snapshot {}", snapshots.len());
1334            let snapshot = worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
1335            snapshots.push(snapshot);
1336        }
1337    }
1338
1339    log::info!("quiescing");
1340    fs.as_fake().flush_events(usize::MAX);
1341    cx.foreground().run_until_parked();
1342
1343    let snapshot = worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
1344    snapshot.check_invariants(true);
1345    let expanded_paths = snapshot
1346        .expanded_entries()
1347        .map(|e| e.path.clone())
1348        .collect::<Vec<_>>();
1349
1350    {
1351        let new_worktree = Worktree::local(
1352            build_client(cx),
1353            root_dir,
1354            true,
1355            fs.clone(),
1356            Default::default(),
1357            &mut cx.to_async(),
1358        )
1359        .await
1360        .unwrap();
1361        new_worktree
1362            .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
1363            .await;
1364        new_worktree
1365            .update(cx, |tree, _| {
1366                tree.as_local_mut()
1367                    .unwrap()
1368                    .refresh_entries_for_paths(expanded_paths)
1369            })
1370            .recv()
1371            .await;
1372        let new_snapshot =
1373            new_worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
1374        assert_eq!(
1375            snapshot.entries_without_ids(true),
1376            new_snapshot.entries_without_ids(true)
1377        );
1378    }
1379
1380    for (i, mut prev_snapshot) in snapshots.into_iter().enumerate().rev() {
1381        for update in updates.lock().iter() {
1382            if update.scan_id >= prev_snapshot.scan_id() as u64 {
1383                prev_snapshot.apply_remote_update(update.clone()).unwrap();
1384            }
1385        }
1386
1387        assert_eq!(
1388            prev_snapshot
1389                .entries(true)
1390                .map(ignore_pending_dir)
1391                .collect::<Vec<_>>(),
1392            snapshot
1393                .entries(true)
1394                .map(ignore_pending_dir)
1395                .collect::<Vec<_>>(),
1396            "wrong updates after snapshot {i}: {updates:#?}",
1397        );
1398    }
1399
1400    fn ignore_pending_dir(entry: &Entry) -> Entry {
1401        let mut entry = entry.clone();
1402        if entry.kind.is_dir() {
1403            entry.kind = EntryKind::Dir
1404        }
1405        entry
1406    }
1407}
1408
1409// The worktree's `UpdatedEntries` event can be used to follow along with
1410// all changes to the worktree's snapshot.
1411fn check_worktree_change_events(tree: &mut Worktree, cx: &mut ModelContext<Worktree>) {
1412    let mut entries = tree.entries(true).cloned().collect::<Vec<_>>();
1413    cx.subscribe(&cx.handle(), move |tree, _, event, _| {
1414        if let Event::UpdatedEntries(changes) = event {
1415            for (path, _, change_type) in changes.iter() {
1416                let entry = tree.entry_for_path(&path).cloned();
1417                let ix = match entries.binary_search_by_key(&path, |e| &e.path) {
1418                    Ok(ix) | Err(ix) => ix,
1419                };
1420                match change_type {
1421                    PathChange::Added => entries.insert(ix, entry.unwrap()),
1422                    PathChange::Removed => drop(entries.remove(ix)),
1423                    PathChange::Updated => {
1424                        let entry = entry.unwrap();
1425                        let existing_entry = entries.get_mut(ix).unwrap();
1426                        assert_eq!(existing_entry.path, entry.path);
1427                        *existing_entry = entry;
1428                    }
1429                    PathChange::AddedOrUpdated | PathChange::Loaded => {
1430                        let entry = entry.unwrap();
1431                        if entries.get(ix).map(|e| &e.path) == Some(&entry.path) {
1432                            *entries.get_mut(ix).unwrap() = entry;
1433                        } else {
1434                            entries.insert(ix, entry);
1435                        }
1436                    }
1437                }
1438            }
1439
1440            let new_entries = tree.entries(true).cloned().collect::<Vec<_>>();
1441            assert_eq!(entries, new_entries, "incorrect changes: {:?}", changes);
1442        }
1443    })
1444    .detach();
1445}
1446
1447fn randomly_mutate_worktree(
1448    worktree: &mut Worktree,
1449    rng: &mut impl Rng,
1450    cx: &mut ModelContext<Worktree>,
1451) -> Task<Result<()>> {
1452    log::info!("mutating worktree");
1453    let worktree = worktree.as_local_mut().unwrap();
1454    let snapshot = worktree.snapshot();
1455    let entry = snapshot.entries(false).choose(rng).unwrap();
1456
1457    match rng.gen_range(0_u32..100) {
1458        0..=33 if entry.path.as_ref() != Path::new("") => {
1459            log::info!("deleting entry {:?} ({})", entry.path, entry.id.0);
1460            worktree.delete_entry(entry.id, cx).unwrap()
1461        }
1462        ..=66 if entry.path.as_ref() != Path::new("") => {
1463            let other_entry = snapshot.entries(false).choose(rng).unwrap();
1464            let new_parent_path = if other_entry.is_dir() {
1465                other_entry.path.clone()
1466            } else {
1467                other_entry.path.parent().unwrap().into()
1468            };
1469            let mut new_path = new_parent_path.join(random_filename(rng));
1470            if new_path.starts_with(&entry.path) {
1471                new_path = random_filename(rng).into();
1472            }
1473
1474            log::info!(
1475                "renaming entry {:?} ({}) to {:?}",
1476                entry.path,
1477                entry.id.0,
1478                new_path
1479            );
1480            let task = worktree.rename_entry(entry.id, new_path, cx).unwrap();
1481            cx.foreground().spawn(async move {
1482                task.await?;
1483                Ok(())
1484            })
1485        }
1486        _ => {
1487            let task = if entry.is_dir() {
1488                let child_path = entry.path.join(random_filename(rng));
1489                let is_dir = rng.gen_bool(0.3);
1490                log::info!(
1491                    "creating {} at {:?}",
1492                    if is_dir { "dir" } else { "file" },
1493                    child_path,
1494                );
1495                worktree.create_entry(child_path, is_dir, cx)
1496            } else {
1497                log::info!("overwriting file {:?} ({})", entry.path, entry.id.0);
1498                worktree.write_file(entry.path.clone(), "".into(), Default::default(), cx)
1499            };
1500            cx.foreground().spawn(async move {
1501                task.await?;
1502                Ok(())
1503            })
1504        }
1505    }
1506}
1507
1508async fn randomly_mutate_fs(
1509    fs: &Arc<dyn Fs>,
1510    root_path: &Path,
1511    insertion_probability: f64,
1512    rng: &mut impl Rng,
1513) {
1514    log::info!("mutating fs");
1515    let mut files = Vec::new();
1516    let mut dirs = Vec::new();
1517    for path in fs.as_fake().paths(false) {
1518        if path.starts_with(root_path) {
1519            if fs.is_file(&path).await {
1520                files.push(path);
1521            } else {
1522                dirs.push(path);
1523            }
1524        }
1525    }
1526
1527    if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
1528        let path = dirs.choose(rng).unwrap();
1529        let new_path = path.join(random_filename(rng));
1530
1531        if rng.gen() {
1532            log::info!(
1533                "creating dir {:?}",
1534                new_path.strip_prefix(root_path).unwrap()
1535            );
1536            fs.create_dir(&new_path).await.unwrap();
1537        } else {
1538            log::info!(
1539                "creating file {:?}",
1540                new_path.strip_prefix(root_path).unwrap()
1541            );
1542            fs.create_file(&new_path, Default::default()).await.unwrap();
1543        }
1544    } else if rng.gen_bool(0.05) {
1545        let ignore_dir_path = dirs.choose(rng).unwrap();
1546        let ignore_path = ignore_dir_path.join(&*GITIGNORE);
1547
1548        let subdirs = dirs
1549            .iter()
1550            .filter(|d| d.starts_with(&ignore_dir_path))
1551            .cloned()
1552            .collect::<Vec<_>>();
1553        let subfiles = files
1554            .iter()
1555            .filter(|d| d.starts_with(&ignore_dir_path))
1556            .cloned()
1557            .collect::<Vec<_>>();
1558        let files_to_ignore = {
1559            let len = rng.gen_range(0..=subfiles.len());
1560            subfiles.choose_multiple(rng, len)
1561        };
1562        let dirs_to_ignore = {
1563            let len = rng.gen_range(0..subdirs.len());
1564            subdirs.choose_multiple(rng, len)
1565        };
1566
1567        let mut ignore_contents = String::new();
1568        for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
1569            writeln!(
1570                ignore_contents,
1571                "{}",
1572                path_to_ignore
1573                    .strip_prefix(&ignore_dir_path)
1574                    .unwrap()
1575                    .to_str()
1576                    .unwrap()
1577            )
1578            .unwrap();
1579        }
1580        log::info!(
1581            "creating gitignore {:?} with contents:\n{}",
1582            ignore_path.strip_prefix(&root_path).unwrap(),
1583            ignore_contents
1584        );
1585        fs.save(
1586            &ignore_path,
1587            &ignore_contents.as_str().into(),
1588            Default::default(),
1589        )
1590        .await
1591        .unwrap();
1592    } else {
1593        let old_path = {
1594            let file_path = files.choose(rng);
1595            let dir_path = dirs[1..].choose(rng);
1596            file_path.into_iter().chain(dir_path).choose(rng).unwrap()
1597        };
1598
1599        let is_rename = rng.gen();
1600        if is_rename {
1601            let new_path_parent = dirs
1602                .iter()
1603                .filter(|d| !d.starts_with(old_path))
1604                .choose(rng)
1605                .unwrap();
1606
1607            let overwrite_existing_dir =
1608                !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
1609            let new_path = if overwrite_existing_dir {
1610                fs.remove_dir(
1611                    &new_path_parent,
1612                    RemoveOptions {
1613                        recursive: true,
1614                        ignore_if_not_exists: true,
1615                    },
1616                )
1617                .await
1618                .unwrap();
1619                new_path_parent.to_path_buf()
1620            } else {
1621                new_path_parent.join(random_filename(rng))
1622            };
1623
1624            log::info!(
1625                "renaming {:?} to {}{:?}",
1626                old_path.strip_prefix(&root_path).unwrap(),
1627                if overwrite_existing_dir {
1628                    "overwrite "
1629                } else {
1630                    ""
1631                },
1632                new_path.strip_prefix(&root_path).unwrap()
1633            );
1634            fs.rename(
1635                &old_path,
1636                &new_path,
1637                fs::RenameOptions {
1638                    overwrite: true,
1639                    ignore_if_exists: true,
1640                },
1641            )
1642            .await
1643            .unwrap();
1644        } else if fs.is_file(&old_path).await {
1645            log::info!(
1646                "deleting file {:?}",
1647                old_path.strip_prefix(&root_path).unwrap()
1648            );
1649            fs.remove_file(old_path, Default::default()).await.unwrap();
1650        } else {
1651            log::info!(
1652                "deleting dir {:?}",
1653                old_path.strip_prefix(&root_path).unwrap()
1654            );
1655            fs.remove_dir(
1656                &old_path,
1657                RemoveOptions {
1658                    recursive: true,
1659                    ignore_if_not_exists: true,
1660                },
1661            )
1662            .await
1663            .unwrap();
1664        }
1665    }
1666}
1667
1668fn random_filename(rng: &mut impl Rng) -> String {
1669    (0..6)
1670        .map(|_| rng.sample(rand::distributions::Alphanumeric))
1671        .map(char::from)
1672        .collect()
1673}
1674
1675#[gpui::test]
1676async fn test_rename_work_directory(cx: &mut TestAppContext) {
1677    init_test(cx);
1678    let root = temp_tree(json!({
1679        "projects": {
1680            "project1": {
1681                "a": "",
1682                "b": "",
1683            }
1684        },
1685
1686    }));
1687    let root_path = root.path();
1688
1689    let tree = Worktree::local(
1690        build_client(cx),
1691        root_path,
1692        true,
1693        Arc::new(RealFs),
1694        Default::default(),
1695        &mut cx.to_async(),
1696    )
1697    .await
1698    .unwrap();
1699
1700    let repo = git_init(&root_path.join("projects/project1"));
1701    git_add("a", &repo);
1702    git_commit("init", &repo);
1703    std::fs::write(root_path.join("projects/project1/a"), "aa").ok();
1704
1705    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
1706        .await;
1707
1708    tree.flush_fs_events(cx).await;
1709
1710    cx.read(|cx| {
1711        let tree = tree.read(cx);
1712        let (work_dir, _) = tree.repositories().next().unwrap();
1713        assert_eq!(work_dir.as_ref(), Path::new("projects/project1"));
1714        assert_eq!(
1715            tree.status_for_file(Path::new("projects/project1/a")),
1716            Some(GitFileStatus::Modified)
1717        );
1718        assert_eq!(
1719            tree.status_for_file(Path::new("projects/project1/b")),
1720            Some(GitFileStatus::Added)
1721        );
1722    });
1723
1724    std::fs::rename(
1725        root_path.join("projects/project1"),
1726        root_path.join("projects/project2"),
1727    )
1728    .ok();
1729    tree.flush_fs_events(cx).await;
1730
1731    cx.read(|cx| {
1732        let tree = tree.read(cx);
1733        let (work_dir, _) = tree.repositories().next().unwrap();
1734        assert_eq!(work_dir.as_ref(), Path::new("projects/project2"));
1735        assert_eq!(
1736            tree.status_for_file(Path::new("projects/project2/a")),
1737            Some(GitFileStatus::Modified)
1738        );
1739        assert_eq!(
1740            tree.status_for_file(Path::new("projects/project2/b")),
1741            Some(GitFileStatus::Added)
1742        );
1743    });
1744}
1745
1746#[gpui::test]
1747async fn test_git_repository_for_path(cx: &mut TestAppContext) {
1748    init_test(cx);
1749    let root = temp_tree(json!({
1750        "c.txt": "",
1751        "dir1": {
1752            ".git": {},
1753            "deps": {
1754                "dep1": {
1755                    ".git": {},
1756                    "src": {
1757                        "a.txt": ""
1758                    }
1759                }
1760            },
1761            "src": {
1762                "b.txt": ""
1763            }
1764        },
1765    }));
1766
1767    let tree = Worktree::local(
1768        build_client(cx),
1769        root.path(),
1770        true,
1771        Arc::new(RealFs),
1772        Default::default(),
1773        &mut cx.to_async(),
1774    )
1775    .await
1776    .unwrap();
1777
1778    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
1779        .await;
1780    tree.flush_fs_events(cx).await;
1781
1782    tree.read_with(cx, |tree, _cx| {
1783        let tree = tree.as_local().unwrap();
1784
1785        assert!(tree.repository_for_path("c.txt".as_ref()).is_none());
1786
1787        let entry = tree.repository_for_path("dir1/src/b.txt".as_ref()).unwrap();
1788        assert_eq!(
1789            entry
1790                .work_directory(tree)
1791                .map(|directory| directory.as_ref().to_owned()),
1792            Some(Path::new("dir1").to_owned())
1793        );
1794
1795        let entry = tree
1796            .repository_for_path("dir1/deps/dep1/src/a.txt".as_ref())
1797            .unwrap();
1798        assert_eq!(
1799            entry
1800                .work_directory(tree)
1801                .map(|directory| directory.as_ref().to_owned()),
1802            Some(Path::new("dir1/deps/dep1").to_owned())
1803        );
1804
1805        let entries = tree.files(false, 0);
1806
1807        let paths_with_repos = tree
1808            .entries_with_repositories(entries)
1809            .map(|(entry, repo)| {
1810                (
1811                    entry.path.as_ref(),
1812                    repo.and_then(|repo| {
1813                        repo.work_directory(&tree)
1814                            .map(|work_directory| work_directory.0.to_path_buf())
1815                    }),
1816                )
1817            })
1818            .collect::<Vec<_>>();
1819
1820        assert_eq!(
1821            paths_with_repos,
1822            &[
1823                (Path::new("c.txt"), None),
1824                (
1825                    Path::new("dir1/deps/dep1/src/a.txt"),
1826                    Some(Path::new("dir1/deps/dep1").into())
1827                ),
1828                (Path::new("dir1/src/b.txt"), Some(Path::new("dir1").into())),
1829            ]
1830        );
1831    });
1832
1833    let repo_update_events = Arc::new(Mutex::new(vec![]));
1834    tree.update(cx, |_, cx| {
1835        let repo_update_events = repo_update_events.clone();
1836        cx.subscribe(&tree, move |_, _, event, _| {
1837            if let Event::UpdatedGitRepositories(update) = event {
1838                repo_update_events.lock().push(update.clone());
1839            }
1840        })
1841        .detach();
1842    });
1843
1844    std::fs::write(root.path().join("dir1/.git/random_new_file"), "hello").unwrap();
1845    tree.flush_fs_events(cx).await;
1846
1847    assert_eq!(
1848        repo_update_events.lock()[0]
1849            .iter()
1850            .map(|e| e.0.clone())
1851            .collect::<Vec<Arc<Path>>>(),
1852        vec![Path::new("dir1").into()]
1853    );
1854
1855    std::fs::remove_dir_all(root.path().join("dir1/.git")).unwrap();
1856    tree.flush_fs_events(cx).await;
1857
1858    tree.read_with(cx, |tree, _cx| {
1859        let tree = tree.as_local().unwrap();
1860
1861        assert!(tree
1862            .repository_for_path("dir1/src/b.txt".as_ref())
1863            .is_none());
1864    });
1865}
1866
1867#[gpui::test]
1868async fn test_git_status(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1869    init_test(cx);
1870    cx.update(|cx| {
1871        cx.update_global::<SettingsStore, _, _>(|store, cx| {
1872            store.update_user_settings::<ProjectSettings>(cx, |project_settings| {
1873                project_settings.file_scan_exclusions =
1874                    Some(vec!["**/.git".to_string(), "**/.gitignore".to_string()]);
1875            });
1876        });
1877    });
1878    const IGNORE_RULE: &'static str = "**/target";
1879
1880    let root = temp_tree(json!({
1881        "project": {
1882            "a.txt": "a",
1883            "b.txt": "bb",
1884            "c": {
1885                "d": {
1886                    "e.txt": "eee"
1887                }
1888            },
1889            "f.txt": "ffff",
1890            "target": {
1891                "build_file": "???"
1892            },
1893            ".gitignore": IGNORE_RULE
1894        },
1895
1896    }));
1897
1898    const A_TXT: &'static str = "a.txt";
1899    const B_TXT: &'static str = "b.txt";
1900    const E_TXT: &'static str = "c/d/e.txt";
1901    const F_TXT: &'static str = "f.txt";
1902    const DOTGITIGNORE: &'static str = ".gitignore";
1903    const BUILD_FILE: &'static str = "target/build_file";
1904    let project_path = Path::new("project");
1905
1906    // Set up git repository before creating the worktree.
1907    let work_dir = root.path().join("project");
1908    let mut repo = git_init(work_dir.as_path());
1909    repo.add_ignore_rule(IGNORE_RULE).unwrap();
1910    git_add(A_TXT, &repo);
1911    git_add(E_TXT, &repo);
1912    git_add(DOTGITIGNORE, &repo);
1913    git_commit("Initial commit", &repo);
1914
1915    let tree = Worktree::local(
1916        build_client(cx),
1917        root.path(),
1918        true,
1919        Arc::new(RealFs),
1920        Default::default(),
1921        &mut cx.to_async(),
1922    )
1923    .await
1924    .unwrap();
1925
1926    tree.flush_fs_events(cx).await;
1927    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
1928        .await;
1929    deterministic.run_until_parked();
1930
1931    // Check that the right git state is observed on startup
1932    tree.read_with(cx, |tree, _cx| {
1933        let snapshot = tree.snapshot();
1934        assert_eq!(snapshot.repositories().count(), 1);
1935        let (dir, _) = snapshot.repositories().next().unwrap();
1936        assert_eq!(dir.as_ref(), Path::new("project"));
1937
1938        assert_eq!(
1939            snapshot.status_for_file(project_path.join(B_TXT)),
1940            Some(GitFileStatus::Added)
1941        );
1942        assert_eq!(
1943            snapshot.status_for_file(project_path.join(F_TXT)),
1944            Some(GitFileStatus::Added)
1945        );
1946    });
1947
1948    // Modify a file in the working copy.
1949    std::fs::write(work_dir.join(A_TXT), "aa").unwrap();
1950    tree.flush_fs_events(cx).await;
1951    deterministic.run_until_parked();
1952
1953    // The worktree detects that the file's git status has changed.
1954    tree.read_with(cx, |tree, _cx| {
1955        let snapshot = tree.snapshot();
1956        assert_eq!(
1957            snapshot.status_for_file(project_path.join(A_TXT)),
1958            Some(GitFileStatus::Modified)
1959        );
1960    });
1961
1962    // Create a commit in the git repository.
1963    git_add(A_TXT, &repo);
1964    git_add(B_TXT, &repo);
1965    git_commit("Committing modified and added", &repo);
1966    tree.flush_fs_events(cx).await;
1967    deterministic.run_until_parked();
1968
1969    // The worktree detects that the files' git status have changed.
1970    tree.read_with(cx, |tree, _cx| {
1971        let snapshot = tree.snapshot();
1972        assert_eq!(
1973            snapshot.status_for_file(project_path.join(F_TXT)),
1974            Some(GitFileStatus::Added)
1975        );
1976        assert_eq!(snapshot.status_for_file(project_path.join(B_TXT)), None);
1977        assert_eq!(snapshot.status_for_file(project_path.join(A_TXT)), None);
1978    });
1979
1980    // Modify files in the working copy and perform git operations on other files.
1981    git_reset(0, &repo);
1982    git_remove_index(Path::new(B_TXT), &repo);
1983    git_stash(&mut repo);
1984    std::fs::write(work_dir.join(E_TXT), "eeee").unwrap();
1985    std::fs::write(work_dir.join(BUILD_FILE), "this should be ignored").unwrap();
1986    tree.flush_fs_events(cx).await;
1987    deterministic.run_until_parked();
1988
1989    // Check that more complex repo changes are tracked
1990    tree.read_with(cx, |tree, _cx| {
1991        let snapshot = tree.snapshot();
1992
1993        assert_eq!(snapshot.status_for_file(project_path.join(A_TXT)), None);
1994        assert_eq!(
1995            snapshot.status_for_file(project_path.join(B_TXT)),
1996            Some(GitFileStatus::Added)
1997        );
1998        assert_eq!(
1999            snapshot.status_for_file(project_path.join(E_TXT)),
2000            Some(GitFileStatus::Modified)
2001        );
2002    });
2003
2004    std::fs::remove_file(work_dir.join(B_TXT)).unwrap();
2005    std::fs::remove_dir_all(work_dir.join("c")).unwrap();
2006    std::fs::write(
2007        work_dir.join(DOTGITIGNORE),
2008        [IGNORE_RULE, "f.txt"].join("\n"),
2009    )
2010    .unwrap();
2011
2012    git_add(Path::new(DOTGITIGNORE), &repo);
2013    git_commit("Committing modified git ignore", &repo);
2014
2015    tree.flush_fs_events(cx).await;
2016    deterministic.run_until_parked();
2017
2018    let mut renamed_dir_name = "first_directory/second_directory";
2019    const RENAMED_FILE: &'static str = "rf.txt";
2020
2021    std::fs::create_dir_all(work_dir.join(renamed_dir_name)).unwrap();
2022    std::fs::write(
2023        work_dir.join(renamed_dir_name).join(RENAMED_FILE),
2024        "new-contents",
2025    )
2026    .unwrap();
2027
2028    tree.flush_fs_events(cx).await;
2029    deterministic.run_until_parked();
2030
2031    tree.read_with(cx, |tree, _cx| {
2032        let snapshot = tree.snapshot();
2033        assert_eq!(
2034            snapshot.status_for_file(&project_path.join(renamed_dir_name).join(RENAMED_FILE)),
2035            Some(GitFileStatus::Added)
2036        );
2037    });
2038
2039    renamed_dir_name = "new_first_directory/second_directory";
2040
2041    std::fs::rename(
2042        work_dir.join("first_directory"),
2043        work_dir.join("new_first_directory"),
2044    )
2045    .unwrap();
2046
2047    tree.flush_fs_events(cx).await;
2048    deterministic.run_until_parked();
2049
2050    tree.read_with(cx, |tree, _cx| {
2051        let snapshot = tree.snapshot();
2052
2053        assert_eq!(
2054            snapshot.status_for_file(
2055                project_path
2056                    .join(Path::new(renamed_dir_name))
2057                    .join(RENAMED_FILE)
2058            ),
2059            Some(GitFileStatus::Added)
2060        );
2061    });
2062}
2063
2064#[gpui::test]
2065async fn test_propagate_git_statuses(cx: &mut TestAppContext) {
2066    init_test(cx);
2067    let fs = FakeFs::new(cx.background());
2068    fs.insert_tree(
2069        "/root",
2070        json!({
2071            ".git": {},
2072            "a": {
2073                "b": {
2074                    "c1.txt": "",
2075                    "c2.txt": "",
2076                },
2077                "d": {
2078                    "e1.txt": "",
2079                    "e2.txt": "",
2080                    "e3.txt": "",
2081                }
2082            },
2083            "f": {
2084                "no-status.txt": ""
2085            },
2086            "g": {
2087                "h1.txt": "",
2088                "h2.txt": ""
2089            },
2090
2091        }),
2092    )
2093    .await;
2094
2095    fs.set_status_for_repo_via_git_operation(
2096        &Path::new("/root/.git"),
2097        &[
2098            (Path::new("a/b/c1.txt"), GitFileStatus::Added),
2099            (Path::new("a/d/e2.txt"), GitFileStatus::Modified),
2100            (Path::new("g/h2.txt"), GitFileStatus::Conflict),
2101        ],
2102    );
2103
2104    let tree = Worktree::local(
2105        build_client(cx),
2106        Path::new("/root"),
2107        true,
2108        fs.clone(),
2109        Default::default(),
2110        &mut cx.to_async(),
2111    )
2112    .await
2113    .unwrap();
2114
2115    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2116        .await;
2117
2118    cx.foreground().run_until_parked();
2119    let snapshot = tree.read_with(cx, |tree, _| tree.snapshot());
2120
2121    check_propagated_statuses(
2122        &snapshot,
2123        &[
2124            (Path::new(""), Some(GitFileStatus::Conflict)),
2125            (Path::new("a"), Some(GitFileStatus::Modified)),
2126            (Path::new("a/b"), Some(GitFileStatus::Added)),
2127            (Path::new("a/b/c1.txt"), Some(GitFileStatus::Added)),
2128            (Path::new("a/b/c2.txt"), None),
2129            (Path::new("a/d"), Some(GitFileStatus::Modified)),
2130            (Path::new("a/d/e2.txt"), Some(GitFileStatus::Modified)),
2131            (Path::new("f"), None),
2132            (Path::new("f/no-status.txt"), None),
2133            (Path::new("g"), Some(GitFileStatus::Conflict)),
2134            (Path::new("g/h2.txt"), Some(GitFileStatus::Conflict)),
2135        ],
2136    );
2137
2138    check_propagated_statuses(
2139        &snapshot,
2140        &[
2141            (Path::new("a/b"), Some(GitFileStatus::Added)),
2142            (Path::new("a/b/c1.txt"), Some(GitFileStatus::Added)),
2143            (Path::new("a/b/c2.txt"), None),
2144            (Path::new("a/d"), Some(GitFileStatus::Modified)),
2145            (Path::new("a/d/e1.txt"), None),
2146            (Path::new("a/d/e2.txt"), Some(GitFileStatus::Modified)),
2147            (Path::new("f"), None),
2148            (Path::new("f/no-status.txt"), None),
2149            (Path::new("g"), Some(GitFileStatus::Conflict)),
2150        ],
2151    );
2152
2153    check_propagated_statuses(
2154        &snapshot,
2155        &[
2156            (Path::new("a/b/c1.txt"), Some(GitFileStatus::Added)),
2157            (Path::new("a/b/c2.txt"), None),
2158            (Path::new("a/d/e1.txt"), None),
2159            (Path::new("a/d/e2.txt"), Some(GitFileStatus::Modified)),
2160            (Path::new("f/no-status.txt"), None),
2161        ],
2162    );
2163
2164    #[track_caller]
2165    fn check_propagated_statuses(
2166        snapshot: &Snapshot,
2167        expected_statuses: &[(&Path, Option<GitFileStatus>)],
2168    ) {
2169        let mut entries = expected_statuses
2170            .iter()
2171            .map(|(path, _)| snapshot.entry_for_path(path).unwrap().clone())
2172            .collect::<Vec<_>>();
2173        snapshot.propagate_git_statuses(&mut entries);
2174        assert_eq!(
2175            entries
2176                .iter()
2177                .map(|e| (e.path.as_ref(), e.git_status))
2178                .collect::<Vec<_>>(),
2179            expected_statuses
2180        );
2181    }
2182}
2183
2184fn build_client(cx: &mut TestAppContext) -> Arc<Client> {
2185    let http_client = FakeHttpClient::with_404_response();
2186    cx.read(|cx| Client::new(http_client, cx))
2187}
2188
2189#[track_caller]
2190fn git_init(path: &Path) -> git2::Repository {
2191    git2::Repository::init(path).expect("Failed to initialize git repository")
2192}
2193
2194#[track_caller]
2195fn git_add<P: AsRef<Path>>(path: P, repo: &git2::Repository) {
2196    let path = path.as_ref();
2197    let mut index = repo.index().expect("Failed to get index");
2198    index.add_path(path).expect("Failed to add a.txt");
2199    index.write().expect("Failed to write index");
2200}
2201
2202#[track_caller]
2203fn git_remove_index(path: &Path, repo: &git2::Repository) {
2204    let mut index = repo.index().expect("Failed to get index");
2205    index.remove_path(path).expect("Failed to add a.txt");
2206    index.write().expect("Failed to write index");
2207}
2208
2209#[track_caller]
2210fn git_commit(msg: &'static str, repo: &git2::Repository) {
2211    use git2::Signature;
2212
2213    let signature = Signature::now("test", "test@zed.dev").unwrap();
2214    let oid = repo.index().unwrap().write_tree().unwrap();
2215    let tree = repo.find_tree(oid).unwrap();
2216    if let Some(head) = repo.head().ok() {
2217        let parent_obj = head.peel(git2::ObjectType::Commit).unwrap();
2218
2219        let parent_commit = parent_obj.as_commit().unwrap();
2220
2221        repo.commit(
2222            Some("HEAD"),
2223            &signature,
2224            &signature,
2225            msg,
2226            &tree,
2227            &[parent_commit],
2228        )
2229        .expect("Failed to commit with parent");
2230    } else {
2231        repo.commit(Some("HEAD"), &signature, &signature, msg, &tree, &[])
2232            .expect("Failed to commit");
2233    }
2234}
2235
2236#[track_caller]
2237fn git_stash(repo: &mut git2::Repository) {
2238    use git2::Signature;
2239
2240    let signature = Signature::now("test", "test@zed.dev").unwrap();
2241    repo.stash_save(&signature, "N/A", None)
2242        .expect("Failed to stash");
2243}
2244
2245#[track_caller]
2246fn git_reset(offset: usize, repo: &git2::Repository) {
2247    let head = repo.head().expect("Couldn't get repo head");
2248    let object = head.peel(git2::ObjectType::Commit).unwrap();
2249    let commit = object.as_commit().unwrap();
2250    let new_head = commit
2251        .parents()
2252        .inspect(|parnet| {
2253            parnet.message();
2254        })
2255        .skip(offset)
2256        .next()
2257        .expect("Not enough history");
2258    repo.reset(&new_head.as_object(), git2::ResetType::Soft, None)
2259        .expect("Could not reset");
2260}
2261
2262#[allow(dead_code)]
2263#[track_caller]
2264fn git_status(repo: &git2::Repository) -> collections::HashMap<String, git2::Status> {
2265    repo.statuses(None)
2266        .unwrap()
2267        .iter()
2268        .map(|status| (status.path().unwrap().to_string(), status.status()))
2269        .collect()
2270}
2271
2272#[track_caller]
2273fn check_worktree_entries(
2274    tree: &Worktree,
2275    expected_excluded_paths: &[&str],
2276    expected_ignored_paths: &[&str],
2277    expected_tracked_paths: &[&str],
2278) {
2279    for path in expected_excluded_paths {
2280        let entry = tree.entry_for_path(path);
2281        assert!(
2282            entry.is_none(),
2283            "expected path '{path}' to be excluded, but got entry: {entry:?}",
2284        );
2285    }
2286    for path in expected_ignored_paths {
2287        let entry = tree
2288            .entry_for_path(path)
2289            .unwrap_or_else(|| panic!("Missing entry for expected ignored path '{path}'"));
2290        assert!(
2291            entry.is_ignored,
2292            "expected path '{path}' to be ignored, but got entry: {entry:?}",
2293        );
2294    }
2295    for path in expected_tracked_paths {
2296        let entry = tree
2297            .entry_for_path(path)
2298            .unwrap_or_else(|| panic!("Missing entry for expected tracked path '{path}'"));
2299        assert!(
2300            !entry.is_ignored,
2301            "expected path '{path}' to be tracked, but got entry: {entry:?}",
2302        );
2303    }
2304}
2305
2306fn init_test(cx: &mut gpui::TestAppContext) {
2307    cx.update(|cx| {
2308        cx.set_global(SettingsStore::test(cx));
2309        Project::init_settings(cx);
2310    });
2311}