gg-cli 0.41.0

GG - Gui for JJ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
mod queries;
mod session;

use anyhow::Result;
use futures_util::TryStreamExt;
use jj_lib::{
    backend::TreeValue, commit::Commit, ref_name::WorkspaceName, repo::Repo as _,
    repo_path::RepoPath, revset::RevsetStreamExt,
};
use pollster::FutureExt as _;
use std::{
    fs::{self, File},
    path::PathBuf,
    sync::Arc,
};
use tempfile::{TempDir, tempdir};
use zip::ZipArchive;

use crate::{
    messages::{ChangeId, CommitId, RevId, RevSet, queries::RevsResult},
    worker::{EventSink, WorkerSession, WorkspaceSession, queries::query_revisions},
};

pub struct NoProgress;

impl EventSink for NoProgress {
    fn send(&self, _event_name: &str, _payload: serde_json::Value) {}
}

impl Default for WorkerSession {
    fn default() -> Self {
        WorkerSession {
            force_log_page_size: None,
            latest_query: None,
            working_directory: None,
            user_settings: crate::config::tests::settings_with_gg_defaults(),
            sink: Arc::new(NoProgress),
            ignore_immutable: false,
            enable_askpass: false,
        }
    }
}

// Test Repository Maintenance
// ==========================
// The test repository is stored as `res/test-repo.zip` and extracted by `mkrepo()`.
//
// To modify the test repository:
// 1. Extract test-repo.zip to a temporary directory
// 2. Use `jj` CLI commands to create/modify commits
// 3. Verify new commits are mutable: `jj log -r 'mutable()'`
// 4. Re-zip the directory (excluding any OS-specific files)
// 5. Update the `revs` module with new commit IDs
//
// The `revs` module provides helpers for known commits. Use `jj log` to find change/commit IDs.

pub fn mkrepo() -> TempDir {
    let repo_dir = tempdir().unwrap();
    let mut archive_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    archive_path.push("res/test-repo.zip");
    let archive_file = File::open(&archive_path).unwrap();
    let mut archive = ZipArchive::new(archive_file).unwrap();

    archive.extract(repo_dir.path()).unwrap();

    repo_dir
}

pub fn mkid(xid: &str, cid: &str) -> RevId {
    RevId {
        change: ChangeId {
            hex: xid.to_owned(),
            prefix: xid.to_owned(),
            rest: "".to_owned(),
            offset: None,
            is_divergent: false,
        },
        commit: CommitId {
            hex: cid.to_owned(),
            prefix: cid.to_owned(),
            rest: "".to_owned(),
        },
    }
}

/// Resolve a commit by change ID, even if it was rewritten and has a new commit ID.
/// Use this to verify commit state after mutations that rewrite commits.
pub fn get_by_chid(ws: &WorkspaceSession, rev_id: &RevId) -> Result<Commit> {
    use jj_lib::repo::Repo;

    let revset = ws.evaluate_revset_str(&rev_id.change.hex)?;
    let store = ws.repo().store();
    let mut stream = revset.as_ref().stream().commits(store);
    match stream.try_next().block_on()? {
        Some(commit) => Ok(commit),
        None => anyhow::bail!("Change {} not found", rev_id.change.hex),
    }
}

pub async fn query_by_chid(ws: &WorkspaceSession<'_>, change_hex: &str) -> Result<RevsResult> {
    let revset = ws.evaluate_revset_str(change_hex)?;
    let store = ws.repo().store();
    let commits: Vec<_> = revset.stream().commits(store).try_collect().await?;
    let commit = commits
        .first()
        .ok_or_else(|| anyhow::anyhow!("not found"))?;
    let id = ws.format_id(commit);
    query_by_id(ws, id).await
}

/// Helper to get a single revision's display details (changes, conflicts, etc.)
pub async fn query_by_id(
    ws: &crate::worker::gui_util::WorkspaceSession<'_>,
    id: RevId,
) -> Result<RevsResult> {
    query_revisions(ws, RevSet::singleton(id)).await
}

