algocline-app 0.16.0

algocline application layer — execution orchestration, package management
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
//! `alc.toml` — project package declaration file.
//!
//! ## File location
//! `alc.toml` lives at the project root.
//!
//! ## Schema example
//! ```toml
//! [packages]
//! coding_orch = "*"
//! flow_design = "0.2.0"
//!
//! [packages.head_agent]
//! path = "packages/head_agent"
//!
//! [packages.my_pkg]
//! git = "https://github.com/user/my-pkg"
//! rev = "abc123"
//! ```

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

// ─── Types ─────────────────────────────────────────────────────────────────

/// Top-level structure of `alc.toml`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub(crate) struct AlcToml {
    #[serde(default)]
    pub packages: BTreeMap<String, PackageDep>,
}

/// A single package dependency declaration.
///
/// Uses `#[serde(untagged)]` — `Version` must come first so that a plain
/// string is matched before the struct variants.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub(crate) enum PackageDep {
    /// `"*"` or `"0.2.0"` — resolve from installed cache.
    Version(String),
    /// `{ path = "..." }` — local directory.
    Path {
        path: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        version: Option<String>,
    },
    /// `{ git = "..." }` — Git source (future).
    Git {
        git: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        rev: Option<String>,
    },
}

// ─── Paths ──────────────────────────────────────────────────────────────────

pub(crate) fn alc_toml_path(project_root: &Path) -> PathBuf {
    project_root.join("alc.toml")
}

// ─── Read ────────────────────────────────────────────────────────────────────

/// Load and parse `alc.toml` using serde.
///
/// Returns `Ok(None)` if the file does not exist.
pub(crate) fn load_alc_toml(project_root: &Path) -> Result<Option<AlcToml>, String> {
    let path = alc_toml_path(project_root);
    if !path.exists() {
        return Ok(None);
    }

    let content = std::fs::read_to_string(&path)
        .map_err(|e| format!("Failed to read alc.toml at {}: {e}", path.display()))?;

    let parsed: AlcToml = toml::from_str(&content)
        .map_err(|e| format!("Failed to parse alc.toml at {}: {e}", path.display()))?;

    Ok(Some(parsed))
}

/// Load `alc.toml` as a raw `toml_edit::DocumentMut` (preserves comments/formatting).
///
/// Returns `Ok(None)` if the file does not exist.
pub(crate) fn load_alc_toml_document(
    project_root: &Path,
) -> Result<Option<toml_edit::DocumentMut>, String> {
    let path = alc_toml_path(project_root);
    if !path.exists() {
        return Ok(None);
    }

    let content = std::fs::read_to_string(&path)
        .map_err(|e| format!("Failed to read alc.toml at {}: {e}", path.display()))?;

    let doc: toml_edit::DocumentMut = content
        .parse()
        .map_err(|e| format!("Failed to parse alc.toml at {}: {e}", path.display()))?;

    Ok(Some(doc))
}

// ─── Write ───────────────────────────────────────────────────────────────────

/// Write a `toml_edit::DocumentMut` back to `alc.toml` (comment-preserving).
pub(crate) fn save_alc_toml(
    project_root: &Path,
    doc: &toml_edit::DocumentMut,
) -> Result<(), String> {
    let path = alc_toml_path(project_root);
    let parent = path.parent().ok_or_else(|| {
        format!(
            "Cannot determine parent directory for alc.toml at {}",
            path.display()
        )
    })?;
    std::fs::create_dir_all(parent)
        .map_err(|e| format!("Failed to create directory for alc.toml: {e}"))?;

    std::fs::write(&path, doc.to_string())
        .map_err(|e| format!("Failed to write alc.toml at {}: {e}", path.display()))?;

    Ok(())
}

// ─── Entry manipulation ──────────────────────────────────────────────────────

