speccoder-runtime 0.9.7

Application services of speccoder: the only crate that executes anything.
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
//! A new project from one line of intent: the plan — the stack's
//! own scaffold, the spec format's own init, `speccoder init --yes` and
//! one commit as the person — computed read-only, shown, confirmed, and
//! then run exactly as shown. speccoder writes none of the stack's or the
//! format's files itself (constitution VII); `speccoder.toml` is written
//! only by `init`.
//!
//! The plan is bound to a digest over its commands and the folder as it
//! was seen; [`perform`] recomputes it and refuses a plan that changed.
//! A run that stopped resumes: each step's effect is detected, never
//! repeated. Undo ([`undo()`]) moves a folder speccoder created to the
//! Trash, or reverts speccoder's commit in an existing repository — only
//! while nothing else happened there.

mod plan;
mod run;
mod stacks;
pub(crate) mod steps;
pub mod undo;

use std::path::{Component, Path, PathBuf};

use serde::{Deserialize, Serialize};
use speccoder_core::actions::Via;
use speccoder_core::new_project::{
    GitIdentity, NewChoices, NewProjectReport, PlanRefusal, PlanStepResult, ProjectMode,
    ProjectPlan, Stack, UndoOffer,
};
use speccoder_core::{CommandData, CommandResult, CommandStatus};

pub(crate) use plan::{Kind, Spec, format_kind, plan_with};
pub use run::perform;
pub use undo::{undo, undo_offer};

const COMMAND: &str = "new";

/// The creation record: what Undo, the recent projects and the new
/// project's first view read. In speccoder's state, never the project.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Creation {
    /// The folder, canonical.
    pub path: String,
    /// `new_folder` or `existing_repository`.
    pub mode: ProjectMode,
    /// speccoder's commit, once made.
    pub commit: Option<String>,
    /// The plan it ran.
    pub plan_digest: String,
    /// The project's name.
    pub name: String,
    /// What the person is building, verbatim (never in an event).
    pub idea: String,
    /// The stack.
    pub stack: Stack,
    /// The spec format.
    pub format: String,
    /// The person's git identity.
    pub by: Option<GitIdentity>,
    /// Through what.
    pub via: Via,
    /// Unix seconds.
    pub at: u64,
    /// The New Feature sheet was offered with the idea once.
    #[serde(default)]
    pub first_feature_offered: bool,
    /// When it was undone.
    #[serde(default)]
    pub undone_at: Option<u64>,
    /// The folder before the first step: what speccoder neither made nor
    /// may commit or move.
    #[serde(default)]
    pub before: Before,
    /// The folder as the last run left it: a run that resumes needs it
    /// unchanged.
    #[serde(default)]
    pub left: Option<Snapshot>,
    /// The repository's own files (`.git`, but its objects and index) as
    /// speccoder made or found them: a step that changes them stops the run.
    #[serde(default)]
    pub git: Option<String>,
}

/// The folder before speccoder's first step.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Before {
    /// It did not exist, or held nothing (`.DS_Store` aside): speccoder made it.
    pub made: bool,
    /// Its entries.
    pub entries: Vec<String>,
    /// The paths git ignored then (an existing repository).
    pub ignored: Vec<String>,
}

/// The folder at one moment.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Snapshot {
    /// Its entries.
    pub entries: Vec<String>,
    /// `git status --porcelain` there.
    pub porcelain: Vec<String>,
}

/// The folder's entries, sorted.
pub(crate) fn entries_of(dir: &Path) -> Vec<String> {
    let mut v: Vec<String> = std::fs::read_dir(dir)
        .map(|d| {
            d.flatten()
                .map(|e| e.file_name().to_string_lossy().into_owned())
                .collect()
        })
        .unwrap_or_default();
    v.sort();
    v
}

/// The folder now.
pub(crate) fn snapshot(dir: &Path) -> Snapshot {
    Snapshot {
        entries: entries_of(dir),
        // Only the folder's own repository: never a parent's.
        porcelain: if dir.join(".git").exists() {
            // Untrimmed: a status line starts with a space (` M path`).
            crate::git::Git::at(dir)
                .run(&["status", "--porcelain", "--untracked-files=all"])
                .map(|b| {
                    String::from_utf8_lossy(&b)
                        .lines()
                        .filter(|l| !l.is_empty())
                        .map(str::to_owned)
                        .collect()
                })
                .unwrap_or_default()
        } else {
            Vec::new()
        },
    }
}

