gobby-wiki 0.8.0

Gobby wiki CLI shell
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
use std::path::{Path, PathBuf};

use gobby_core::config::{ConfigSource, EnvOnlySource};

use crate::models::{validate_project_id, validate_topic_name};
use crate::{ScopeSelection, WikiError};

const HUB_ENV: &str = "GOBBY_WIKI_HUB";
const HUB_CONFIG_KEYS: [&str; 2] = ["wiki.hub_path", "gwiki.hub_path"];

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedScope {
    kind: ScopeKind,
    root: PathBuf,
    registry_path: PathBuf,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScopeKind {
    Topic {
        name: String,
    },
    Project {
        project_id: String,
        project_root: PathBuf,
    },
}

impl ResolvedScope {
    pub fn topic(name: String, root: PathBuf, registry_path: PathBuf) -> Self {
        Self {
            kind: ScopeKind::Topic { name },
            root,
            registry_path,
        }
    }

    pub fn project(project_id: String, project_root: PathBuf, root: PathBuf) -> Self {
        let registry_path = root.join("wikis.json");
        Self {
            kind: ScopeKind::Project {
                project_id,
                project_root,
            },
            root,
            registry_path,
        }
    }

    pub fn kind(&self) -> &ScopeKind {
        &self.kind
    }

    pub fn root(&self) -> &Path {
        &self.root
    }

    pub fn registry_path(&self) -> &Path {
        &self.registry_path
    }

    pub fn identity(&self) -> String {
        match &self.kind {
            ScopeKind::Topic { name } => format!("topic:{name}"),
            ScopeKind::Project { project_id, .. } => format!("project:{project_id}"),
        }
    }

    pub fn topic_name(&self) -> Option<&str> {
        match &self.kind {
            ScopeKind::Topic { name } => Some(name),
            ScopeKind::Project { .. } => None,
        }
    }

    pub fn project_id(&self) -> Option<&str> {
        match &self.kind {
            ScopeKind::Topic { .. } => None,
            ScopeKind::Project { project_id, .. } => Some(project_id),
        }
    }

    pub fn project_root(&self) -> Option<&Path> {
        match &self.kind {
            ScopeKind::Topic { .. } => None,
            ScopeKind::Project { project_root, .. } => Some(project_root),
        }
    }
}

pub fn resolve(selection: &ScopeSelection, cwd: &Path) -> Result<ResolvedScope, WikiError> {
    let mut source = EnvOnlySource;
    resolve_with_source(selection, cwd, &mut source)
}

pub fn resolve_with_source(
    selection: &ScopeSelection,
    cwd: &Path,
    source: &mut impl ConfigSource,
) -> Result<ResolvedScope, WikiError> {
    if let Some(topic) = selection.topic_name() {
        return resolve_topic(topic, source);
    }

    if let Some(project_root) = selection.project_root() {
        let project_root = if project_root.is_relative() {
            cwd.join(project_root)
        } else {
            project_root.to_path_buf()
        };
        return resolve_project_from_root(&project_root);
    }

    if let Some(project_root) = gobby_core::project::find_project_root(cwd) {
        return resolve_project_from_root(&project_root);
    }

    Err(WikiError::InvalidScope {
        detail: "select a wiki scope with --topic <name> or run inside a Gobby project".to_string(),
    })
}

fn resolve_topic(topic: &str, source: &mut impl ConfigSource) -> Result<ResolvedScope, WikiError> {
    let topic = validate_topic_name(topic)?;
    let hub = resolve_hub_path(source)?;
    let root = hub.join("topics").join(&topic);

    Ok(ResolvedScope::topic(topic, root, hub.join("wikis.json")))
}

fn resolve_project_from_root(project_root: &Path) -> Result<ResolvedScope, WikiError> {
    let project_root = project_root
        .canonicalize()
        .map_err(|error| WikiError::InvalidScope {
            detail: format!(
                "failed to resolve project root {}: {error}",
                project_root.display()
            ),
        })?;
    let project_id = gobby_core::project::read_project_id(&project_root).map_err(|error| {
        WikiError::InvalidScope {
            detail: format!(
                "failed to read project identity from {}: {error}",
                project_root.display()
            ),
        }
    })?;
    let project_id = validate_project_id(&project_id)?;
    let root = gobby_core::vault::resolve_vault_dir(&project_root).ok_or_else(|| {
        WikiError::InvalidScope {
            detail: format!(
                "no usable wiki vault directory under {}: `{}` and every `{}` fallback is occupied by a non-vault path",
                project_root.display(),
                gobby_core::vault::DEFAULT_VAULT_DIR,
                gobby_core::vault::FALLBACK_VAULT_DIR,
            ),
        }
    })?;

    Ok(ResolvedScope::project(project_id, project_root, root))
}

fn resolve_hub_path(source: &mut impl ConfigSource) -> Result<PathBuf, WikiError> {
    if let Some(path) = std::env::var_os(HUB_ENV).filter(|value| !value.is_empty()) {
        let path = PathBuf::from(path);
        if let Some(value) = path.to_str()
            && (value == "~" || value.starts_with("~/"))
        {
            return expand_home(value);
        }
        return Ok(path);
    }

    for key in HUB_CONFIG_KEYS {
        let Some(value) = source.config_value(key) else {
            continue;
        };
        let value = source
            .resolve_value(&value)
            .map_err(|error| WikiError::Config {
                detail: format!("failed to resolve {key}: {error}"),
            })?;
        if !value.trim().is_empty() {
            return expand_home(value.trim());
        }
    }

    default_hub_path()
}

fn default_hub_path() -> Result<PathBuf, WikiError> {
    let home = dirs::home_dir().ok_or_else(|| WikiError::Config {
        detail: "HOME is not set; configure GOBBY_WIKI_HUB or wiki.hub_path".to_string(),
    })?;

    Ok(home.join("wiki"))
}

fn expand_home(path: &str) -> Result<PathBuf, WikiError> {
    if path == "~" {
        return dirs::home_dir().ok_or_else(|| WikiError::Config {
            detail: "HOME is not set; cannot expand `~` in wiki hub path".to_string(),
        });
    }

    if let Some(rest) = path.strip_prefix("~/") {
        return dirs::home_dir()
            .map(|home| home.join(rest))
            .ok_or_else(|| WikiError::Config {
                detail: format!("HOME is not set; cannot expand `{path}` in wiki hub path"),
            });
    }

    Ok(PathBuf::from(path))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::support::test_env::EnvGuard;
    use gobby_core::config::ConfigSource;
    use std::collections::HashMap;
    use std::fs;

    struct TestConfig {
        values: HashMap<String, String>,
    }

    impl TestConfig {
        fn with(key: &str, value: impl Into<String>) -> Self {
            Self {
                values: HashMap::from([(key.to_string(), value.into())]),
            }
        }
    }

    impl ConfigSource for TestConfig {
        fn config_value(&mut self, key: &str) -> Option<String> {
            self.values.get(key).cloned()
        }

        fn resolve_value(&mut self, value: &str) -> anyhow::Result<String> {
            Ok(value.to_string())
        }
    }

    #[test]
    #[serial_test::serial]
    fn resolves_global_topic() {
        let _env = EnvGuard::unset(HUB_ENV);
        let tmp = tempfile::tempdir().expect("tempdir");
        let hub = tmp.path().join("knowledge");
        let mut config = TestConfig::with("wiki.hub_path", hub.display().to_string());

        let scope = resolve_with_source(
            &crate::ScopeSelection::topic("rust-async"),
            tmp.path(),
            &mut config,
        )
        .expect("topic scope resolves");

        assert_eq!(scope.identity(), "topic:rust-async");
        assert_eq!(scope.root(), hub.join("topics").join("rust-async"));
        assert_eq!(scope.registry_path(), hub.join("wikis.json"));
    }

    #[test]
    fn rejects_invalid_topic_names() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let hub = tmp.path().join("knowledge");
        for topic in [".", "..", "bad/topic", r"bad\topic", "bad:topic"] {
            let mut config = TestConfig::with("wiki.hub_path", hub.display().to_string());
            let err = resolve_with_source(
                &crate::ScopeSelection::topic(topic),
                tmp.path(),
                &mut config,
            )
            .expect_err("invalid topic fails");

            assert!(matches!(err, WikiError::InvalidScope { .. }));
        }
    }

    #[test]
    fn resolves_project_scope_read_only() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let project = tmp.path().join("project");
        let nested = project.join("src").join("bin");
        fs::create_dir_all(project.join(".gobby")).expect("create .gobby");
        fs::create_dir_all(&nested).expect("create nested dir");
        let gcode_json = project.join(".gobby").join("gcode.json");
        let original_gcode_json = r#"{
  "id": "project-123",
  "name": "demo"
}
"#;
        fs::write(&gcode_json, original_gcode_json).expect("write gcode json");

        let mut config = TestConfig::with(
            "wiki.hub_path",
            tmp.path().join("hub").display().to_string(),
        );
        let scope = resolve_with_source(
            &crate::ScopeSelection::project(&project),
            &nested,
            &mut config,
        )
        .expect("project scope resolves");
        let canonical_project = project.canonicalize().expect("canonicalize project root");

        assert_eq!(scope.identity(), "project:project-123");
        assert_eq!(scope.root(), canonical_project.join("wiki"));
        assert_eq!(
            fs::read_to_string(gcode_json).expect("read gcode json"),
            original_gcode_json
        );
        assert!(
            !project.join("wiki").exists(),
            "resolution must not initialize the vault"
        );
    }

    #[test]
    fn project_scope_falls_back_when_wiki_is_occupied_by_non_vault() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let project = tmp.path().join("project");
        fs::create_dir_all(project.join(".gobby")).expect("create .gobby");
        fs::write(
            project.join(".gobby").join("gcode.json"),
            r#"{
  "id": "project-123",
  "name": "demo"
}
"#,
        )
        .expect("write gcode json");
        fs::create_dir_all(project.join("wiki")).expect("create non-vault wiki collision");

        let mut config = TestConfig::with(
            "wiki.hub_path",
            tmp.path().join("hub").display().to_string(),
        );
        let scope = resolve_with_source(
            &crate::ScopeSelection::project(&project),
            &project,
            &mut config,
        )
        .expect("project scope resolves");
        let canonical_project = project.canonicalize().expect("canonicalize project root");

        assert_eq!(scope.root(), canonical_project.join("gobby-wiki"));
    }

    #[test]
    fn project_scope_prefers_existing_wiki_vault() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let project = tmp.path().join("project");
        fs::create_dir_all(project.join(".gobby")).expect("create .gobby");
        fs::write(
            project.join(".gobby").join("gcode.json"),
            r#"{
  "id": "project-123",
  "name": "demo"
}
"#,
        )
        .expect("write gcode json");
        let state_dir = project.join("wiki").join(gobby_core::vault::STATE_ROOT);
        fs::create_dir_all(&state_dir).expect("create vault state dir");
        fs::write(state_dir.join(gobby_core::vault::SCOPE_FILE), "{}\n").expect("mark vault");

        let mut config = TestConfig::with(
            "wiki.hub_path",
            tmp.path().join("hub").display().to_string(),
        );
        let scope = resolve_with_source(
            &crate::ScopeSelection::project(&project),
            &project,
            &mut config,
        )
        .expect("project scope resolves");
        let canonical_project = project.canonicalize().expect("canonicalize project root");

        assert_eq!(scope.root(), canonical_project.join("wiki"));
    }

    #[test]
    fn project_dot_resolves_to_absolute_project_wiki_root() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let project = tmp.path().join("project");
        fs::create_dir_all(project.join(".gobby")).expect("create .gobby");
        fs::write(
            project.join(".gobby").join("gcode.json"),
            r#"{
  "id": "project-123",
  "name": "demo"
}
"#,
        )
        .expect("write gcode json");

        let mut config = TestConfig::with(
            "wiki.hub_path",
            tmp.path().join("hub").display().to_string(),
        );
        let scope =
            resolve_with_source(&crate::ScopeSelection::project("."), &project, &mut config)
                .expect("project scope resolves");
        let project = project.canonicalize().expect("canonicalize project root");

        assert_eq!(scope.project_root(), Some(project.as_path()));
        assert_eq!(scope.root(), project.join("wiki"));
        assert!(scope.root().is_absolute());
    }
}