newgit-core 0.1.0

Core domain model for newgit: branch instances, tracker lanes, and resource lifecycles
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
use camino::{Utf8Path, Utf8PathBuf};
use chrono::Utc;
use serde::Serialize;
use serde::de::DeserializeOwned;

use crate::branch::BranchInstance;
use crate::config::{ProjectConfig, SourceSubstrate};
use crate::error::{NewgitError, Result};
use crate::materializer::{WorkspaceMarker, create_dir_all};
use crate::resource::ResourceDefinition;
use crate::tracker::{TrackerDefinition, validate_disjoint};

const LOCAL_GITIGNORE: &str = "\
# newgit local state — never committed
/local/
/branches/
/snapshots/
/logs/
/state/
/checkpoints/
";

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MetadataStore {
    paths: NewgitPaths,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NewgitPaths {
    pub project_root: Utf8PathBuf,
    pub metadata_root: Utf8PathBuf,
    pub config: Utf8PathBuf,
    pub branches: Utf8PathBuf,
    pub archived_branches: Utf8PathBuf,
    pub trackers: Utf8PathBuf,
    pub resources: Utf8PathBuf,
    pub local: Utf8PathBuf,
    pub snapshots: Utf8PathBuf,
    pub logs: Utf8PathBuf,
    pub state: Utf8PathBuf,
    pub checkpoints: Utf8PathBuf,
}

/// Where a newgit command is standing: which store owns the metadata, and —
/// when inside a workspace — which branch instance the cwd belongs to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Context {
    pub store: MetadataStore,
    pub current_branch: Option<String>,
}

impl MetadataStore {
    pub fn at(project_root: impl Into<Utf8PathBuf>) -> Self {
        Self {
            paths: NewgitPaths::new(project_root.into()),
        }
    }

    pub fn init(
        project_root: impl Into<Utf8PathBuf>,
        project_name: &str,
        source: SourceSubstrate,
    ) -> Result<Self> {
        let store = Self::at(project_root);
        if store.paths.config.exists() {
            return Err(NewgitError::AlreadyExists(store.paths.config.clone()));
        }
        store.create_layout()?;
        let config = ProjectConfig::new(project_name, source);
        store.write_toml(&store.paths.config, "project config", &config)?;
        Ok(store)
    }

    /// Walk upward from `cwd` to find the governing metadata. A workspace is
    /// recognized by its gitignored marker and resolves to the store it was
    /// cloned from; a directory with a committed `.newgit/config.toml` and no
    /// marker is the store itself.
    pub fn discover(cwd: &Utf8Path) -> Result<Context> {
        let mut dir = Some(cwd);
        while let Some(current) = dir {
            let metadata_root = current.join(".newgit");
            if metadata_root.is_dir() {
                let marker_path = metadata_root.join("local/instance.toml");
                if marker_path.is_file() {
                    let marker: WorkspaceMarker = read_toml_at(&marker_path)?;
                    let store = Self::at(marker.store_root);
                    store.ensure_initialized()?;
                    return Ok(Context {
                        store,
                        current_branch: Some(marker.branch),
                    });
                }
                if metadata_root.join("config.toml").is_file() {
                    return Ok(Context {
                        store: Self::at(current),
                        current_branch: None,
                    });
                }
            }
            dir = current.parent();
        }
        Err(NewgitError::MissingMetadata(cwd.to_path_buf()))
    }

    pub fn paths(&self) -> &NewgitPaths {
        &self.paths
    }

    pub fn ensure_initialized(&self) -> Result<()> {
        if self.paths.metadata_root.is_dir() && self.paths.config.is_file() {
            Ok(())
        } else {
            Err(NewgitError::MissingMetadata(
                self.paths.metadata_root.clone(),
            ))
        }
    }

    pub fn load_config(&self) -> Result<ProjectConfig> {
        read_toml_at(&self.paths.config)
    }

