worktree_tests.rs

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