pub mod revs {
    use crate::messages::RevId;

    use super::mkid;

    /// The working copy commit (empty, child of main)
    pub fn working_copy() -> RevId {
        mkid("kvptxrkr", "e7080cd830960125c13e276aa056c811e7ce600a")
    }

    /// The main bookmark commit (renamed c.txt)
    pub fn main_bookmark() -> RevId {
        mkid("wnpusytq", "025843422c8f5374a4160fe79195b92d6ec3c6ee")
    }

    /// Bookmark added to immutable_heads()
    pub fn immutable_bookmark() -> RevId {
        mkid("ywknyuol", "f86298e8166104062708cde7c1cf697022b4cf8b")
    }

    /// An immutable commit (parent of immutable_bookmark)
    pub fn immutable_parent() -> RevId {
        mkid("nxxylmpu", "fa32b17fcc7f44f176539feec6c13af413924329")
    }

    /// An immutable commit (grandparent of immutable_bookmark)
    pub fn immutable_grandparent() -> RevId {
        mkid("tqnnuvwv", "983d594962e861aa155c8cee9e49122978cec40f")
    }

    /// A commit with a conflict in b.txt
    pub fn conflict_bookmark() -> RevId {
        mkid("pkullrwy", "18edcaea9423cd9975c3f1ffbf07e00fe3ecc47a")
    }

    /// Child of conflict_bookmark that resolves the conflict
    pub fn resolve_conflict() -> RevId {
        mkid("yvtwywll", "461b914dbab3347a7c789bac200f0e135d03807e")
    }

    /// Child of conflict_bookmark that does NOT resolve the conflict
    /// Adds unrelated.txt but keeps b.txt in conflict state
    pub fn inherited_conflict() -> RevId {
        mkid("tlxnptkw", "7241ca5bfef9f77eccb9544f8a69c61025d766c1")
    }

    /// Merge commit that introduces conflict in conflict_chain.txt
    /// Child of resolve_conflict via two bookmarks (chain bookmark A and B)
    pub fn chain_conflict() -> RevId {
        mkid("vwxxopnk", "f80d4defdcf8627e7e8dca52fefb250e2e05d133")
    }

    /// Child of chain_conflict that resolves the conflict in conflict_chain.txt
    pub fn chain_resolved() -> RevId {
        mkid("lwzoqltx", "8c812d8bacb3ccb4ce4a3eff30e1221eef3373ca")
    }

    /// Mutable commit that changed b.txt from "1" to "11"
    pub fn hunk_source() -> RevId {
        mkid("xoooutru", "1b3949ce69432a74966165308ac30f5501fd9a83")
    }

    /// Contains hunk_test.txt with 5 lines: line1-line5
    pub fn hunk_base() -> RevId {
        mkid("xrqnzmzy", "71627400c7459f17fa45ea5dfd2572830f5c26ab")
    }

    /// Child of hunk_base, modifies line 2: line2 -> modified2
    pub fn hunk_child_single() -> RevId {
        mkid("rwpmyumq", "cb56950fd81e14bcf30ea657f3c69a99ca743229")
    }

    /// Child of hunk_base, modifies lines 2 and 4: line2 -> changed2, line4 -> changed4
    pub fn hunk_child_multi() -> RevId {
        mkid("nwywsplo", "b234894cba9641611cbd3e0648dd2ac3c634c272")
    }

    /// Child of hunk_base, adds lines 6-8: new6, new7, new8
    pub fn hunk_sibling() -> RevId {
        mkid("lpvoqxrx", "489cf8d28d84c3477c65f89a856ba70ac91081bb")
    }

    /// Child of hunk_child_single, modifies line 3: line3 -> grandchild3
    /// This creates a 3-level hierarchy: hunk_base -> hunk_child_single -> hunk_grandchild
    pub fn hunk_grandchild() -> RevId {
        mkid("onsonsrz", "1c073dfca738cdca246a1f8818f8f67bb3b4c8e6")
    }

