sirno 0.0.4

Sirno gives project design a semantic intermediate representation.
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
//! Project-local lock state for frost, upstream lakes, and tide.
//!
//! `Sirno.toml` configures paths and policy.
//! `Sirno.lock.toml` records generated project state represented by the lake.

use std::ffi::{OsStr, OsString};
use std::fs::{self, OpenOptions};
use std::io::{ErrorKind, Write};
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use eter::{Eterator, GcGeneration, SnapshotRef};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tracing::trace;

use crate::config::UpstreamSettings;
use crate::identifier::EntryAtom;
use crate::tide::TideResolution;

/// Canonical Sirno project lock filename.
pub const LOCK_FILE_NAME: &str = "Sirno.lock.toml";

const LOCK_FILE_HEADER: &str = "\
# This file is generated and managed by Sirno.
# Do not edit it by hand.

";

/// Project-local generated state.
///
/// Invariant: when `frost` is present,
/// `frost.generation` and `frost.version` name the `eter` snapshot represented by the lake.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
// sirno:witness:sirno-lock:begin
pub struct SirnoLock {
    /// Current lake state relative to frost.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub frost: Option<FrostLock>,
    /// Resolved upstream lake commits.
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub upstreams: UpstreamLockMap,
    /// Explicit dependency review resolutions for the current lake edit session.
    #[serde(default, skip_serializing_if = "TideLock::is_empty")]
    pub tide: TideLock,
}
// sirno:witness:sirno-lock:end

/// Ordered upstream lock records keyed by upstream domain.
pub type UpstreamLockMap = IndexMap<EntryAtom, UpstreamLock>;

impl SirnoLock {
    /// Construct a lock for the current editable lake.
    // sirno:witness:sirno-lock:begin
    pub fn current(snapshot: SnapshotRef) -> Self {
        Self {
            frost: Some(FrostLock::current(snapshot)),
            upstreams: UpstreamLockMap::new(),
            tide: TideLock::default(),
        }
    }
    // sirno:witness:sirno-lock:end

    /// Construct a lock for a checked-out frost snapshot.
    // sirno:witness:sirno-lock:begin
    pub fn checked_out(snapshot: SnapshotRef, mutable: bool) -> Self {
        Self {
            frost: Some(FrostLock::checked_out(snapshot, mutable)),
            upstreams: UpstreamLockMap::new(),
            tide: TideLock::default(),
        }
    }
    // sirno:witness:sirno-lock:end

    /// Resolve the lock path next to the config file.
    pub fn path_for_config(config_path: impl AsRef<Path>) -> PathBuf {
        config_path.as_ref().parent().unwrap_or_else(|| Path::new(".")).join(LOCK_FILE_NAME)
    }

    /// Load a lock from a specific file path.
    // sirno:witness:sirno-lock:begin
    pub fn from_file(path: impl AsRef<Path>) -> Result<Self, LockError> {
        let path = path.as_ref();
        trace!("sirno lock load begin: path={}", path.display());
        let source = fs::read_to_string(path)
            .map_err(|source| LockError::Read { path: path.to_path_buf(), source })?;
        let lock: Self = toml::from_str(&source)
            .map_err(|source| LockError::Parse { path: path.to_path_buf(), source })?;
        lock.validate()?;
        trace!("sirno lock load end");
        Ok(lock)
    }
    // sirno:witness:sirno-lock:end

    /// Load a lock from a file path when it exists.
    pub fn from_file_if_exists(path: impl AsRef<Path>) -> Result<Option<Self>, LockError> {
        match Self::from_file(path) {
            | Ok(lock) => Ok(Some(lock)),
            | Err(LockError::Read { source, .. }) if source.kind() == ErrorKind::NotFound => {
                Ok(None)
            }
            | Err(source) => Err(source),
        }
    }

