vissue-core 0.6.0

Plain-text issue tracking over per-project orgmode files: model, store, queries, and org projection
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
//! Root and layout resolution plus the optional on-disk configuration.
//!
//! A tracker lives under `<root>/<prefix>`, one directory per project, each
//! holding an `issues.org`. `root` comes from the caller, `ISSUE_ROOT`,
//! `VISSUE_ROOT`, or the current directory. `prefix` comes from the caller,
//! `VISSUE_PREFIX`, `<root>/vissue.toml`, or the `Software` default.

use anyhow::Context;

use crate::error::Result;
use serde::Deserialize;
use std::fs;
use std::path::{Path, PathBuf};

/// Directory under the root that holds one subdirectory per project.
pub const DEFAULT_PREFIX: &str = "Software";

/// Where the tracker lives: a root directory and the project prefix inside it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Layout {
    root: PathBuf,
    prefix: String,
}

impl Layout {
    /// Build a layout from an explicit root and prefix.
    ///
    /// An empty prefix falls back to [`DEFAULT_PREFIX`].
    pub fn new(root: impl Into<PathBuf>, prefix: impl Into<String>) -> Self {
        let prefix = prefix.into();
        Self {
            root: root.into(),
            prefix: if prefix.is_empty() {
                DEFAULT_PREFIX.to_string()
            } else {
                prefix
            },
        }
    }

    /// Resolve from explicit arguments, falling back to the environment, the
    /// on-disk `vissue.toml`, and finally the compiled defaults.
    ///
    /// # Errors
    ///
    /// Returns an error if the current directory cannot be resolved, or if
    /// `<root>/vissue.toml` exists but cannot be read or parsed.
    pub fn resolve(root: Option<&Path>, prefix: Option<&str>) -> Result<Self> {
        let root = match root {
            Some(p) => p.to_path_buf(),
            None => {
                match std::env::var_os("ISSUE_ROOT").or_else(|| std::env::var_os("VISSUE_ROOT")) {
                    Some(v) => PathBuf::from(v),
                    None => std::env::current_dir().context("resolve current directory as root")?,
                }
            }
        };
        let prefix = match prefix {
            Some(p) if !p.is_empty() => p.to_string(),
            _ => match std::env::var("VISSUE_PREFIX") {
                Ok(v) if !v.is_empty() => v,
                _ => RootConfig::load(&root)?
                    .prefix
                    .unwrap_or_else(|| DEFAULT_PREFIX.to_string()),
            },
        };
        Ok(Self::new(root, prefix))
    }

    /// Tracker root: the directory that holds `vissue.toml` and `prefix`.
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Directory name under [`Self::root`] that holds one subdirectory per project.
    pub fn prefix(&self) -> &str {
        &self.prefix
    }

    /// `<root>/<prefix>`: the directory scanned for projects.
    pub fn projects_dir(&self) -> PathBuf {
        self.root.join(&self.prefix)
    }

    /// `<root>/<prefix>/<project>/issues.org`.
    pub fn project_issues_path(&self, project: &str) -> PathBuf {
        self.projects_dir().join(project).join("issues.org")
    }
}

/// `<root>/vissue.toml`, the product-level configuration file.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
struct RootConfig {
    prefix: Option<String>,
    agent: Option<String>,
    issues: IssuesOverride,
}

impl RootConfig {
    fn load(root: &Path) -> Result<Self> {
        let path = root.join("vissue.toml");
        if !path.exists() {
            return Ok(Self::default());
        }
        let raw = fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
        toml::from_str(&raw)
            .with_context(|| format!("parse {}", path.display()))
            .map_err(crate::error::Error::from)
    }
}

/// Knobs that shape newly created issues.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct IssuesSection {
    /// Priority cookie applied when `create` is called without one.
    pub default_priority: char,
    /// Length in base36 characters of the random suffix in a generated id.
    pub id_length: usize,
    /// How long a claim may sit on a STARTED issue before hygiene calls it
    /// stale.
    pub stale_claim_days: i64,
}

impl Default for IssuesSection {
    fn default() -> Self {
        Self {
            default_priority: 'C',
            id_length: 4,
            stale_claim_days: 7,
        }
    }
}

/// The subset of [`IssuesSection`] a configuration file names. A key left out
/// of a file stays whatever the layer below it set, so a file that tunes one
/// knob does not silently reset the others.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
struct IssuesOverride {
    default_priority: Option<char>,
    id_length: Option<usize>,
    stale_claim_days: Option<i64>,
}