    pub fn write_config(&self, config: &ProjectConfig) -> Result<()> {
        self.write_toml(&self.paths.config, "project config", config)
    }

    pub fn branch_record_path(&self, slug: &str) -> Utf8PathBuf {
        self.paths.branches.join(format!("{slug}.toml"))
    }

    /// Write a brand-new binding record; fails on slug collision.
    pub fn create_branch_record(&self, branch: &BranchInstance) -> Result<Utf8PathBuf> {
        create_dir_all(&self.paths.branches)?;
        let path = self.branch_record_path(&branch.slug);
        if path.exists() {
            return Err(NewgitError::BranchInstanceExists {
                name: branch.name.clone(),
                path,
            });
        }
        self.write_toml(&path, &format!("branch `{}`", branch.name), branch)?;
        Ok(path)
    }

    /// Overwrite an existing binding record (e.g. after a tracker capture).
    pub fn save_branch_record(&self, branch: &BranchInstance) -> Result<Utf8PathBuf> {
        create_dir_all(&self.paths.branches)?;
        let path = self.branch_record_path(&branch.slug);
        self.write_toml(&path, &format!("branch `{}`", branch.name), branch)?;
        Ok(path)
    }

    /// Tracker definitions, one per file in `.newgit/trackers/`; the name
    /// comes from the filename. Lanes are validated as disjoint.
    pub fn load_tracker_definitions(&self) -> Result<Vec<TrackerDefinition>> {
        self.ensure_initialized()?;
        let mut definitions = Vec::new();
        for entry in read_dir_sorted(&self.paths.trackers)? {
            if entry.extension() != Some("toml") {
                continue;
            }
            let Some(name) = entry.file_stem() else {
                continue;
            };
            definitions.push(TrackerDefinition::from_file(name, &entry)?);
        }
        validate_disjoint(&definitions)?;
        Ok(definitions)
    }

    pub fn create_tracker_definition(&self, definition: &TrackerDefinition) -> Result<Utf8PathBuf> {
        create_dir_all(&self.paths.trackers)?;
        let path = self
            .paths
            .trackers
            .join(format!("{}.toml", definition.name));
        if path.exists() {
            return Err(NewgitError::AlreadyExists(path));
        }
        self.write_toml(
            &path,
            &format!("tracker `{}`", definition.name),
            &definition.to_file(),
        )?;
        Ok(path)
    }

    pub fn save_tracker_definition(&self, definition: &TrackerDefinition) -> Result<Utf8PathBuf> {
        create_dir_all(&self.paths.trackers)?;
        let path = self
            .paths
            .trackers
            .join(format!("{}.toml", definition.name));
        self.write_toml(
            &path,
            &format!("tracker `{}`", definition.name),
            &definition.to_file(),
        )?;
        Ok(path)
    }

    /// Resource definitions, one per file in `.newgit/resources/`.
    pub fn load_resource_definitions(&self) -> Result<Vec<ResourceDefinition>> {
        self.ensure_initialized()?;
        let mut definitions = Vec::new();
        for entry in read_dir_sorted(&self.paths.resources)? {
            if entry.extension() != Some("toml") {
                continue;
            }
            let Some(name) = entry.file_stem() else {
                continue;
            };
            definitions.push(ResourceDefinition::from_file(name, &entry)?);
        }
        Ok(definitions)
    }

    pub fn write_resource_file(&self, name: &str, contents: &str) -> Result<Utf8PathBuf> {
        create_dir_all(&self.paths.resources)?;
        let path = self.paths.resources.join(format!("{name}.toml"));
        if path.exists() {
            return Err(NewgitError::AlreadyExists(path));
        }
        std::fs::write(&path, contents).map_err(|source| NewgitError::io(&path, source))?;
        Ok(path)
    }

    pub fn instance_state_dir(&self, slug: &str) -> Utf8PathBuf {
        self.paths.state.join(slug)
    }