/// Add a package entry to `[packages]` in the document.
///
/// Returns `true` if the entry was added, `false` if it already existed (skip).
pub(crate) fn add_package_entry(
    doc: &mut toml_edit::DocumentMut,
    name: &str,
    dep: &PackageDep,
) -> bool {
    use toml_edit::{value, Item, Table};

    // Ensure [packages] table exists.
    if doc.get("packages").is_none() {
        doc.insert("packages", Item::Table(Table::new()));
    }

    let packages = match doc["packages"].as_table_mut() {
        Some(t) => t,
        None => return false,
    };

    // Already exists — skip.
    if packages.contains_key(name) {
        return false;
    }

    match dep {
        PackageDep::Version(v) => {
            packages.insert(name, value(v.as_str()));
        }
        PackageDep::Path { path, version: ver } => {
            let mut tbl = toml_edit::InlineTable::new();
            tbl.insert("path", path.as_str().into());
            if let Some(v) = ver {
                tbl.insert("version", v.as_str().into());
            }
            packages.insert(name, Item::Value(toml_edit::Value::InlineTable(tbl)));
        }
        PackageDep::Git { git, rev } => {
            let mut tbl = toml_edit::InlineTable::new();
            tbl.insert("git", git.as_str().into());
            if let Some(r) = rev {
                tbl.insert("rev", r.as_str().into());
            }
            packages.insert(name, Item::Value(toml_edit::Value::InlineTable(tbl)));
        }
    }

    true
}

/// Remove a package entry from `[packages]` in the document.
///
/// Returns `true` if the entry was removed, `false` if it did not exist.
pub(crate) fn remove_package_entry(doc: &mut toml_edit::DocumentMut, name: &str) -> bool {
    let packages = match doc.get_mut("packages").and_then(|i| i.as_table_mut()) {
        Some(t) => t,
        None => return false,
    };
    packages.remove(name).is_some()
}

// ─── Validation ──────────────────────────────────────────────────────────────

/// Validate a package name: must match `[a-zA-Z][a-zA-Z0-9_-]*`.
pub(crate) fn validate_package_name(name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err("package name must not be empty".to_string());
    }

    let mut chars = name.chars();
    let first = chars.next().unwrap();
    if !first.is_ascii_alphabetic() {
        return Err(format!(
            "package name must start with a letter, got '{first}'"
        ));
    }

    for c in chars {
        if !c.is_ascii_alphanumeric() && c != '_' && c != '-' {
            return Err(format!(
                "package name contains invalid character '{c}': only [a-zA-Z0-9_-] allowed"
            ));
        }
    }

    Ok(())
}