    /// Contains small.txt with 2 lines: line1, line2
    pub fn small_parent() -> RevId {
        mkid("uqpmkpqu", "cd1a7fc72d71051f3a336a40da45d01d1d1a624c")
    }

    /// Child of small_parent, modifies line 2: line2 -> changed
    pub fn small_child() -> RevId {
        mkid("vnstymnv", "f08d8a81983eb0c7849359b1555dca2d93016b54")
    }
}

#[tokio::test]
async fn wc_path_is_visible() -> Result<()> {
    let repo = mkrepo();

    let mut session = WorkerSession::default();
    let ws = session.load_workspace(repo.path()).await?;

    let commit = ws.get_commit(ws.wc_id())?;
    let value = commit
        .tree()
        .path_value(RepoPath::from_internal_string("a.txt")?)
        .await?;

    assert!(value.is_resolved());
    assert!(
        value
            .first()
            .as_ref()
            .is_some_and(|x| matches!(x, TreeValue::File { .. }))
    );

    Ok(())
}

#[tokio::test]
async fn snapshot_updates_wc_if_changed() -> Result<()> {
    let repo = mkrepo();

    let mut session = WorkerSession::default();
    let mut ws = session.load_workspace(repo.path()).await?;
    let old_wc = ws.wc_id().clone();

    assert!(!ws.import_and_snapshot(true, false).await?);
    assert_eq!(&old_wc, ws.wc_id());

    fs::write(repo.path().join("new.txt"), []).unwrap();

    assert!(ws.import_and_snapshot(true, false).await?);
    assert_ne!(&old_wc, ws.wc_id());

    Ok(())
}

#[tokio::test]
async fn transaction_updates_wc_if_snapshot() -> Result<()> {
    let repo = mkrepo();

    let mut session = WorkerSession::default();
    let mut ws = session.load_workspace(repo.path()).await?;
    let old_wc = ws.wc_id().clone();

    fs::write(repo.path().join("new.txt"), []).unwrap();

    let tx = ws.start_transaction().await?;
    ws.finish_transaction(tx, "do nothing").await?;

    assert_ne!(&old_wc, ws.wc_id());

    Ok(())
}

#[tokio::test]
async fn transaction_snapshot_path_is_visible() -> Result<()> {
    let repo = mkrepo();

    let mut session = WorkerSession::default();
    let mut ws = session.load_workspace(repo.path()).await?;

    fs::write(repo.path().join("new.txt"), []).unwrap();

    let tx = ws.start_transaction().await?;
    ws.finish_transaction(tx, "do nothing").await?;

    let commit = ws.get_commit(ws.wc_id())?;
    let value = commit
        .tree()
        .path_value(RepoPath::from_internal_string("new.txt")?)
        .await?;

    assert!(value.is_resolved());
    assert!(
        value
            .first()
            .as_ref()
            .is_some_and(|x| matches!(x, TreeValue::File { .. }))
    );

    Ok(())
}

// serialize tests that mutate XDG_CONFIG_HOME
static XDG_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

#[tokio::test]
async fn snapshot_respects_xdg_gitignore_colocated() -> Result<()> {
    let _lock = XDG_ENV_LOCK.lock().unwrap();

    let xdg_dir = tempdir()?;
    let ignore_dir = xdg_dir.path().join("git");
    fs::create_dir_all(&ignore_dir)?;
    fs::write(ignore_dir.join("ignore"), "*.ignored\n")?;

    unsafe { std::env::set_var("XDG_CONFIG_HOME", xdg_dir.path()) };
    let _guard = SetVarGuard("XDG_CONFIG_HOME");

    let workspace_dir = tempdir()?;
    let mut session = WorkerSession::default();
    session
        .init_repository(&workspace_dir.path().to_owned(), true)
        .await?;
    let mut ws = session.load_workspace(workspace_dir.path()).await?;

    fs::write(workspace_dir.path().join("tracked.txt"), "hello")?;
    fs::write(workspace_dir.path().join("should_be.ignored"), "hidden")?;

    assert!(ws.import_and_snapshot(true, false).await?);

    let commit = ws.get_commit(ws.wc_id())?;
    let tracked = commit
        .tree()
        .path_value(RepoPath::from_internal_string("tracked.txt")?)
        .await?;
    let ignored = commit
        .tree()
        .path_value(RepoPath::from_internal_string("should_be.ignored")?)
        .await?;

    assert!(tracked.is_resolved() && tracked.first().as_ref().is_some());
    assert!(ignored.is_absent());

    Ok(())
}