    /// Per-instance checkpoint records: `.newgit/checkpoints/<slug>/`.
    pub fn checkpoint_dir(&self, slug: &str) -> Utf8PathBuf {
        self.paths.checkpoints.join(slug)
    }

    /// Every slug with a checkpoint directory, including instances whose
    /// binding record has been archived. Checkpoints outlive removal, so
    /// snapshot pruning has to consult all of them, not just live records.
    pub fn checkpointed_slugs(&self) -> Result<Vec<String>> {
        Ok(read_subdirs_sorted(&self.paths.checkpoints)?
            .iter()
            .filter_map(|dir| dir.file_name().map(ToOwned::to_owned))
            .collect())
    }

    /// Per-instance runtime state directories that exist on disk.
    pub fn state_dirs(&self) -> Result<Vec<Utf8PathBuf>> {
        read_subdirs_sorted(&self.paths.state)
    }

    /// Timestamped log path for one action run.
    pub fn action_log_path(&self, slug: &str, label: &str) -> Utf8PathBuf {
        let now = Utc::now();
        self.paths.logs.join(slug).join(format!(
            "{label}-{}-{:09}Z.log",
            now.format("%Y%m%dT%H%M%S"),
            now.timestamp_subsec_nanos()
        ))
    }

    /// Append patterns to the store repo's .gitignore under a labeled block.
    pub fn append_gitignore(&self, label: &str, patterns: &[String]) -> Result<()> {
        if patterns.is_empty() {
            return Ok(());
        }
        let path = self.paths.project_root.join(".gitignore");
        let existing = if path.exists() {
            std::fs::read_to_string(&path).map_err(|source| NewgitError::io(&path, source))?
        } else {
            String::new()
        };
        let mut updated = existing.clone();
        if !updated.is_empty() && !updated.ends_with('\n') {
            updated.push('\n');
        }
        updated.push_str(&format!("\n# newgit tracker: {label}\n"));
        for pattern in patterns {
            updated.push_str(pattern);
            updated.push('\n');
        }
        std::fs::write(&path, updated).map_err(|source| NewgitError::io(&path, source))
    }

    pub fn load_branches(&self) -> Result<Vec<BranchInstance>> {
        self.ensure_initialized()?;
        let mut branches: Vec<BranchInstance> = Vec::new();

        for entry in read_dir_sorted(&self.paths.branches)? {
            if entry.extension() == Some("toml") {
                branches.push(read_toml_at(&entry)?);
            }
        }

        branches.sort_by(|left, right| left.name.cmp(&right.name));
        Ok(branches)
    }

    /// Look an instance up by name or slug.
    pub fn find_branch(&self, name: &str) -> Result<BranchInstance> {
        self.load_branches()?
            .into_iter()
            .find(|branch| branch.name == name || branch.slug == name)
            .ok_or_else(|| NewgitError::UnknownBranchInstance(name.to_owned()))
    }

    /// The binding record outlives the workspace: removal archives it rather
    /// than deleting it.
    pub fn archive_branch_record(&self, branch: &BranchInstance) -> Result<Utf8PathBuf> {
        create_dir_all(&self.paths.archived_branches)?;
        let record = self.branch_record_path(&branch.slug);
        let archived = self.paths.archived_branches.join(format!(
            "{}-{}.toml",
            branch.slug,
            Utc::now().format("%Y%m%dT%H%M%SZ")
        ));
        std::fs::rename(&record, &archived).map_err(|source| NewgitError::io(record, source))?;
        Ok(archived)
    }

    fn create_layout(&self) -> Result<()> {
        for path in [
            &self.paths.metadata_root,
            &self.paths.branches,
            &self.paths.trackers,
            &self.paths.resources,
            &self.paths.local,
            &self.paths.snapshots,
            &self.paths.logs,
            &self.paths.state,
            &self.paths.checkpoints,
        ] {
            create_dir_all(path)?;
        }

        let gitignore = self.paths.metadata_root.join(".gitignore");
        if !gitignore.exists() {
            std::fs::write(&gitignore, LOCAL_GITIGNORE)
                .map_err(|source| NewgitError::io(gitignore, source))?;
        }
        Ok(())
    }