/// The paths git ignores in `dir` now.
pub(crate) fn ignored(dir: &Path) -> Vec<String> {
    crate::git::Git::at(dir)
        .line(&[
            "status",
            "--porcelain",
            "--ignored",
            "--untracked-files=all",
        ])
        .map(|l| {
            l.lines()
                .filter_map(|x| x.strip_prefix("!! ").map(str::to_owned))
                .collect()
        })
        .unwrap_or_default()
}

/// SHA-256 over `.git`'s files but its objects, index and logs — its
/// configuration, attributes, refs: what decides what speccoder's own git
/// runs. `None` without a repository.
pub(crate) fn git_digest(dir: &Path) -> Option<String> {
    fn walk(base: &Path, p: &Path, out: &mut Vec<(String, Vec<u8>)>) {
        let Ok(rd) = std::fs::read_dir(p) else {
            return;
        };
        for e in rd.flatten() {
            let path = e.path();
            let rel = path
                .strip_prefix(base)
                .map(|r| r.display().to_string())
                .unwrap_or_default();
            if matches!(rel.as_str(), "objects" | "index" | "logs" | "index.lock") {
                continue;
            }
            if path.is_dir() {
                walk(base, &path, out);
            } else {
                out.push((rel, std::fs::read(&path).unwrap_or_default()));
            }
        }
    }
    let git = dir.join(".git");
    if !git.is_dir() {
        return None;
    }
    let mut files = Vec::new();
    walk(&git, &git, &mut files);
    files.sort();
    let mut all = Vec::new();
    for (p, b) in files {
        all.extend_from_slice(p.as_bytes());
        all.push(0);
        all.extend_from_slice(sha(&b).as_bytes());
        all.push(0);
    }
    Some(sha(&all))
}

fn now() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs())
}

/// SHA-256 of `bytes`, hex.
fn sha(bytes: &[u8]) -> String {
    crate::integrity::sha256_hex(bytes)
}

/// The record's directory for the folder `target` (canonical).
fn record_dir(state: &Path, target: &Path) -> PathBuf {
    let id: String = sha(target.to_string_lossy().as_bytes())
        .chars()
        .take(16)
        .collect();
    state.join("new").join(id)
}

/// SHA-256 of the canonical path: what an event names instead of the path.
#[must_use]
pub fn path_digest(target: &Path) -> String {
    format!("sha256:{}", sha(target.to_string_lossy().as_bytes()))
}

/// The creation record of the project at `target`, if speccoder created it.
#[must_use]
pub fn creation(state: &Path, target: &Path) -> Option<Creation> {
    let t = std::fs::canonicalize(target).unwrap_or_else(|_| target.to_path_buf());
    let text = std::fs::read_to_string(record_dir(state, &t).join("creation.json")).ok()?;
    serde_json::from_str(&text).ok()
}

pub(crate) fn write_creation(state: &Path, c: &Creation) -> Result<(), String> {
    let dir = record_dir(state, Path::new(&c.path));
    std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
    let text = serde_json::to_string_pretty(c).map_err(|e| e.to_string())?;
    let f = dir.join("creation.json");
    let tmp = f.with_extension("json.tmp");
    std::fs::write(&tmp, text).map_err(|e| format!("{}: {e}", tmp.display()))?;
    std::fs::rename(&tmp, &f).map_err(|e| format!("{}: {e}", f.display()))
}

/// The idea of a project speccoder created, offered once while it has no
/// unit: the New Feature sheet opens prefilled with it. Marks it
/// offered.
#[must_use]
pub fn first_feature(state: &Path, root: &Path) -> Option<String> {
    let mut c = creation(state, root)?;
    if c.first_feature_offered || c.commit.is_none() || c.undone_at.is_some() || c.idea.is_empty() {
        return None;
    }
    let has_unit = crate::format::open(root, None)
        .map(|o| !o.snapshot.features.is_empty())
        .unwrap_or(true);
    if has_unit {
        return None;
    }
    c.first_feature_offered = true;
    write_creation(state, &c).ok()?;
    Some(c.idea)
}