    /// Write this lock to an existing or new file.
    ///
    /// The lock is first written to a sibling temporary file.
    /// A rename then publishes the complete TOML file as one filesystem replacement.
    // sirno:witness:sirno-lock:begin
    pub fn write(&self, path: impl AsRef<Path>) -> Result<(), LockError> {
        let path = path.as_ref();
        trace!("sirno lock write begin: path={}", path.display());
        let source = self.to_toml()?;
        let temporary_path = Self::temporary_path(path);
        let mut file =
            OpenOptions::new().write(true).create_new(true).open(&temporary_path).map_err(
                |source| LockError::CreateTemporary { path: temporary_path.clone(), source },
            )?;
        if let Err(source) = file.write_all(source.as_bytes()) {
            drop(file);
            let _ = fs::remove_file(&temporary_path);
            return Err(LockError::WriteTemporary { path: temporary_path, source });
        }
        if let Err(source) = file.sync_all() {
            drop(file);
            let _ = fs::remove_file(&temporary_path);
            return Err(LockError::WriteTemporary { path: temporary_path, source });
        }
        drop(file);
        if let Err(source) = fs::rename(&temporary_path, path) {
            let _ = fs::remove_file(&temporary_path);
            return Err(LockError::Replace { path: path.to_path_buf(), temporary_path, source });
        }
        trace!("sirno lock write end");
        Ok(())
    }
    // sirno:witness:sirno-lock:end

    // sirno:witness:sirno-lock:begin
    fn validate(&self) -> Result<(), LockError> {
        if let Some(frost) = &self.frost {
            frost.validate()?;
        }
        if self.frost.is_none() && !self.tide.is_empty() {
            return Err(LockError::TideWithoutFrost);
        }
        for (domain, upstream) in &self.upstreams {
            upstream.validate(domain)?;
        }
        Ok(())
    }

    fn to_toml(&self) -> Result<String, LockError> {
        self.validate()?;
        let mut source = String::from(LOCK_FILE_HEADER);
        source.push_str(&toml::to_string_pretty(self).map_err(LockError::Render)?);
        Ok(source)
    }

    fn temporary_path(path: &Path) -> PathBuf {
        let parent = path.parent().unwrap_or_else(|| Path::new("."));
        let file_name = path.file_name().unwrap_or_else(|| OsStr::new(LOCK_FILE_NAME));
        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|duration| duration.as_nanos())
            .unwrap_or(0);
        let mut temporary_name = OsString::from(".");
        temporary_name.push(file_name);
        temporary_name.push(format!(".{}.{}.tmp", std::process::id(), nonce));
        parent.join(temporary_name)
    }
    // sirno:witness:sirno-lock:end
}

impl Default for SirnoLock {
    fn default() -> Self {
        Self { frost: None, upstreams: UpstreamLockMap::new(), tide: TideLock::default() }
    }
}

/// Resolved upstream state recorded in `Sirno.lock.toml`.
///
/// Invariant: `commit` is a non-empty Git commit id.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UpstreamLock {
    /// Git source copied from `Sirno.toml`.
    pub git: String,
    /// Branch copied from `Sirno.toml`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,
    /// Tag copied from `Sirno.toml`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tag: Option<String>,
    /// Commit-ish copied from `Sirno.toml`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rev: Option<String>,
    /// Directory inside the Git tree containing `Sirno.toml`.
    pub project: PathBuf,
    /// Lake path read from the upstream project's `Sirno.toml`.
    pub lake: PathBuf,
    /// Exact Git commit crystallized into the lake.
    pub commit: String,
}

impl UpstreamLock {
    /// Construct a lock record from config and a resolved commit.
    pub fn new(settings: &UpstreamSettings, lake: PathBuf, commit: impl Into<String>) -> Self {
        Self {
            git: settings.git.clone(),
            branch: settings.branch.clone(),
            tag: settings.tag.clone(),
            rev: settings.rev.clone(),
            project: settings.project.clone(),
            lake,
            commit: commit.into(),
        }
    }

    /// Return whether this lock still corresponds to a config declaration.
    pub fn matches_settings(&self, settings: &UpstreamSettings) -> bool {
        self.git == settings.git
            && self.branch == settings.branch
            && self.tag == settings.tag
            && self.rev == settings.rev
            && self.project == settings.project
    }

    fn validate(&self, domain: &EntryAtom) -> Result<(), LockError> {
        if self.git.trim().is_empty() {
            return Err(LockError::UpstreamGitSource(domain.clone()));
        }
        if self.commit.trim().is_empty() {
            return Err(LockError::UpstreamCommit(domain.clone()));
        }
        let ref_count = [self.branch.as_ref(), self.tag.as_ref(), self.rev.as_ref()]
            .into_iter()
            .flatten()
            .count();
        if ref_count != 1 {
            return Err(LockError::UpstreamRefSelector(domain.clone()));
        }
        Ok(())
    }
}