// ─── Tests ──────────────────────────────────────────────────────────────────

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

    // ── parse tests ─────────────────────────────────────────────────

    #[test]
    fn parse_version_dep() {
        let toml = r#"
[packages]
cot = "*"
flow = "0.2.0"
"#;
        let parsed: AlcToml = toml::from_str(toml).unwrap();
        assert_eq!(parsed.packages["cot"], PackageDep::Version("*".to_string()));
        assert_eq!(
            parsed.packages["flow"],
            PackageDep::Version("0.2.0".to_string())
        );
    }

    #[test]
    fn parse_path_dep() {
        let toml = r#"
[packages.head_agent]
path = "packages/head_agent"
"#;
        let parsed: AlcToml = toml::from_str(toml).unwrap();
        assert_eq!(
            parsed.packages["head_agent"],
            PackageDep::Path {
                path: "packages/head_agent".to_string(),
                version: None,
            }
        );
    }

    #[test]
    fn parse_git_dep() {
        let toml = r#"
[packages.my_pkg]
git = "https://github.com/user/my-pkg"
rev = "abc123"
"#;
        let parsed: AlcToml = toml::from_str(toml).unwrap();
        assert_eq!(
            parsed.packages["my_pkg"],
            PackageDep::Git {
                git: "https://github.com/user/my-pkg".to_string(),
                rev: Some("abc123".to_string()),
            }
        );
    }

    #[test]
    fn parse_mixed() {
        let toml = r#"
[packages]
cot = "*"

[packages.head_agent]
path = "packages/head_agent"
version = "0.3.0"

[packages.my_pkg]
git = "https://github.com/user/my-pkg"
"#;
        let parsed: AlcToml = toml::from_str(toml).unwrap();
        assert_eq!(parsed.packages.len(), 3);
        assert_eq!(parsed.packages["cot"], PackageDep::Version("*".to_string()));
        assert_eq!(
            parsed.packages["head_agent"],
            PackageDep::Path {
                path: "packages/head_agent".to_string(),
                version: Some("0.3.0".to_string()),
            }
        );
        assert_eq!(
            parsed.packages["my_pkg"],
            PackageDep::Git {
                git: "https://github.com/user/my-pkg".to_string(),
                rev: None,
            }
        );
    }

    #[test]
    fn parse_invalid_format() {
        let toml = r#"
[packages]
invalid_key = 42
"#;
        let result: Result<AlcToml, _> = toml::from_str(toml);
        assert!(result.is_err());
    }

    // ── load/save roundtrip ──────────────────────────────────────────

    #[test]
    fn load_returns_none_when_missing() {
        let tmp = tempfile::tempdir().unwrap();
        let result = load_alc_toml(tmp.path()).unwrap();
        assert_eq!(result, None);
    }

    #[test]
    fn load_and_parse() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("alc.toml"), "[packages]\ncot = \"*\"\n").unwrap();

        let parsed = load_alc_toml(tmp.path()).unwrap().unwrap();
        assert_eq!(parsed.packages["cot"], PackageDep::Version("*".to_string()));
    }

    #[test]
    fn document_roundtrip() {
        let tmp = tempfile::tempdir().unwrap();
        let content = "# comment\n[packages]\ncot = \"*\"\n";
        std::fs::write(tmp.path().join("alc.toml"), content).unwrap();

        let doc = load_alc_toml_document(tmp.path()).unwrap().unwrap();
        save_alc_toml(tmp.path(), &doc).unwrap();

        let after = std::fs::read_to_string(tmp.path().join("alc.toml")).unwrap();
        // comment must be preserved
        assert!(after.contains("# comment"), "comment was lost: {after}");
        assert!(after.contains("cot"), "cot entry was lost");
    }

    // ── add/remove entry ─────────────────────────────────────────────

    #[test]
    fn add_version_entry() {
        let mut doc: toml_edit::DocumentMut = "[packages]\n".parse().unwrap();
        let added = add_package_entry(&mut doc, "cot", &PackageDep::Version("*".to_string()));
        assert!(added);
        assert!(doc.to_string().contains("cot"));
    }

    #[test]
    fn add_path_entry() {
        let mut doc: toml_edit::DocumentMut = "[packages]\n".parse().unwrap();
        let added = add_package_entry(
            &mut doc,
            "head",
            &PackageDep::Path {
                path: "packages/head".to_string(),
                version: None,
            },
        );
        assert!(added);
        assert!(doc.to_string().contains("head"));
        assert!(doc.to_string().contains("packages/head"));
    }

    #[test]
    fn add_skips_existing() {
        let mut doc: toml_edit::DocumentMut = "[packages]\ncot = \"*\"\n".parse().unwrap();
        let added = add_package_entry(&mut doc, "cot", &PackageDep::Version("0.1.0".to_string()));
        assert!(!added, "should skip existing entry");
        // value unchanged
        assert!(doc.to_string().contains("\"*\""));
    }

    #[test]
    fn add_creates_packages_table() {
        let mut doc: toml_edit::DocumentMut = "".parse().unwrap();
        let added = add_package_entry(&mut doc, "cot", &PackageDep::Version("*".to_string()));
        assert!(added);
        assert!(doc.to_string().contains("[packages]"));
    }

    #[test]
    fn remove_entry() {
        let mut doc: toml_edit::DocumentMut = "[packages]\ncot = \"*\"\n".parse().unwrap();
        let removed = remove_package_entry(&mut doc, "cot");
        assert!(removed);
        assert!(!doc.to_string().contains("cot"));
    }

    #[test]
    fn remove_nonexistent_returns_false() {
        let mut doc: toml_edit::DocumentMut = "[packages]\n".parse().unwrap();
        let removed = remove_package_entry(&mut doc, "nonexistent");
        assert!(!removed);
    }

    // ── validate_package_name ────────────────────────────────────────

    #[test]
    fn valid_names() {
        assert!(validate_package_name("cot").is_ok());
        assert!(validate_package_name("head_agent").is_ok());
        assert!(validate_package_name("my-pkg").is_ok());
        assert!(validate_package_name("A123").is_ok());
    }

    #[test]
    fn invalid_names() {
        assert!(validate_package_name("").is_err());
        assert!(validate_package_name("1start").is_err());
        assert!(validate_package_name("_start").is_err());
        assert!(validate_package_name("has space").is_err());
        assert!(validate_package_name("has.dot").is_err());
    }
}