    fn write_toml<T>(&self, path: &Utf8Path, label: &str, value: &T) -> Result<()>
    where
        T: Serialize,
    {
        write_toml_at(path, label, value)
    }
}

impl NewgitPaths {
    pub fn new(project_root: Utf8PathBuf) -> Self {
        let metadata_root = project_root.join(".newgit");
        Self {
            project_root,
            config: metadata_root.join("config.toml"),
            branches: metadata_root.join("branches"),
            archived_branches: metadata_root.join("branches/archived"),
            trackers: metadata_root.join("trackers"),
            resources: metadata_root.join("resources"),
            local: metadata_root.join("local"),
            snapshots: metadata_root.join("snapshots"),
            logs: metadata_root.join("logs"),
            state: metadata_root.join("state"),
            checkpoints: metadata_root.join("checkpoints"),
            metadata_root,
        }
    }
}

pub fn expand_home(path: &Utf8Path) -> Utf8PathBuf {
    let Some(stripped) = path.as_str().strip_prefix("~/") else {
        return path.to_path_buf();
    };

    std::env::var("HOME")
        .map(|home| Utf8PathBuf::from(home).join(stripped))
        .unwrap_or_else(|_| path.to_path_buf())
}

pub(crate) fn read_toml_at<T>(path: &Utf8Path) -> Result<T>
where
    T: DeserializeOwned,
{
    let contents = std::fs::read_to_string(path).map_err(|source| NewgitError::io(path, source))?;
    toml::from_str(&contents).map_err(|source| NewgitError::TomlRead {
        path: path.to_path_buf(),
        source,
    })
}

pub(crate) fn write_toml_at<T>(path: &Utf8Path, label: &str, value: &T) -> Result<()>
where
    T: Serialize,
{
    let contents = toml::to_string_pretty(value).map_err(|source| NewgitError::TomlWrite {
        label: label.to_owned(),
        source,
    })?;
    std::fs::write(path, contents).map_err(|source| NewgitError::io(path, source))
}

/// Immediate subdirectories, sorted. The dir-shaped counterpart to
/// [`read_dir_sorted`], for walking per-instance checkpoint dirs and lane
/// rev dirs.
pub(crate) fn read_subdirs_sorted(path: &Utf8Path) -> Result<Vec<Utf8PathBuf>> {
    if !path.exists() {
        return Ok(Vec::new());
    }

    let mut entries = Vec::new();
    for entry in std::fs::read_dir(path).map_err(|source| NewgitError::io(path, source))? {
        let entry = entry.map_err(|source| NewgitError::io(path, source))?;
        let path = Utf8PathBuf::from_path_buf(entry.path())
            .map_err(|path| NewgitError::NonUtf8Path(path.display().to_string()))?;
        if path.is_dir() {
            entries.push(path);
        }
    }
    entries.sort();
    Ok(entries)
}

pub(crate) fn read_dir_sorted(path: &Utf8Path) -> Result<Vec<Utf8PathBuf>> {
    if !path.exists() {
        return Ok(Vec::new());
    }

    let mut entries = Vec::new();
    for entry in std::fs::read_dir(path).map_err(|source| NewgitError::io(path, source))? {
        let entry = entry.map_err(|source| NewgitError::io(path, source))?;
        let path = Utf8PathBuf::from_path_buf(entry.path())
            .map_err(|path| NewgitError::NonUtf8Path(path.display().to_string()))?;
        if path.is_file() && path.file_name() != Some(".DS_Store") {
            entries.push(path);
        }
    }
    entries.sort();
    Ok(entries)
}