/// Tide state recorded in `Sirno.lock.toml`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct TideLock {
    /// Explicitly resolved tide workitems.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub resolved: Vec<TideResolution>,
}

impl TideLock {
    /// Returns true when no tide state is stored.
    pub fn is_empty(&self) -> bool {
        self.resolved.is_empty()
    }

    /// Replace stored resolutions with a deterministic list.
    pub fn set_resolved(&mut self, mut resolved: Vec<TideResolution>) {
        resolved.sort();
        resolved.dedup();
        self.resolved = resolved;
    }

    /// Clear all tide state.
    pub fn clear(&mut self) {
        self.resolved.clear();
    }
}

/// Frost state recorded in `Sirno.lock.toml`.
///
/// Invariant: `mutable` is true only for checked-out snapshots created with `--unsafe-mutable`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
// sirno:witness:versioning:begin
pub struct FrostLock {
    /// lake status relative to the configured frost path.
    pub status: FrostLockStatus,
    /// GC generation for the represented snapshot.
    pub generation: u64,
    /// Raw `Eterator` coordinate represented by the lake.
    pub version: u64,
    /// Whether a checked-out frozen snapshot was intentionally left writable.
    #[serde(default, skip_serializing_if = "is_false")]
    pub mutable: bool,
}
// sirno:witness:versioning:end

impl FrostLock {
    /// Construct state for the current editable lake.
    // sirno:witness:versioning:begin
    pub fn current(snapshot: SnapshotRef) -> Self {
        Self {
            status: FrostLockStatus::Current,
            generation: snapshot.generation.number(),
            version: snapshot.version(),
            mutable: false,
        }
    }
    // sirno:witness:versioning:end

    /// Construct state for a checked-out frost snapshot.
    // sirno:witness:versioning:begin
    pub fn checked_out(snapshot: SnapshotRef, mutable: bool) -> Self {
        Self {
            status: FrostLockStatus::CheckedOut,
            generation: snapshot.generation.number(),
            version: snapshot.version(),
            mutable,
        }
    }
    // sirno:witness:versioning:end

    /// Return the stored snapshot reference.
    // sirno:witness:versioning:begin
    pub fn snapshot_ref(&self) -> SnapshotRef {
        SnapshotRef::new(GcGeneration(self.generation), Eterator(self.version))
    }
    // sirno:witness:versioning:end

    /// Returns true when the lake is a frost checkout.
    // sirno:witness:versioning:begin
    pub fn is_checked_out(&self) -> bool {
        self.status == FrostLockStatus::CheckedOut
    }

    /// Returns true when the lake is a writable historical checkout.
    pub fn is_unsafe_mutable_checkout(&self) -> bool {
        self.is_checked_out() && self.mutable
    }
    // sirno:witness:versioning:end

    // sirno:witness:versioning:begin
    fn validate(&self) -> Result<(), LockError> {
        if self.status == FrostLockStatus::Current && self.mutable {
            return Err(LockError::CurrentMutable);
        }
        Ok(())
    }
    // sirno:witness:versioning:end
}

/// lake status relative to frost.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
// sirno:witness:versioning:begin
pub enum FrostLockStatus {
    /// The lake is the current editable version.
    Current,
    /// The lake is a materialized frozen snapshot.
    CheckedOut,
}
// sirno:witness:versioning:end

fn is_false(value: &bool) -> bool {
    !*value
}

