Skip to main content

memstead_base/
workspace_create.rs

1//! The refusals a command meets when it creates a workspace, a mem's
2//! folder or a schema package where one cannot go: inside another
3//! workspace, over a workspace already there, over a `.memstead/` that is
4//! not one, over a schema package already there, or into a folder with
5//! content. One type, so `init`, `quickstart` and `schema new` report each
6//! state with one code and one payload.
7
8use std::path::{Path, PathBuf};
9
10/// What a fresh workspace or mem folder refuses to be created over.
11#[derive(Debug, Clone, thiserror::Error)]
12pub enum WorkspaceCreateError {
13    #[error(
14        "{} is already inside the memstead workspace at {}; workspaces do not nest",
15        target.display(),
16        found_at.display()
17    )]
18    AlreadyExistsAbove { target: PathBuf, found_at: PathBuf },
19    #[error("{} is already a Memstead workspace", path.display())]
20    AlreadyInitialised { path: PathBuf },
21    #[error("{} already exists; a mem-repo is never created over one", path.display())]
22    MemRepoExists { path: PathBuf },
23    #[error(
24        "{} is a `.memstead/` directory that is not a workspace (no workspace.toml)",
25        store.display()
26    )]
27    ForeignMemsteadDir { store: PathBuf },
28    #[error("{} already contains a schema package, which is never overwritten", path.display())]
29    SchemaPackageExists { path: PathBuf },
30    #[error("{} is not empty (found {})", path.display(), found.join(", "))]
31    TargetNotEmpty {
32        path: PathBuf,
33        found: Vec<String>,
34        /// The command that retries with a free name, when the caller has one.
35        retry: Option<String>,
36    },
37}
38
39/// The recovery sentence a nested workspace carries on every surface.
40/// It names no command: which one works in the existing workspace
41/// depends on how that workspace was created (a quickstart workspace admits
42/// no `mem init`), so each command adds its own.
43pub const NESTED_WORKSPACE_HINT: &str =
44    "Work in the existing workspace, or create the new one in a folder outside it.";
45
46impl WorkspaceCreateError {
47    pub fn code(&self) -> &'static str {
48        match self {
49            WorkspaceCreateError::AlreadyExistsAbove { .. } => "WORKSPACE_ALREADY_EXISTS_ABOVE",
50            WorkspaceCreateError::AlreadyInitialised { .. } => "WORKSPACE_ALREADY_INITIALISED",
51            WorkspaceCreateError::ForeignMemsteadDir { .. } => "FOREIGN_MEMSTEAD_DIR",
52            WorkspaceCreateError::SchemaPackageExists { .. } => "SCHEMA_PACKAGE_EXISTS",
53            WorkspaceCreateError::MemRepoExists { .. } => "MEM_DB_ALREADY_EXISTS",
54            WorkspaceCreateError::TargetNotEmpty { .. } => "TARGET_NOT_EMPTY",
55        }
56    }
57
58    pub fn details(&self) -> serde_json::Value {
59        match self {
60            WorkspaceCreateError::AlreadyExistsAbove { found_at, .. } => serde_json::json!({
61                "found_at": found_at.display().to_string(),
62                "hint": NESTED_WORKSPACE_HINT,
63            }),
64            WorkspaceCreateError::AlreadyInitialised { path }
65            | WorkspaceCreateError::SchemaPackageExists { path }
66            | WorkspaceCreateError::MemRepoExists { path } => {
67                serde_json::json!({ "path": path.display().to_string() })
68            }
69            WorkspaceCreateError::ForeignMemsteadDir { store } => {
70                serde_json::json!({ "path": store.display().to_string() })
71            }
72            WorkspaceCreateError::TargetNotEmpty { path, found, retry } => {
73                let mut d = serde_json::json!({
74                    "path": path.display().to_string(),
75                    "found": found,
76                });
77                if let Some(retry) = retry {
78                    d["retry"] = serde_json::json!(retry);
79                }
80                d
81            }
82        }
83    }
84}
85
86/// The `workspace.toml` of the nearest workspace above `target` (not
87/// `target` itself), if any.
88pub fn ancestor_workspace(target: &Path) -> std::io::Result<Option<PathBuf>> {
89    let abs = std::fs::canonicalize(target)?;
90    for ancestor in abs.ancestors().skip(1) {
91        if crate::is_workspace_root(ancestor) {
92            return Ok(Some(
93                ancestor
94                    .join(crate::WORKSPACE_STORE_DIR)
95                    .join("workspace.toml"),
96            ));
97        }
98    }
99    Ok(None)
100}