#[tokio::test]
async fn snapshot_respects_xdg_gitignore_internal() -> Result<()> {
    let _lock = XDG_ENV_LOCK.lock().unwrap();

    let xdg_dir = tempdir()?;
    let ignore_dir = xdg_dir.path().join("git");
    fs::create_dir_all(&ignore_dir)?;
    fs::write(ignore_dir.join("ignore"), "*.ignored\n")?;

    unsafe { std::env::set_var("XDG_CONFIG_HOME", xdg_dir.path()) };
    let _guard = SetVarGuard("XDG_CONFIG_HOME");

    let workspace_dir = tempdir()?;
    let mut session = WorkerSession::default();
    session
        .init_repository(&workspace_dir.path().to_owned(), false)
        .await?;
    let mut ws = session.load_workspace(workspace_dir.path()).await?;

    fs::write(workspace_dir.path().join("tracked.txt"), "hello")?;
    fs::write(workspace_dir.path().join("should_be.ignored"), "hidden")?;

    assert!(ws.import_and_snapshot(true, false).await?);

    let commit = ws.get_commit(ws.wc_id())?;
    let tracked = commit
        .tree()
        .path_value(RepoPath::from_internal_string("tracked.txt")?)
        .await?;
    let ignored = commit
        .tree()
        .path_value(RepoPath::from_internal_string("should_be.ignored")?)
        .await?;

    assert!(tracked.is_resolved() && tracked.first().as_ref().is_some());
    assert!(ignored.is_absent());

    Ok(())
}

#[tokio::test]
async fn add_workspace_creates_new_workspace() -> Result<()> {
    let repo = mkrepo();

    let mut session = WorkerSession::default();
    let mut ws = session.load_workspace(repo.path()).await?;
    let original_wc = ws.wc_id().clone();

    let new_ws_path = repo.path().join("second-workspace");
    ws.add_workspace("second".to_owned(), new_ws_path.clone())
        .await?;

    // new workspace is registered in the view
    assert!(
        ws.view()
            .get_wc_commit_id(WorkspaceName::new("second"))
            .is_some()
    );

    // new workspace has a .jj directory
    assert!(new_ws_path.join(".jj").exists());

    // original workspace's WC didn't change identity
    assert_eq!(&original_wc, ws.wc_id());

    // new workspace's WC commit is different from the original
    let new_wc_id = ws
        .view()
        .get_wc_commit_id(WorkspaceName::new("second"))
        .unwrap();
    assert_ne!(new_wc_id, ws.wc_id());

    // new WC commit has the same parents as the original
    let original_parents = ws.get_commit(ws.wc_id())?.parents().await?;
    let new_parents = ws.get_commit(new_wc_id)?.parents().await?;
    assert_eq!(
        original_parents.iter().map(|c| c.id()).collect::<Vec<_>>(),
        new_parents.iter().map(|c| c.id()).collect::<Vec<_>>()
    );

    Ok(())
}

#[tokio::test]
async fn add_workspace_rejects_duplicate_name() -> Result<()> {
    let repo = mkrepo();

    let mut session = WorkerSession::default();
    let mut ws = session.load_workspace(repo.path()).await?;

    let new_ws_path = repo.path().join("second-workspace");
    ws.add_workspace("second".to_owned(), new_ws_path).await?;

    let err = ws
        .add_workspace("second".to_owned(), repo.path().join("third"))
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("already exists"),
        "unexpected error: {err}"
    );

    Ok(())
}

