jj-cz 1.1.0

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

use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    sync::{Arc, Mutex},
};

use etcetera::BaseStrategy;
use futures_util::StreamExt;
use jj_lib::{
    backend::CommitId,
    config::{ConfigSource, StackedConfig},
    fileset::FilesetAliasesMap,
    ref_name::WorkspaceNameBuf,
    repo::{ReadonlyRepo, Repo, StoreFactories},
    repo_path::RepoPathUiConverter,
    revset::{
        self, RevsetAliasesMap, RevsetDiagnostics, RevsetExtensions, RevsetParseContext,
        RevsetWorkspaceContext, SymbolResolver, SymbolResolverExtension,
    },
    settings::UserSettings,
    workspace::{Workspace, default_working_copy_factories},
};

use crate::error::Error;
use crate::jj::JjExecutor;

/// JjLib provides jj repository operations via jj-lib 0.39.0
#[derive(Debug)]
pub struct JjLib {
    working_dir: PathBuf,
    repo: Mutex<Arc<ReadonlyRepo>>,
    workspace_name: WorkspaceNameBuf,
    workspace_root: PathBuf,
}

impl JjLib {
    /// Create a new JjLib instance using the current working directory
    pub async fn new() -> Result<Self, Error> {
        let working_dir = std::env::current_dir()?;
        let (repo, workspace_name, workspace_root) = Self::load_repo(&working_dir).await?;
        Ok(Self {
            working_dir,
            repo: repo.into(),
            workspace_name,
            workspace_root,
        })
    }

    /// Create a new JjLib instance with a specific working directory
    pub async fn with_working_dir(path: impl AsRef<Path>) -> Result<Self, Error> {
        let (repo, workspace_name, workspace_root) = Self::load_repo(path.as_ref()).await?;
        Ok(Self {
            working_dir: path.as_ref().to_path_buf(),
            repo: repo.into(),
            workspace_name,
            workspace_root,
        })
    }

    /// Load the repo from the given working directory
    async fn load_repo(
        working_dir: &Path,
    ) -> Result<(Arc<ReadonlyRepo>, WorkspaceNameBuf, PathBuf), Error> {
        let settings = Self::load_settings()?;
        let store_factories = StoreFactories::default();
        let wc_factories = default_working_copy_factories();

        let workspace = Workspace::load(&settings, working_dir, &store_factories, &wc_factories)
            .map_err(|_| Error::NotARepository)?;
        let repo =
            workspace
                .repo_loader()
                .load_at_head()
                .await
                .map_err(|e| Error::JjOperation {
                    context: e.to_string(),
                })?;
        Ok((
            repo,
            workspace.workspace_name().to_owned(),
            workspace.workspace_root().to_path_buf(),
        ))
    }

    fn load_settings() -> Result<UserSettings, Error> {
        let mut config = StackedConfig::with_defaults();
        for path in Self::user_config_paths() {
            if path.is_dir() {
                config.load_dir(ConfigSource::User, &path).map_err(|e| {
                    Error::FailedReadingConfig {
                        context: e.to_string(),
                    }
                })?;
            } else if path.exists() {
                config.load_file(ConfigSource::User, path).map_err(|e| {
                    Error::FailedReadingConfig {
                        context: e.to_string(),
                    }
                })?;
            }
        }
        UserSettings::from_config(config).map_err(|e| Error::FailedReadingConfig {
            context: e.to_string(),
        })
    }

    /// Resolves user config file paths following the same logic as the jj CLI:
    /// 1. `$JJ_CONFIG` (colon-separated list), if set
    /// 2. `~/.jjconfig.toml` (if it exists, or no platform config dir is available)
    /// 3. Platform config dir `/jj/config.toml` (e.g. `~/.config/jj/config.toml`)
    /// 4. Platform config dir `/jj/conf.d/` (if it exists)
    fn user_config_paths() -> Vec<PathBuf> {
        if let Ok(paths) = std::env::var("JJ_CONFIG") {
            return std::env::split_paths(&paths)
                .filter(|p| !p.as_os_str().is_empty())
                .collect();
        }

        let home_dir = etcetera::home_dir().ok();
        let config_dir = etcetera::choose_base_strategy()
            .ok()
            .map(|s| s.config_dir());

        let home_config = home_dir.as_ref().map(|h| h.join(".jjconfig.toml"));
        let platform_config = config_dir
            .as_ref()
            .map(|c| c.join("jj").join("config.toml"));
        let platform_conf_d = config_dir.as_ref().map(|c| c.join("jj").join("conf.d"));

        let mut paths = Vec::new();

        if let Some(path) = home_config
            && (path.exists() || platform_config.is_none())
        {
            paths.push(path);
        }
        if let Some(path) = platform_config {
            paths.push(path);
        }
        if let Some(path) = platform_conf_d
            && path.exists()
        {
            paths.push(path);
        }

        paths
    }