/// Error raised by Sirno lock operations.
#[derive(Debug, Error)]
pub enum LockError {
    /// The lock file could not be read.
    #[error("failed to read lock file {path}")]
    Read {
        /// Path that could not be read.
        path: PathBuf,
        /// Underlying I/O error.
        #[source]
        source: std::io::Error,
    },
    /// The lock file could not be parsed as TOML.
    #[error("failed to parse lock file {path}")]
    Parse {
        /// Path that could not be parsed.
        path: PathBuf,
        /// Underlying TOML parse error.
        #[source]
        source: toml::de::Error,
    },
    /// The lock file could not be rendered.
    #[error("failed to render lock file")]
    Render(#[source] toml::ser::Error),
    /// Current lake state must be editable.
    #[error("current frost state cannot be marked mutable")]
    CurrentMutable,
    /// Tide state requires frost state.
    #[error("tide lock state requires frost state")]
    TideWithoutFrost,
    /// An upstream Git source is empty.
    #[error("locked upstream `{0}` git source must not be empty")]
    UpstreamGitSource(EntryAtom),
    /// An upstream must have exactly one ref selector.
    #[error("locked upstream `{0}` must configure exactly one of branch, tag, or rev")]
    UpstreamRefSelector(EntryAtom),
    /// An upstream commit is empty.
    #[error("locked upstream `{0}` commit must not be empty")]
    UpstreamCommit(EntryAtom),
    /// The temporary lock file could not be created.
    #[error("failed to create temporary lock file {path}")]
    CreateTemporary {
        /// Temporary path that could not be created.
        path: PathBuf,
        /// Underlying I/O error.
        #[source]
        source: std::io::Error,
    },
    /// The temporary lock file could not be written.
    #[error("failed to write temporary lock file {path}")]
    WriteTemporary {
        /// Temporary path that could not be written.
        path: PathBuf,
        /// Underlying I/O error.
        #[source]
        source: std::io::Error,
    },
    /// The temporary lock file could not replace the public lock file.
    #[error("failed to replace lock file {path} with temporary lock file {temporary_path}")]
    Replace {
        /// Lock path that could not be replaced.
        path: PathBuf,
        /// Complete temporary lock path.
        temporary_path: PathBuf,
        /// Underlying I/O error.
        #[source]
        source: std::io::Error,
    },
}

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

    #[test]
    fn renders_current_frost_lock() {
        let lock = SirnoLock::current(SnapshotRef::new(GcGeneration::INITIAL, Eterator(7)));
        let rendered = lock.to_toml().unwrap();

        assert_eq!(
            rendered,
            "\
# This file is generated and managed by Sirno.
# Do not edit it by hand.

[frost]
status = \"current\"
generation = 0
version = 7
"
        );
    }

    #[test]
    fn lock_path_uses_toml_suffix() {
        let path = SirnoLock::path_for_config("/project/Sirno.toml");

        assert_eq!(path, PathBuf::from("/project/Sirno.lock.toml"));
    }

    #[test]
    fn renders_mutable_checkout_lock() {
        let lock = SirnoLock::checked_out(SnapshotRef::new(GcGeneration(2), Eterator(3)), true);
        let rendered = lock.to_toml().unwrap();

        assert_eq!(
            rendered,
            "\
# This file is generated and managed by Sirno.
# Do not edit it by hand.

[frost]
status = \"checked-out\"
generation = 2
version = 3
mutable = true
"
        );
    }

    #[test]
    fn renders_upstream_lock_without_frost() {
        let settings = UpstreamSettings::branch("../core.git", "main");
        let lock = SirnoLock {
            frost: None,
            upstreams: UpstreamLockMap::from([(
                EntryAtom::new("core").unwrap(),
                UpstreamLock::new(&settings, PathBuf::from("docs"), "0123456789abcdef"),
            )]),
            tide: TideLock::default(),
        };
        let rendered = lock.to_toml().unwrap();
        let read: SirnoLock = toml::from_str(&rendered).unwrap();

        assert_eq!(read, lock);
        assert!(rendered.contains("[upstreams.core]"));
        assert!(rendered.contains("git = \"../core.git\""));
        assert!(rendered.contains("branch = \"main\""));
        assert!(rendered.contains("lake = \"docs\""));
        assert!(rendered.contains("commit = \"0123456789abcdef\""));
    }

    #[test]
    fn rejects_mutable_current_lock() {
        let error = toml::from_str::<SirnoLock>(
            r#"
[frost]
status = "current"
generation = 0
version = 3
mutable = true
"#,
        )
        .unwrap()
        .validate()
        .unwrap_err();

        assert!(matches!(error, LockError::CurrentMutable));
    }

    #[test]
    fn lock_write_replaces_existing_file() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join(LOCK_FILE_NAME);
        SirnoLock::current(SnapshotRef::new(GcGeneration::INITIAL, Eterator(1)))
            .write(&path)
            .unwrap();

        SirnoLock::current(SnapshotRef::new(GcGeneration::INITIAL, Eterator(2)))
            .write(&path)
            .unwrap();

        let rendered = fs::read_to_string(&path).unwrap();
        assert!(rendered.contains("version = 2"));
        assert!(!rendered.contains("version = 1"));
        let paths = fs::read_dir(temp.path()).unwrap().count();
        assert_eq!(paths, 1);
    }
}