impl IssuesOverride {
    fn apply_to(&self, base: &mut IssuesSection) {
        if let Some(value) = self.default_priority {
            base.default_priority = value;
        }
        if let Some(value) = self.id_length {
            base.id_length = value;
        }
        if let Some(value) = self.stale_claim_days {
            base.stale_claim_days = value;
        }
    }
}

/// Effective configuration for one layout.
#[derive(Debug, Clone, Default)]
pub struct VissueConfig {
    /// Knobs that shape newly created issues and hygiene thresholds.
    pub issues: IssuesSection,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
struct PrefixConfigFile {
    issues: IssuesOverride,
}

impl VissueConfig {
    /// `<root>/<prefix>/issues.config.toml` overrides `<root>/vissue.toml`,
    /// which overrides the compiled defaults. Neither file is required, and
    /// each layer overrides key by key rather than wholesale.
    ///
    /// # Errors
    ///
    /// Returns an error if a configuration file exists but cannot be read or
    /// parsed.
    pub fn load(layout: &Layout) -> Result<Self> {
        let mut issues = IssuesSection::default();
        RootConfig::load(layout.root())?
            .issues
            .apply_to(&mut issues);
        let path = layout.projects_dir().join("issues.config.toml");
        if path.exists() {
            let raw =
                fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
            let parsed: PrefixConfigFile =
                toml::from_str(&raw).with_context(|| format!("parse {}", path.display()))?;
            parsed.issues.apply_to(&mut issues);
        }
        Ok(Self { issues })
    }
}

/// Who is claiming work here.
///
/// `VISSUE_AGENT` wins, then `agent` in `<root>/vissue.toml`, then
/// `user@host`. The value is opaque: an agent should set `VISSUE_AGENT` to
/// something stable enough to identify it across sessions, such as a model
/// and session tag, and any string it picks is stored verbatim.
pub fn identity(layout: &Layout) -> String {
    if let Ok(value) = crate::process_env::var("VISSUE_AGENT") {
        let value = value.trim();
        if !value.is_empty() {
            return value.to_string();
        }
    }
    if let Ok(cfg) = RootConfig::load(layout.root())
        && let Some(agent) = cfg.agent
    {
        let agent = agent.trim().to_string();
        if !agent.is_empty() {
            return agent;
        }
    }
    format!("{}@{}", current_user(), current_host())
}

fn current_user() -> String {
    for var in ["USER", "LOGNAME", "USERNAME"] {
        if let Ok(value) = std::env::var(var)
            && !value.trim().is_empty()
        {
            return value.trim().to_string();
        }
    }
    "unknown".to_string()
}

fn current_host() -> String {
    if let Ok(value) = std::env::var("HOSTNAME")
        && !value.trim().is_empty()
    {
        return value.trim().to_string();
    }
    // HOSTNAME is not exported by every shell, so fall back to the file the
    // system keeps it in.
    for path in ["/etc/hostname", "/proc/sys/kernel/hostname"] {
        if let Ok(text) = fs::read_to_string(path) {
            let trimmed = text.trim();
            if !trimmed.is_empty() {
                return trimmed.to_string();
            }
        }
    }
    "unknown".to_string()
}

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

    #[test]
    fn layout_defaults_to_software_prefix() {
        let layout = Layout::new("/somewhere", "");
        assert_eq!(layout.prefix(), DEFAULT_PREFIX);
        assert_eq!(
            layout.project_issues_path("demo"),
            Path::new("/somewhere/Software/demo/issues.org")
        );
    }