    /// Resolve a revset string to a commit ID
    async fn get_commit_id(&self, revset: &str) -> Result<CommitId, Error> {
        let context = RevsetParseContext {
            workspace: Some(RevsetWorkspaceContext {
                workspace_name: &self.workspace_name,
                path_converter: &RepoPathUiConverter::Fs {
                    cwd: self.working_dir.clone(),
                    base: self.workspace_root.clone(),
                },
            }),
            aliases_map: &RevsetAliasesMap::new(),
            fileset_aliases_map: &FilesetAliasesMap::new(),
            local_variables: HashMap::new(),
            user_email: "",
            date_pattern_context: chrono::Local::now().into(),
            default_ignored_remote: None,
            use_glob_by_default: false,
            extensions: &RevsetExtensions::default(),
        };
        let mut diagnostic = RevsetDiagnostics::new();
        let repo = self.repo.lock()?.clone();
        let symbol_resolver =
            SymbolResolver::new(&*repo, &([] as [Box<dyn SymbolResolverExtension>; 0]));
        let revision = revset::parse(&mut diagnostic, revset, &context)
            .map_err(|e| Error::from_revset_parse_error(revset, e))?
            .resolve_user_expression(&*repo, &symbol_resolver)
            .map_err(|e| Error::from_revset_resolution_error(revset, e))?
            .evaluate(&*repo)
            .map_err(|e| Error::from_revset_evaluation_error(revset, e))?;
        let mut all_ids = revision.commit_change_ids();
        let commit_id = all_ids
            .next()
            .await
            .ok_or(Error::RevsetResolutionError {
                revset: revset.into(),
                context: "No matching revision".to_string(),
            })?
            .map_err(|e| Error::from_revset_evaluation_error(revset, e))?;
        match all_ids.next().await {
            None => Ok(commit_id.0),
            Some(_) => Err(Error::MultipleRevisions {
                revset: revset.to_string(),
            }),
        }
    }
}

#[async_trait::async_trait(?Send)]
impl JjExecutor for JjLib {
    async fn is_repository(&self) -> Result<bool, Error> {
        let settings = Self::load_settings()?;
        let store_factories = StoreFactories::default();
        let wc_factories = default_working_copy_factories();
        Ok(Workspace::load(
            &settings,
            &self.working_dir,
            &store_factories,
            &wc_factories,
        )
        .is_ok())
    }

    async fn describe(&self, revset: &str, message: &str) -> Result<(), Error> {
        let commit_id = self.get_commit_id(revset).await?;
        let repo = self.repo.lock()?.clone();
        let mut tx = repo.start_transaction();
        let commit = tx
            .repo()
            .store()
            .get_commit(&commit_id)
            .map_err(|e| Error::JjOperation {
                context: e.to_string(),
            })?;

        tx.repo_mut()
            .rewrite_commit(&commit)
            .set_description(message)
            .write()
            .await
            .map_err(|e| Error::JjOperation {
                context: e.to_string(),
            })?;

        tx.repo_mut()
            .rebase_descendants()
            .await
            .map_err(|e| Error::JjOperation {
                context: format!("{e:?}"),
            })?;

        let new_repo = tx
            .commit("jj-cz: update commit description")
            .await
            .map_err(|e| Error::JjOperation {
                context: e.to_string(),
            })?;
        *self.repo.lock()? = new_repo;

        Ok(())
    }

    async fn get_description(&self, revset: &str) -> Result<String, Error> {
        let commit_id = self.get_commit_id(revset).await?;
        let repo = self.repo.lock()?.clone();
        let commit = repo
            .store()
            .get_commit(&commit_id)
            .map_err(|e| Error::JjOperation {
                context: e.to_string(),
            })?;
        Ok(commit.description().trim_end().to_string())
    }