#[tokio::test]
async fn add_workspace_rejects_empty_name() -> Result<()> {
    let repo = mkrepo();

    let mut session = WorkerSession::default();
    let mut ws = session.load_workspace(repo.path()).await?;

    let err = ws
        .add_workspace("".to_owned(), repo.path().join("empty-name"))
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("cannot be empty"),
        "unexpected error: {err}"
    );

    Ok(())
}

#[tokio::test]
async fn add_workspace_rejects_nonempty_destination() -> Result<()> {
    let repo = mkrepo();

    let mut session = WorkerSession::default();
    let mut ws = session.load_workspace(repo.path()).await?;

    let nonempty = repo.path().join("nonempty");
    fs::create_dir(&nonempty)?;
    fs::write(nonempty.join("file.txt"), "content")?;

    let err = ws
        .add_workspace("second".to_owned(), nonempty)
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("not an empty directory"),
        "unexpected error: {err}"
    );

    Ok(())
}

#[tokio::test]
async fn forget_workspace_removes_workspace() -> Result<()> {
    let repo = mkrepo();

    let mut session = WorkerSession::default();
    let mut ws = session.load_workspace(repo.path()).await?;

    // add a workspace, then forget it
    let new_ws_path = repo.path().join("to-forget");
    ws.add_workspace("to-forget".to_owned(), new_ws_path.clone())
        .await?;
    assert!(
        ws.view()
            .get_wc_commit_id(WorkspaceName::new("to-forget"))
            .is_some()
    );

    ws.forget_workspace("to-forget".to_owned()).await?;

    // workspace is no longer in the view
    assert!(
        ws.view()
            .get_wc_commit_id(WorkspaceName::new("to-forget"))
            .is_none()
    );

    // directory is NOT deleted (matches jj behavior)
    assert!(new_ws_path.exists());

    Ok(())
}

#[tokio::test]
async fn forget_workspace_rejects_current() -> Result<()> {
    let repo = mkrepo();

    let mut session = WorkerSession::default();
    let mut ws = session.load_workspace(repo.path()).await?;
    let current_name = ws.name().as_str().to_owned();

    let err = ws.forget_workspace(current_name).await.unwrap_err();
    assert!(
        err.to_string().contains("cannot forget the current"),
        "unexpected error: {err}"
    );

    Ok(())
}

#[tokio::test]
async fn forget_workspace_rejects_nonexistent() -> Result<()> {
    let repo = mkrepo();

    let mut session = WorkerSession::default();
    let mut ws = session.load_workspace(repo.path()).await?;

    let err = ws
        .forget_workspace("nonexistent".to_owned())
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("not found"),
        "unexpected error: {err}"
    );

    Ok(())
}

#[tokio::test]
async fn list_workspaces_returns_sorted_names() -> Result<()> {
    let repo = mkrepo();

    let mut session = WorkerSession::default();
    let mut ws = session.load_workspace(repo.path()).await?;
    let current_name = ws.name().as_symbol().to_string();

    // initially only the current workspace exists
    assert_eq!(ws.list_workspaces(), vec![current_name.clone()]);

    // add two more workspaces
    ws.add_workspace("alpha".to_owned(), repo.path().join("alpha"))
        .await?;
    ws.add_workspace("zeta".to_owned(), repo.path().join("zeta"))
        .await?;

    // all three names are present and sorted
    assert_eq!(
        ws.list_workspaces(),
        vec!["alpha".to_owned(), current_name, "zeta".to_owned()]
    );

    Ok(())
}

/// RAII guard that removes an env var on drop
struct SetVarGuard(&'static str);

impl Drop for SetVarGuard {
    fn drop(&mut self) {
        unsafe { std::env::remove_var(self.0) };
    }
}