/// The folder `path` names, absolute, with `.` and `..` resolved and
/// symbolic links of the part that exists resolved: what the plan names.
fn resolve(path: &Path) -> Result<PathBuf, PlanRefusal> {
    let abs = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .map_err(|e| {
                refusal(
                    "USAGE",
                    &format!("no current directory: {e}"),
                    "→ give an absolute path",
                )
            })?
            .join(path)
    };
    let mut lexical = PathBuf::new();
    for c in abs.components() {
        match c {
            Component::ParentDir => {
                lexical.pop();
            }
            Component::CurDir => {}
            other => lexical.push(other),
        }
    }
    if std::fs::symlink_metadata(&lexical).is_ok_and(|m| m.file_type().is_symlink()) {
        return Err(refusal(
            "NEW-TARGET-NOT-EMPTY",
            &format!("{} is a symbolic link", lexical.display()),
            "→ choose the folder it points to, or another one",
        ));
    }
    // The longest part that exists, canonical; the rest appended.
    let mut existing = lexical.clone();
    let mut rest: Vec<std::ffi::OsString> = Vec::new();
    while !existing.exists() {
        match (existing.file_name(), existing.parent()) {
            (Some(n), Some(p)) => {
                rest.push(n.to_os_string());
                existing = p.to_path_buf();
            }
            _ => break,
        }
    }
    let mut out = std::fs::canonicalize(&existing).unwrap_or(existing);
    for n in rest.iter().rev() {
        out.push(n);
    }
    Ok(out)
}

fn refusal(code: &str, message: &str, fix: &str) -> PlanRefusal {
    PlanRefusal {
        code: code.to_owned(),
        message: message.to_owned(),
        fix: fix.to_owned(),
    }
}

/// `~/x` for a path under the home directory.
fn shown(p: &Path) -> String {
    match std::env::var_os("HOME").map(PathBuf::from) {
        Some(h) if p.starts_with(&h) => {
            format!(
                "~/{}",
                p.strip_prefix(&h)
                    .map_or_else(|_| p.display().to_string(), |r| r.display().to_string())
            )
        }
        _ => p.display().to_string(),
    }
}

/// SHA-256 over what the confirmation binds: everything the plan runs and
/// the folder as seen — not the informational options beside it.
#[must_use]
pub fn digest(plan: &ProjectPlan) -> String {
    let bound = serde_json::json!({
        "target": plan.target,
        "name": plan.name,
        "mode": plan.mode,
        "stack": plan.stack,
        "format": plan.format,
        "extensions": plan.extensions,
        "preset": plan.preset,
        "steps": plan.steps,
        "sandbox": plan.sandbox,
        "identity": plan.identity,
        "refusal": plan.refusal,
        "observed": plan.observed,
    });
    format!("sha256:{}", sha(bound.to_string().as_bytes()))
}

/// The plan for `path` with `choices` (read-only; the sheet's and
/// `--dry-run`'s).
#[must_use]
pub fn plan(path: &Path, choices: &NewChoices, state: &Path) -> ProjectPlan {
    plan_with(path, choices, state, false).0
}

fn report(plan: ProjectPlan, results: Vec<PlanStepResult>, dry_run: bool) -> NewProjectReport {
    NewProjectReport {
        plan,
        results,
        init: None,
        commit: None,
        undo: UndoOffer {
            available: false,
            kind: "none".to_owned(),
            reason: None,
        },
        dry_run,
        first_feature: None,
    }
}

fn refused_result(plan: ProjectPlan, results: Vec<PlanStepResult>) -> CommandResult {
    let r = plan
        .refusal
        .clone()
        .unwrap_or_else(|| refusal("USAGE", "refused", ""));
    let status =
        speccoder_core::codes::lookup(&r.code).map_or(CommandStatus::UsageError, |e| e.status);
    CommandResult::new(COMMAND, status, &r.message)
        .with_code(&r.code)
        .with_fix(vec![r.fix.clone()])
        .with_data(CommandData::NewProject(Box::new(report(
            plan, results, false,
        ))))
}

/// `speccoder new --dry-run`: the plan and its digest; nothing changes.
#[must_use]
pub fn dry_run(path: &Path, choices: &NewChoices, state: &Path) -> CommandResult {
    let plan = plan(path, choices, state);
    if plan.refusal.is_some() {
        let r = refused_result(plan, Vec::new());
        return r;
    }
    let message = format!(
        "plan for {} in {}: {} commands (nothing ran)",
        plan.name,
        shown(Path::new(&plan.target)),
        plan.steps.len()
    );
    CommandResult::new(COMMAND, CommandStatus::Ok, &message).with_data(CommandData::NewProject(
        Box::new(report(plan, Vec::new(), true)),
    ))
}