    #[test]
    fn explicit_prefix_wins() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("vissue.toml"), "prefix = \"projects\"\n").unwrap();
        let layout = Layout::resolve(Some(dir.path()), Some("tracker")).unwrap();
        assert_eq!(layout.prefix(), "tracker");
    }

    #[test]
    fn root_config_supplies_prefix() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("vissue.toml"), "prefix = \"projects\"\n").unwrap();
        let layout = Layout::resolve(Some(dir.path()), None).unwrap();
        assert_eq!(layout.prefix(), "projects");
        assert_eq!(
            layout.projects_dir(),
            dir.path().join("projects"),
            "projects dir follows the configured prefix"
        );
    }

    /// `VISSUE_AGENT` is process-global, so the identity tests take turns.
    static AGENT_ENV: std::sync::Mutex<()> = std::sync::Mutex::new(());

    #[test]
    fn the_environment_names_the_claiming_identity_first() {
        let _guard = AGENT_ENV.lock().unwrap_or_else(|p| p.into_inner());
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("vissue.toml"), "agent = \"from-file\"\n").unwrap();
        let layout = Layout::new(dir.path(), DEFAULT_PREFIX);

        crate::process_env::override_var("VISSUE_AGENT", Some("from-env"));
        let from_env = identity(&layout);
        crate::process_env::override_var("VISSUE_AGENT", Some("   "));
        let blank_falls_through = identity(&layout);
        crate::process_env::override_var("VISSUE_AGENT", None);
        let from_file = identity(&layout);
        crate::process_env::clear_override("VISSUE_AGENT");

        assert_eq!(from_env, "from-env");
        assert_eq!(
            blank_falls_through, "from-file",
            "a blank value is not an identity"
        );
        assert_eq!(from_file, "from-file");
    }

    #[test]
    fn without_configuration_the_identity_is_user_at_host() {
        let _guard = AGENT_ENV.lock().unwrap_or_else(|p| p.into_inner());
        let dir = tempfile::tempdir().unwrap();
        let layout = Layout::new(dir.path(), DEFAULT_PREFIX);
        crate::process_env::override_var("VISSUE_AGENT", None);
        let resolved = identity(&layout);
        crate::process_env::clear_override("VISSUE_AGENT");
        assert!(resolved.contains('@'), "{resolved}");
        assert!(!resolved.starts_with('@'), "{resolved}");
        assert!(!resolved.ends_with('@'), "{resolved}");
    }

    #[test]
    fn the_stale_claim_threshold_is_configurable() {
        let dir = tempfile::tempdir().unwrap();
        let layout = Layout::new(dir.path(), DEFAULT_PREFIX);
        assert_eq!(
            VissueConfig::load(&layout).unwrap().issues.stale_claim_days,
            7
        );

        fs::write(
            dir.path().join("vissue.toml"),
            "[issues]\nstale_claim_days = 3\n",
        )
        .unwrap();
        assert_eq!(
            VissueConfig::load(&layout).unwrap().issues.stale_claim_days,
            3
        );
    }

    #[test]
    fn config_defaults_when_no_files_present() {
        let dir = tempfile::tempdir().unwrap();
        let layout = Layout::new(dir.path(), DEFAULT_PREFIX);
        let cfg = VissueConfig::load(&layout).unwrap();
        assert_eq!(cfg.issues.default_priority, 'C');
        assert_eq!(cfg.issues.id_length, 4);
    }

    #[test]
    fn prefix_scoped_config_overrides_root_config() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join("vissue.toml"),
            "[issues]\ndefault_priority = \"B\"\nid_length = 5\n",
        )
        .unwrap();
        let layout = Layout::new(dir.path(), DEFAULT_PREFIX);
        let cfg = VissueConfig::load(&layout).unwrap();
        assert_eq!(cfg.issues.default_priority, 'B');
        assert_eq!(cfg.issues.id_length, 5);

        fs::create_dir_all(layout.projects_dir()).unwrap();
        fs::write(
            layout.projects_dir().join("issues.config.toml"),
            "[issues]\ndefault_priority = \"A\"\nid_length = 6\n",
        )
        .unwrap();
        let cfg = VissueConfig::load(&layout).unwrap();
        assert_eq!(cfg.issues.default_priority, 'A');
        assert_eq!(cfg.issues.id_length, 6);
    }

    #[test]
    fn a_partial_override_keeps_the_keys_it_does_not_name() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join("vissue.toml"),
            "[issues]\ndefault_priority = \"B\"\nid_length = 5\nstale_claim_days = 3\n",
        )
        .unwrap();
        let layout = Layout::new(dir.path(), DEFAULT_PREFIX);
        fs::create_dir_all(layout.projects_dir()).unwrap();
        fs::write(
            layout.projects_dir().join("issues.config.toml"),
            "[issues]\nid_length = 6\n",
        )
        .unwrap();

        let cfg = VissueConfig::load(&layout).unwrap();
        assert_eq!(cfg.issues.id_length, 6, "the named key is overridden");
        assert_eq!(
            cfg.issues.default_priority, 'B',
            "an unnamed key keeps the root value"
        );
        assert_eq!(cfg.issues.stale_claim_days, 3);
    }
}