    async fn new_revision(&self, revset: &str) -> Result<(), Error> {
        let commit_id = self.get_commit_id(revset).await?;
        let repo = self.repo.lock()?.clone();
        let mut tx = repo.start_transaction();
        let parent_commit =
            tx.repo()
                .store()
                .get_commit(&commit_id)
                .map_err(|e| Error::JjOperation {
                    context: e.to_string(),
                })?;
        tx.repo_mut()
            .check_out(self.workspace_name.clone(), &parent_commit)
            .await
            .map_err(|e| Error::JjOperation {
                context: e.to_string(),
            })?;
        let new_repo =
            tx.commit("jj-cz: create new revision")
                .await
                .map_err(|e| Error::JjOperation {
                    context: e.to_string(),
                })?;
        *self.repo.lock()? = new_repo;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Initialize a jj repository in the given directory using jj-lib directly
    async fn init_jj_repo(dir: &Path) -> Result<(), String> {
        let settings = JjLib::load_settings().map_err(|e| e.to_string())?;
        Workspace::init_internal_git(&settings, dir)
            .await
            .map(|_| ())
            .map_err(|e| format!("Failed to init jj repo: {e}"))
    }

    async fn get_commit_description(dir: &Path) -> Result<String, String> {
        let settings = JjLib::load_settings().map_err(|e| e.to_string())?;
        let store_factories = StoreFactories::default();
        let wc_factories = default_working_copy_factories();

        let workspace = Workspace::load(&settings, dir, &store_factories, &wc_factories)
            .map_err(|e| format!("Failed to load workspace: {e}"))?;

        let repo = workspace
            .repo_loader()
            .load_at_head()
            .await
            .map_err(|e| format!("Failed to load repo: {e}"))?;

        let wc_commit_id = repo
            .view()
            .get_wc_commit_id(jj_lib::ref_name::WorkspaceName::DEFAULT)
            .ok_or_else(|| "No working copy commit found".to_string())?
            .clone();

        let wc_commit = repo
            .store()
            .get_commit(&wc_commit_id)
            .map_err(|e| format!("Failed to get commit: {e}"))?;

        Ok(wc_commit.description().trim_end().to_string())
    }

    #[tokio::test]
    async fn is_repository_returns_true_inside_jj_repo() {
        let temp_dir = assert_fs::TempDir::new().unwrap();
        init_jj_repo(temp_dir.path())
            .await
            .expect("Failed to init jj repo");

        let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();
        let result = executor.is_repository().await;

        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[tokio::test]
    async fn is_repository_returns_false_outside_jj_repo() {
        let temp_dir = assert_fs::TempDir::new().unwrap();

        let executor = JjLib::with_working_dir(temp_dir.path()).await;
        assert!(executor.is_err());
    }

    #[tokio::test]
    async fn describe_updates_commit_description() {
        let temp_dir = assert_fs::TempDir::new().unwrap();
        init_jj_repo(temp_dir.path())
            .await
            .expect("Failed to init jj repo");

        let test_message = "test: initial commit";
        let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();

        let result = executor.describe("@", test_message).await;
        assert!(result.is_ok(), "describe failed: {result:?}");

        let actual = get_commit_description(temp_dir.path())
            .await
            .expect("Failed to get description");
        assert_eq!(actual, test_message);
    }

    #[tokio::test]
    async fn describe_handles_special_characters() {
        let temp_dir = assert_fs::TempDir::new().unwrap();
        init_jj_repo(temp_dir.path())
            .await
            .expect("Failed to init jj repo");

        let test_message = "feat: add feature with special chars !@#$%^&*()";
        let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();

        let result = executor.describe("@", test_message).await;
        assert!(result.is_ok());

        let actual = get_commit_description(temp_dir.path())
            .await
            .expect("Failed to get description");
        assert_eq!(actual, test_message);
    }

    #[tokio::test]
    async fn describe_handles_unicode() {
        let temp_dir = assert_fs::TempDir::new().unwrap();
        init_jj_repo(temp_dir.path())
            .await
            .expect("Failed to init jj repo");

        let test_message = "docs: add unicode support 🎉 🚀";
        let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();

        let result = executor.describe("@", test_message).await;
        assert!(result.is_ok());

        let actual = get_commit_description(temp_dir.path())
            .await
            .expect("Failed to get description");
        assert_eq!(actual, test_message);
    }

    #[tokio::test]
    async fn describe_handles_multiline_message() {
        let temp_dir = assert_fs::TempDir::new().unwrap();
        init_jj_repo(temp_dir.path())
            .await
            .expect("Failed to init jj repo");

        let test_message = "feat: add feature\n\nThis is a multiline\ndescription";
        let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();

        let result = executor.describe("@", test_message).await;
        assert!(result.is_ok());

        let actual = get_commit_description(temp_dir.path())
            .await
            .expect("Failed to get description");
        assert_eq!(actual, test_message);
    }

    #[tokio::test]
    async fn describe_fails_outside_repo() {
        // with_working_dir returns Err when not in a repo
        let temp_dir = assert_fs::TempDir::new().unwrap();
        let executor = JjLib::with_working_dir(temp_dir.path()).await;
        assert!(executor.is_err());

        let valid_dir = assert_fs::TempDir::new().unwrap();
        init_jj_repo(valid_dir.path())
            .await
            .expect("Failed to init jj repo");
        let executor = JjLib::with_working_dir(valid_dir.path()).await.unwrap();
        let result = executor
            .describe("this-bookmark-does-not-exist", "test: should fail")
            .await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn describe_can_be_called_multiple_times() {
        let temp_dir = assert_fs::TempDir::new().unwrap();
        init_jj_repo(temp_dir.path())
            .await
            .expect("Failed to init jj repo");

        let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();

        executor
            .describe("@", "feat: first commit")
            .await
            .expect("First describe failed");
        let desc1 = get_commit_description(temp_dir.path())
            .await
            .expect("Failed to get first description");
        assert_eq!(desc1, "feat: first commit");

        executor
            .describe("@", "feat: updated commit")
            .await
            .expect("Second describe failed");
        let desc2 = get_commit_description(temp_dir.path())
            .await
            .expect("Failed to get second description");
        assert_eq!(desc2, "feat: updated commit");
    }

    #[tokio::test]
    async fn get_description_returns_empty_for_fresh_commit() {
        let temp_dir = assert_fs::TempDir::new().unwrap();
        init_jj_repo(temp_dir.path())
            .await
            .expect("Failed to init jj repo");

        let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();
        let desc = executor
            .get_description("@")
            .await
            .expect("get_description failed");

        assert_eq!(desc, "");
    }

    #[tokio::test]
    async fn get_description_reflects_describe_on_same_executor() {
        let temp_dir = assert_fs::TempDir::new().unwrap();
        init_jj_repo(temp_dir.path())
            .await
            .expect("Failed to init jj repo");

        let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();
        let message = "feat: test get_description";

        executor
            .describe("@", message)
            .await
            .expect("describe failed");
        let desc = executor
            .get_description("@")
            .await
            .expect("get_description failed");

        assert_eq!(desc, message);
    }

    #[tokio::test]
    async fn multiple_revisions_error_for_multi_commit_revset() {
        let temp_dir = assert_fs::TempDir::new().unwrap();
        init_jj_repo(temp_dir.path())
            .await
            .expect("Failed to init jj repo");

        let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();
        let result = executor.describe("@ | root()", "test").await;

        assert!(matches!(result, Err(Error::MultipleRevisions { .. })));
    }

    #[tokio::test]
    async fn empty_revset_returns_resolution_error() {
        let temp_dir = assert_fs::TempDir::new().unwrap();
        init_jj_repo(temp_dir.path())
            .await
            .expect("Failed to init jj repo");

        let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();
        let result = executor.describe("none()", "test").await;

        assert!(matches!(result, Err(Error::RevsetResolutionError { .. })));
    }

    #[tokio::test]
    async fn invalid_revset_syntax_returns_resolution_error() {
        let temp_dir = assert_fs::TempDir::new().unwrap();
        init_jj_repo(temp_dir.path())
            .await
            .expect("Failed to init jj repo");

        let executor = JjLib::with_working_dir(temp_dir.path()).await.unwrap();
        let result = executor.describe("(((invalid", "test").await;

        assert!(matches!(result, Err(Error::RevsetResolutionError { .. })));
    }

    #[tokio::test]
    async fn jj_lib_implements_jj_executor_trait() {
        fn assert_implements<T: JjExecutor>() {}
        assert_implements::<JjLib>();
    }

    mod user_config_paths_tests {
        use super::*;
        use std::sync::{LazyLock, Mutex};

        /// Serialize all tests that mutate environment variables to prevent
        /// data races: env vars are process-global in Rust's test runner.
        static ENV_LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));

        /// RAII guard that restores an environment variable on drop.
        struct EnvGuard {
            key: &'static str,
            original: Option<String>,
        }

        impl EnvGuard {
            fn set(key: &'static str, value: impl AsRef<std::ffi::OsStr>) -> Self {
                let original = std::env::var(key).ok();
                // SAFETY: tests hold ENV_LOCK, so no concurrent env mutation
                unsafe { std::env::set_var(key, value) };
                Self { key, original }
            }

            fn remove(key: &'static str) -> Self {
                let original = std::env::var(key).ok();
                // SAFETY: tests hold ENV_LOCK, so no concurrent env mutation
                unsafe { std::env::remove_var(key) };
                Self { key, original }
            }
        }

        impl Drop for EnvGuard {
            fn drop(&mut self) {
                match &self.original {
                    // SAFETY: tests hold ENV_LOCK, so no concurrent env mutation
                    Some(v) => unsafe { std::env::set_var(self.key, v) },
                    None => unsafe { std::env::remove_var(self.key) },
                }
            }
        }

        #[test]
        fn jj_config_single_path_returned_directly() {
            let _lock = ENV_LOCK.lock().unwrap();
            let temp = assert_fs::TempDir::new().unwrap();
            let config_path = temp.path().join("config.toml");

            let _jj = EnvGuard::set("JJ_CONFIG", &config_path);

            assert_eq!(JjLib::user_config_paths(), vec![config_path]);
        }

        #[test]
        fn jj_config_multiple_paths_all_returned() {
            let _lock = ENV_LOCK.lock().unwrap();
            let temp = assert_fs::TempDir::new().unwrap();
            let path_a = temp.path().join("a.toml");
            let path_b = temp.path().join("b.toml");
            let combined = std::env::join_paths([&path_a, &path_b]).unwrap();

            let _jj = EnvGuard::set("JJ_CONFIG", &combined);

            assert_eq!(JjLib::user_config_paths(), vec![path_a, path_b]);
        }

        #[test]
        fn jj_config_empty_segments_are_filtered_out() {
            let _lock = ENV_LOCK.lock().unwrap();
            let temp = assert_fs::TempDir::new().unwrap();
            let config_path = temp.path().join("config.toml");
            // Wrap the path with empty segments (Unix colon separators)
            let value = format!(":{}:", config_path.display());

            let _jj = EnvGuard::set("JJ_CONFIG", &value);

            assert_eq!(JjLib::user_config_paths(), vec![config_path]);
        }

        #[test]
        fn platform_config_toml_always_included_when_xdg_set() {
            let _lock = ENV_LOCK.lock().unwrap();
            let temp = assert_fs::TempDir::new().unwrap();

            let _jj = EnvGuard::remove("JJ_CONFIG");
            let _xdg = EnvGuard::set("XDG_CONFIG_HOME", temp.path());

            let paths = JjLib::user_config_paths();

            assert!(paths.contains(&temp.path().join("jj").join("config.toml")));
        }

        #[test]
        fn home_config_included_when_it_exists() {
            let _lock = ENV_LOCK.lock().unwrap();
            let temp = assert_fs::TempDir::new().unwrap();
            let home_config = temp.path().join(".jjconfig.toml");
            std::fs::write(&home_config, "").unwrap();

            let _jj = EnvGuard::remove("JJ_CONFIG");
            let _home = EnvGuard::set("HOME", temp.path());
            let _xdg = EnvGuard::set("XDG_CONFIG_HOME", temp.path().join("xdg"));

            let paths = JjLib::user_config_paths();

            assert!(paths.contains(&home_config));
        }

        #[test]
        fn home_config_excluded_when_missing_and_platform_config_is_available() {
            let _lock = ENV_LOCK.lock().unwrap();
            let temp = assert_fs::TempDir::new().unwrap();
            // ~/.jjconfig.toml intentionally not created

            let _jj = EnvGuard::remove("JJ_CONFIG");
            let _home = EnvGuard::set("HOME", temp.path());
            let _xdg = EnvGuard::set("XDG_CONFIG_HOME", temp.path().join("xdg"));

            let paths = JjLib::user_config_paths();

            assert!(!paths.contains(&temp.path().join(".jjconfig.toml")));
        }

        #[test]
        fn conf_d_included_when_directory_exists() {
            let _lock = ENV_LOCK.lock().unwrap();
            let temp = assert_fs::TempDir::new().unwrap();
            let conf_d = temp.path().join("jj").join("conf.d");
            std::fs::create_dir_all(&conf_d).unwrap();

            let _jj = EnvGuard::remove("JJ_CONFIG");
            let _xdg = EnvGuard::set("XDG_CONFIG_HOME", temp.path());

            let paths = JjLib::user_config_paths();

            assert!(paths.contains(&conf_d));
        }

        #[test]
        fn conf_d_excluded_when_directory_is_missing() {
            let _lock = ENV_LOCK.lock().unwrap();
            let temp = assert_fs::TempDir::new().unwrap();
            // conf.d intentionally not created

            let _jj = EnvGuard::remove("JJ_CONFIG");
            let _xdg = EnvGuard::set("XDG_CONFIG_HOME", temp.path());

            let paths = JjLib::user_config_paths();

            assert!(!paths.contains(&temp.path().join("jj").join("conf.d")));
        }
    }
}