refactor(cli,host): finish command, dispatch and package module split
This commit is contained in:
1 parent
8a0c068856
commit
7859c26213
9 files changed
+546
-504
No files matched your search
+6
-426
@@ -10,62 +10,26 @@ use marqdo_span::Span;
|
||||
use serde_json::json;
|
||||
|
||||
mod check;
|
||||
mod init;
|
||||
mod inspect;
|
||||
mod package;
|
||||
mod run;
|
||||
mod sandbox;
|
||||
mod tool;
|
||||
|
||||
pub use check::check;
|
||||
pub use init::init;
|
||||
pub use inspect::inspect;
|
||||
pub use inspect::InspectFlags;
|
||||
pub use package::{add, lock, remove, sync};
|
||||
pub use run::execute;
|
||||
pub use sandbox::SandboxSettings;
|
||||
pub use tool::{fmt, plugin_inspect};
|
||||
|
||||
use crate::args;
|
||||
use crate::loader::{self, FileDiagnostic, LoadedProject};
|
||||
use crate::output;
|
||||
|
||||
/// `marqdo init`.
|
||||
pub fn init(dir: Option<&Path>) -> i32 {
|
||||
let dir = dir.unwrap_or_else(|| Path::new("."));
|
||||
if dir.join(marqdo_package::MANIFEST_FILE).exists() {
|
||||
eprintln!(
|
||||
"error: `{}` already contains {}",
|
||||
dir.display(),
|
||||
marqdo_package::MANIFEST_FILE
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
let name = dir
|
||||
.canonicalize()
|
||||
.ok()
|
||||
.and_then(|path| {
|
||||
path.file_name()
|
||||
.map(|name| name.to_string_lossy().to_string())
|
||||
})
|
||||
.unwrap_or_else(|| "example".to_string());
|
||||
if let Err(error) = std::fs::create_dir_all(dir) {
|
||||
eprintln!("error: cannot create {}: {error}", dir.display());
|
||||
return 1;
|
||||
}
|
||||
let manifest = marqdo_package::Manifest::template(&name);
|
||||
if let Err(error) = std::fs::write(dir.join(marqdo_package::MANIFEST_FILE), manifest.to_yaml())
|
||||
{
|
||||
eprintln!("error: cannot write manifest: {error}");
|
||||
return 1;
|
||||
}
|
||||
let entry = dir.join("index.mq.md");
|
||||
if let Err(error) = std::fs::write(&entry, INIT_TEMPLATE) {
|
||||
eprintln!("error: cannot write {}: {error}", entry.display());
|
||||
return 1;
|
||||
}
|
||||
let _ = std::fs::write(dir.join(".gitignore"), ".marqdo/\n");
|
||||
println!("Initialized Marqdo project `{name}` in {}", dir.display());
|
||||
println!("Next: marqdo check index.mq.md && marqdo run index.mq.md");
|
||||
0
|
||||
}
|
||||
|
||||
const INIT_TEMPLATE: &str = "## main\n\n**问候 = \"你好,Marqdo\"**\n\n> 打印(问候)\n\n*问候*\n";
|
||||
|
||||
fn load_project(file: Option<&Path>, json: bool) -> Result<LoadedProject, i32> {
|
||||
let file = file.unwrap_or_else(|| Path::new("index.mq.md"));
|
||||
match loader::load(file) {
|
||||
@@ -565,390 +529,6 @@ fn render_runtime_error(error: &RuntimeError, project: &LoadedProject) -> String
|
||||
out
|
||||
}
|
||||
|
||||
/// `marqdo fmt`.
|
||||
pub fn fmt(file: Option<&Path>, check_only: bool) -> i32 {
|
||||
let file = file.unwrap_or_else(|| Path::new("index.mq.md"));
|
||||
let Ok(source) = std::fs::read_to_string(file) else {
|
||||
eprintln!("error: cannot read `{}`", file.display());
|
||||
return 2;
|
||||
};
|
||||
let mut formatted = source.replace("\r\n", "\n");
|
||||
while formatted.ends_with("\n\n") {
|
||||
formatted.pop();
|
||||
}
|
||||
if !formatted.ends_with('\n') {
|
||||
formatted.push('\n');
|
||||
}
|
||||
if formatted == source {
|
||||
return 0;
|
||||
}
|
||||
if check_only {
|
||||
eprintln!(
|
||||
"error: `{}` is not formatted (trailing whitespace/newlines or CRLF)",
|
||||
file.display()
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
if let Err(error) = std::fs::write(file, formatted) {
|
||||
eprintln!("error: cannot write `{}`: {error}", file.display());
|
||||
return 1;
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
/// `marqdo plugin inspect`.
|
||||
pub fn plugin_inspect(target: &Path, json: bool) -> i32 {
|
||||
let manifest_path = if target.is_dir() {
|
||||
target.join("plugin.yaml")
|
||||
} else {
|
||||
target.to_path_buf()
|
||||
};
|
||||
let base_dir = manifest_path
|
||||
.parent()
|
||||
.map(|parent| parent.to_path_buf())
|
||||
.unwrap_or_else(|| PathBuf::from("."));
|
||||
let manifest = match marqdo_plugin_abi::PluginManifest::load(&manifest_path) {
|
||||
Ok(manifest) => manifest,
|
||||
Err(error) => {
|
||||
report_plugin_error(&error, json);
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
if let Err(error) = manifest.validate() {
|
||||
report_plugin_error(&error, json);
|
||||
return 1;
|
||||
}
|
||||
let host_target = marqdo_plugin_abi::HostTarget::current();
|
||||
let artifact = match manifest.verify_artifact(&base_dir, &host_target) {
|
||||
Ok((path, artifact)) => {
|
||||
let abi = match manifest.abi_requirement() {
|
||||
Ok(requirement) => {
|
||||
if requirement.is_compatible_with(marqdo_plugin_abi::AbiVersion::current()) {
|
||||
"compatible"
|
||||
} else {
|
||||
"incompatible"
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
report_plugin_error(&error, json);
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
(path, artifact, abi)
|
||||
}
|
||||
Err(error) => {
|
||||
report_plugin_error(&error, json);
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
let (artifact_path, artifact_info, abi) = artifact;
|
||||
if json {
|
||||
output::print_json(&json!({
|
||||
"command": "plugin.inspect",
|
||||
"success": true,
|
||||
"plugin": manifest.plugin.name,
|
||||
"version": manifest.plugin.version,
|
||||
"abi": manifest.plugin.abi,
|
||||
"abi_compatibility": abi,
|
||||
"target": host_target.triple().as_str(),
|
||||
"artifact": {
|
||||
"file": artifact_info.file,
|
||||
"path": artifact_path.display().to_string(),
|
||||
"sha256": artifact_info.sha256,
|
||||
"verified": true,
|
||||
},
|
||||
"exports": manifest.plugin.exports.iter().map(|export| json!({
|
||||
"name": export.name,
|
||||
"signature": export.signature,
|
||||
})).collect::<Vec<_>>(),
|
||||
"loaded": false,
|
||||
}));
|
||||
} else {
|
||||
println!(
|
||||
"plugin: {} {}",
|
||||
manifest.plugin.name, manifest.plugin.version
|
||||
);
|
||||
println!("abi: {} ({abi})", manifest.plugin.abi);
|
||||
println!("target: {}", host_target.triple().as_str());
|
||||
println!(
|
||||
"artifact: {} (sha256 verified: {})",
|
||||
artifact_path.display(),
|
||||
artifact_info.sha256
|
||||
);
|
||||
println!("exports:");
|
||||
for export in &manifest.plugin.exports {
|
||||
println!(" {} {}", export.name, export.signature);
|
||||
}
|
||||
println!("loaded: false (inspection never executes plugin code)");
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
fn report_plugin_error(error: &marqdo_plugin_abi::PluginError, json: bool) {
|
||||
if json {
|
||||
output::print_json(&json!({
|
||||
"command": "plugin.inspect",
|
||||
"success": false,
|
||||
"error": {
|
||||
"kind": error.kind,
|
||||
"code": error.code,
|
||||
"message": error.message,
|
||||
}
|
||||
}));
|
||||
} else {
|
||||
eprintln!("error[{}]: {}", error.code, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/// `marqdo lock`.
|
||||
pub fn lock(json: bool) -> i32 {
|
||||
let root = match discover_project_root() {
|
||||
Ok(root) => root,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let manifest = match marqdo_package::Manifest::load(&root.join(marqdo_package::MANIFEST_FILE)) {
|
||||
Ok(manifest) => manifest,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let graph =
|
||||
match marqdo_package::PackageResolver::new(root.clone(), Some(manifest.clone()), None)
|
||||
.with_fetch(true)
|
||||
.with_unlocked(true)
|
||||
.resolve_lock_graph()
|
||||
{
|
||||
Ok(graph) => graph,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
let lockfile = graph.lock;
|
||||
let path = root.join(marqdo_package::LOCK_FILE);
|
||||
if let Err(error) = write_atomic(&path, lockfile.to_yaml().as_bytes()) {
|
||||
eprintln!("error: cannot write {}: {error}", path.display());
|
||||
return 1;
|
||||
}
|
||||
if json {
|
||||
output::print_json(&json!({
|
||||
"command": "lock",
|
||||
"success": true,
|
||||
"packages": lockfile.packages,
|
||||
}));
|
||||
} else {
|
||||
println!(
|
||||
"locked {} package(s) in {}",
|
||||
lockfile.packages.len(),
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
/// `marqdo sync [--locked]`.
|
||||
pub fn sync(locked: bool, json: bool) -> i32 {
|
||||
let root = match discover_project_root() {
|
||||
Ok(root) => root,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let manifest = match marqdo_package::Manifest::load(&root.join(marqdo_package::MANIFEST_FILE)) {
|
||||
Ok(manifest) => manifest,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let lock_path = root.join(marqdo_package::LOCK_FILE);
|
||||
if !lock_path.is_file() {
|
||||
eprintln!(
|
||||
"error: {} is missing; run `marqdo lock` first",
|
||||
lock_path.display()
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
let lockfile = match marqdo_package::LockFile::load(&lock_path) {
|
||||
Ok(lockfile) => lockfile,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
if let Err(error) = lockfile.validate_root(&manifest) {
|
||||
eprintln!("error: {error}");
|
||||
return 1;
|
||||
}
|
||||
let resolver =
|
||||
marqdo_package::PackageResolver::new(root, Some(manifest.clone()), Some(lockfile.clone()))
|
||||
.with_fetch(!locked);
|
||||
if let Err(error) = resolver.materialize_env(&lockfile) {
|
||||
eprintln!("error: cannot materialize project environment: {error}");
|
||||
return 1;
|
||||
}
|
||||
if json {
|
||||
output::print_json(&json!({
|
||||
"command": "sync",
|
||||
"success": true,
|
||||
"locked": locked,
|
||||
"packages": lockfile.packages,
|
||||
}));
|
||||
} else {
|
||||
println!(
|
||||
"synchronized {} package(s){} into {}",
|
||||
lockfile.packages.len(),
|
||||
if locked { " (locked)" } else { "" },
|
||||
resolver.env_root().display()
|
||||
);
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
fn discover_project_root() -> Result<PathBuf, String> {
|
||||
let cwd = std::env::current_dir().map_err(|error| error.to_string())?;
|
||||
marqdo_package::discover_root(&cwd).ok_or_else(|| {
|
||||
format!(
|
||||
"no {} found in {} or any parent",
|
||||
marqdo_package::MANIFEST_FILE,
|
||||
cwd.display()
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn write_atomic(path: &Path, contents: &[u8]) -> Result<(), String> {
|
||||
let file_name = path
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "marqdo.lock".to_string());
|
||||
let temp = path.with_file_name(format!(
|
||||
".{file_name}.tmp-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|duration| duration.as_nanos())
|
||||
.unwrap_or(0)
|
||||
));
|
||||
let result = (|| -> Result<(), String> {
|
||||
let mut file = std::fs::File::create(&temp)
|
||||
.map_err(|error| format!("cannot create {}: {error}", temp.display()))?;
|
||||
std::io::Write::write_all(&mut file, contents)
|
||||
.map_err(|error| format!("cannot write {}: {error}", temp.display()))?;
|
||||
file.sync_all()
|
||||
.map_err(|error| format!("cannot sync {}: {error}", temp.display()))?;
|
||||
std::fs::rename(&temp, path)
|
||||
.map_err(|error| format!("cannot publish {}: {error}", path.display()))?;
|
||||
Ok(())
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = std::fs::remove_file(&temp);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// `marqdo add <name> --path <dir> [--git URL --rev SHA]`.
|
||||
pub fn add(
|
||||
name: &str,
|
||||
path: Option<&Path>,
|
||||
git: Option<&str>,
|
||||
rev: Option<&str>,
|
||||
json: bool,
|
||||
) -> i32 {
|
||||
let root = match discover_project_root() {
|
||||
Ok(root) => root,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let manifest_path = root.join(marqdo_package::MANIFEST_FILE);
|
||||
let mut manifest = match marqdo_package::Manifest::load(&manifest_path) {
|
||||
Ok(manifest) => manifest,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let dependency = marqdo_package::Dependency {
|
||||
path: path.map(|path| path.to_path_buf()),
|
||||
git: git.map(str::to_string),
|
||||
rev: rev.map(str::to_string),
|
||||
};
|
||||
if let Err(error) = dependency.validate(name) {
|
||||
eprintln!("error: {error}");
|
||||
return 2;
|
||||
}
|
||||
if manifest.dependencies.contains_key(name) {
|
||||
eprintln!("error: dependency `{name}` already exists; remove it first");
|
||||
return 1;
|
||||
}
|
||||
manifest.dependencies.insert(name.to_string(), dependency);
|
||||
if let Err(error) = std::fs::write(&manifest_path, manifest.to_yaml()) {
|
||||
eprintln!("error: cannot write {}: {error}", manifest_path.display());
|
||||
return 1;
|
||||
}
|
||||
if json {
|
||||
output::print_json(&json!({
|
||||
"command": "add",
|
||||
"success": true,
|
||||
"dependency": name,
|
||||
"manifest": manifest_path.display().to_string(),
|
||||
}));
|
||||
} else {
|
||||
println!("added dependency `{name}` to {}", manifest_path.display());
|
||||
println!(
|
||||
"run `marqdo lock` to pin it in {}",
|
||||
marqdo_package::LOCK_FILE
|
||||
);
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
/// `marqdo remove <name>`.
|
||||
pub fn remove(name: &str, json: bool) -> i32 {
|
||||
let root = match discover_project_root() {
|
||||
Ok(root) => root,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let manifest_path = root.join(marqdo_package::MANIFEST_FILE);
|
||||
let mut manifest = match marqdo_package::Manifest::load(&manifest_path) {
|
||||
Ok(manifest) => manifest,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
if manifest.dependencies.remove(name).is_none() {
|
||||
eprintln!("error: dependency `{name}` is not declared");
|
||||
return 1;
|
||||
}
|
||||
if let Err(error) = std::fs::write(&manifest_path, manifest.to_yaml()) {
|
||||
eprintln!("error: cannot write {}: {error}", manifest_path.display());
|
||||
return 1;
|
||||
}
|
||||
// The lock is a graph, not a per-name list: regenerating it here would
|
||||
// require resolving the new manifest. Leave it stale and tell the user.
|
||||
if json {
|
||||
output::print_json(&json!({
|
||||
"command": "remove",
|
||||
"success": true,
|
||||
"dependency": name,
|
||||
}));
|
||||
} else {
|
||||
println!("removed dependency `{name}`");
|
||||
println!("run `marqdo lock` to refresh {}", marqdo_package::LOCK_FILE);
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
/// Resolve `--arg` strings into typed arguments.
|
||||
pub fn parse_named_args(raw: &[String]) -> Result<Vec<(String, Value)>, String> {
|
||||
raw.iter()
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
//! `marqdo init` command.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// `marqdo init`.
|
||||
pub fn init(dir: Option<&Path>) -> i32 {
|
||||
let dir = dir.unwrap_or_else(|| Path::new("."));
|
||||
if dir.join(marqdo_package::MANIFEST_FILE).exists() {
|
||||
eprintln!(
|
||||
"error: `{}` already contains {}",
|
||||
dir.display(),
|
||||
marqdo_package::MANIFEST_FILE
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
let name = dir
|
||||
.canonicalize()
|
||||
.ok()
|
||||
.and_then(|path| {
|
||||
path.file_name()
|
||||
.map(|name| name.to_string_lossy().to_string())
|
||||
})
|
||||
.unwrap_or_else(|| "example".to_string());
|
||||
if let Err(error) = std::fs::create_dir_all(dir) {
|
||||
eprintln!("error: cannot create {}: {error}", dir.display());
|
||||
return 1;
|
||||
}
|
||||
let manifest = marqdo_package::Manifest::template(&name);
|
||||
if let Err(error) = std::fs::write(dir.join(marqdo_package::MANIFEST_FILE), manifest.to_yaml())
|
||||
{
|
||||
eprintln!("error: cannot write manifest: {error}");
|
||||
return 1;
|
||||
}
|
||||
let entry = dir.join("index.mq.md");
|
||||
if let Err(error) = std::fs::write(&entry, INIT_TEMPLATE) {
|
||||
eprintln!("error: cannot write {}: {error}", entry.display());
|
||||
return 1;
|
||||
}
|
||||
let _ = std::fs::write(dir.join(".gitignore"), ".marqdo/\n");
|
||||
println!("Initialized Marqdo project `{name}` in {}", dir.display());
|
||||
println!("Next: marqdo check index.mq.md && marqdo run index.mq.md");
|
||||
0
|
||||
}
|
||||
|
||||
const INIT_TEMPLATE: &str = "## main\n\n**问候 = \"你好,Marqdo\"**\n\n> 打印(问候)\n\n*问候*\n";
|
||||
@@ -0,0 +1,252 @@
|
||||
//! Package lock/sync/add/remove commands.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// `marqdo lock`.
|
||||
pub fn lock(json: bool) -> i32 {
|
||||
let root = match discover_project_root() {
|
||||
Ok(root) => root,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let manifest = match marqdo_package::Manifest::load(&root.join(marqdo_package::MANIFEST_FILE)) {
|
||||
Ok(manifest) => manifest,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let graph =
|
||||
match marqdo_package::PackageResolver::new(root.clone(), Some(manifest.clone()), None)
|
||||
.with_fetch(true)
|
||||
.with_unlocked(true)
|
||||
.resolve_lock_graph()
|
||||
{
|
||||
Ok(graph) => graph,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
let lockfile = graph.lock;
|
||||
let path = root.join(marqdo_package::LOCK_FILE);
|
||||
if let Err(error) = write_atomic(&path, lockfile.to_yaml().as_bytes()) {
|
||||
eprintln!("error: cannot write {}: {error}", path.display());
|
||||
return 1;
|
||||
}
|
||||
if json {
|
||||
output::print_json(&json!({
|
||||
"command": "lock",
|
||||
"success": true,
|
||||
"packages": lockfile.packages,
|
||||
}));
|
||||
} else {
|
||||
println!(
|
||||
"locked {} package(s) in {}",
|
||||
lockfile.packages.len(),
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
/// `marqdo sync [--locked]`.
|
||||
pub fn sync(locked: bool, json: bool) -> i32 {
|
||||
let root = match discover_project_root() {
|
||||
Ok(root) => root,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let manifest = match marqdo_package::Manifest::load(&root.join(marqdo_package::MANIFEST_FILE)) {
|
||||
Ok(manifest) => manifest,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let lock_path = root.join(marqdo_package::LOCK_FILE);
|
||||
if !lock_path.is_file() {
|
||||
eprintln!(
|
||||
"error: {} is missing; run `marqdo lock` first",
|
||||
lock_path.display()
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
let lockfile = match marqdo_package::LockFile::load(&lock_path) {
|
||||
Ok(lockfile) => lockfile,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
if let Err(error) = lockfile.validate_root(&manifest) {
|
||||
eprintln!("error: {error}");
|
||||
return 1;
|
||||
}
|
||||
let resolver =
|
||||
marqdo_package::PackageResolver::new(root, Some(manifest.clone()), Some(lockfile.clone()))
|
||||
.with_fetch(!locked);
|
||||
if let Err(error) = resolver.materialize_env(&lockfile) {
|
||||
eprintln!("error: cannot materialize project environment: {error}");
|
||||
return 1;
|
||||
}
|
||||
if json {
|
||||
output::print_json(&json!({
|
||||
"command": "sync",
|
||||
"success": true,
|
||||
"locked": locked,
|
||||
"packages": lockfile.packages,
|
||||
}));
|
||||
} else {
|
||||
println!(
|
||||
"synchronized {} package(s){} into {}",
|
||||
lockfile.packages.len(),
|
||||
if locked { " (locked)" } else { "" },
|
||||
resolver.env_root().display()
|
||||
);
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
fn discover_project_root() -> Result<PathBuf, String> {
|
||||
let cwd = std::env::current_dir().map_err(|error| error.to_string())?;
|
||||
marqdo_package::discover_root(&cwd).ok_or_else(|| {
|
||||
format!(
|
||||
"no {} found in {} or any parent",
|
||||
marqdo_package::MANIFEST_FILE,
|
||||
cwd.display()
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn write_atomic(path: &Path, contents: &[u8]) -> Result<(), String> {
|
||||
let file_name = path
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "marqdo.lock".to_string());
|
||||
let temp = path.with_file_name(format!(
|
||||
".{file_name}.tmp-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|duration| duration.as_nanos())
|
||||
.unwrap_or(0)
|
||||
));
|
||||
let result = (|| -> Result<(), String> {
|
||||
let mut file = std::fs::File::create(&temp)
|
||||
.map_err(|error| format!("cannot create {}: {error}", temp.display()))?;
|
||||
std::io::Write::write_all(&mut file, contents)
|
||||
.map_err(|error| format!("cannot write {}: {error}", temp.display()))?;
|
||||
file.sync_all()
|
||||
.map_err(|error| format!("cannot sync {}: {error}", temp.display()))?;
|
||||
std::fs::rename(&temp, path)
|
||||
.map_err(|error| format!("cannot publish {}: {error}", path.display()))?;
|
||||
Ok(())
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = std::fs::remove_file(&temp);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// `marqdo add <name> --path <dir> [--git URL --rev SHA]`.
|
||||
pub fn add(
|
||||
name: &str,
|
||||
path: Option<&Path>,
|
||||
git: Option<&str>,
|
||||
rev: Option<&str>,
|
||||
json: bool,
|
||||
) -> i32 {
|
||||
let root = match discover_project_root() {
|
||||
Ok(root) => root,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let manifest_path = root.join(marqdo_package::MANIFEST_FILE);
|
||||
let mut manifest = match marqdo_package::Manifest::load(&manifest_path) {
|
||||
Ok(manifest) => manifest,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let dependency = marqdo_package::Dependency {
|
||||
path: path.map(|path| path.to_path_buf()),
|
||||
git: git.map(str::to_string),
|
||||
rev: rev.map(str::to_string),
|
||||
};
|
||||
if let Err(error) = dependency.validate(name) {
|
||||
eprintln!("error: {error}");
|
||||
return 2;
|
||||
}
|
||||
if manifest.dependencies.contains_key(name) {
|
||||
eprintln!("error: dependency `{name}` already exists; remove it first");
|
||||
return 1;
|
||||
}
|
||||
manifest.dependencies.insert(name.to_string(), dependency);
|
||||
if let Err(error) = std::fs::write(&manifest_path, manifest.to_yaml()) {
|
||||
eprintln!("error: cannot write {}: {error}", manifest_path.display());
|
||||
return 1;
|
||||
}
|
||||
if json {
|
||||
output::print_json(&json!({
|
||||
"command": "add",
|
||||
"success": true,
|
||||
"dependency": name,
|
||||
"manifest": manifest_path.display().to_string(),
|
||||
}));
|
||||
} else {
|
||||
println!("added dependency `{name}` to {}", manifest_path.display());
|
||||
println!(
|
||||
"run `marqdo lock` to pin it in {}",
|
||||
marqdo_package::LOCK_FILE
|
||||
);
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
/// `marqdo remove <name>`.
|
||||
pub fn remove(name: &str, json: bool) -> i32 {
|
||||
let root = match discover_project_root() {
|
||||
Ok(root) => root,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let manifest_path = root.join(marqdo_package::MANIFEST_FILE);
|
||||
let mut manifest = match marqdo_package::Manifest::load(&manifest_path) {
|
||||
Ok(manifest) => manifest,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
if manifest.dependencies.remove(name).is_none() {
|
||||
eprintln!("error: dependency `{name}` is not declared");
|
||||
return 1;
|
||||
}
|
||||
if let Err(error) = std::fs::write(&manifest_path, manifest.to_yaml()) {
|
||||
eprintln!("error: cannot write {}: {error}", manifest_path.display());
|
||||
return 1;
|
||||
}
|
||||
// The lock is a graph, not a per-name list: regenerating it here would
|
||||
// require resolving the new manifest. Leave it stale and tell the user.
|
||||
if json {
|
||||
output::print_json(&json!({
|
||||
"command": "remove",
|
||||
"success": true,
|
||||
"dependency": name,
|
||||
}));
|
||||
} else {
|
||||
println!("removed dependency `{name}`");
|
||||
println!("run `marqdo lock` to refresh {}", marqdo_package::LOCK_FILE);
|
||||
}
|
||||
0
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
//! CLI formatter and plugin/tool inspection commands.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// `marqdo fmt`.
|
||||
pub fn fmt(file: Option<&Path>, check_only: bool) -> i32 {
|
||||
let file = file.unwrap_or_else(|| Path::new("index.mq.md"));
|
||||
let Ok(source) = std::fs::read_to_string(file) else {
|
||||
eprintln!("error: cannot read `{}`", file.display());
|
||||
return 2;
|
||||
};
|
||||
let mut formatted = source.replace("\r\n", "\n");
|
||||
while formatted.ends_with("\n\n") {
|
||||
formatted.pop();
|
||||
}
|
||||
if !formatted.ends_with('\n') {
|
||||
formatted.push('\n');
|
||||
}
|
||||
if formatted == source {
|
||||
return 0;
|
||||
}
|
||||
if check_only {
|
||||
eprintln!(
|
||||
"error: `{}` is not formatted (trailing whitespace/newlines or CRLF)",
|
||||
file.display()
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
if let Err(error) = std::fs::write(file, formatted) {
|
||||
eprintln!("error: cannot write `{}`: {error}", file.display());
|
||||
return 1;
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
/// `marqdo plugin inspect`.
|
||||
pub fn plugin_inspect(target: &Path, json: bool) -> i32 {
|
||||
let manifest_path = if target.is_dir() {
|
||||
target.join("plugin.yaml")
|
||||
} else {
|
||||
target.to_path_buf()
|
||||
};
|
||||
let base_dir = manifest_path
|
||||
.parent()
|
||||
.map(|parent| parent.to_path_buf())
|
||||
.unwrap_or_else(|| PathBuf::from("."));
|
||||
let manifest = match marqdo_plugin_abi::PluginManifest::load(&manifest_path) {
|
||||
Ok(manifest) => manifest,
|
||||
Err(error) => {
|
||||
report_plugin_error(&error, json);
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
if let Err(error) = manifest.validate() {
|
||||
report_plugin_error(&error, json);
|
||||
return 1;
|
||||
}
|
||||
let host_target = marqdo_plugin_abi::HostTarget::current();
|
||||
let artifact = match manifest.verify_artifact(&base_dir, &host_target) {
|
||||
Ok((path, artifact)) => {
|
||||
let abi = match manifest.abi_requirement() {
|
||||
Ok(requirement) => {
|
||||
if requirement.is_compatible_with(marqdo_plugin_abi::AbiVersion::current()) {
|
||||
"compatible"
|
||||
} else {
|
||||
"incompatible"
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
report_plugin_error(&error, json);
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
(path, artifact, abi)
|
||||
}
|
||||
Err(error) => {
|
||||
report_plugin_error(&error, json);
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
let (artifact_path, artifact_info, abi) = artifact;
|
||||
if json {
|
||||
output::print_json(&json!({
|
||||
"command": "plugin.inspect",
|
||||
"success": true,
|
||||
"plugin": manifest.plugin.name,
|
||||
"version": manifest.plugin.version,
|
||||
"abi": manifest.plugin.abi,
|
||||
"abi_compatibility": abi,
|
||||
"target": host_target.triple().as_str(),
|
||||
"artifact": {
|
||||
"file": artifact_info.file,
|
||||
"path": artifact_path.display().to_string(),
|
||||
"sha256": artifact_info.sha256,
|
||||
"verified": true,
|
||||
},
|
||||
"exports": manifest.plugin.exports.iter().map(|export| json!({
|
||||
"name": export.name,
|
||||
"signature": export.signature,
|
||||
})).collect::<Vec<_>>(),
|
||||
"loaded": false,
|
||||
}));
|
||||
} else {
|
||||
println!(
|
||||
"plugin: {} {}",
|
||||
manifest.plugin.name, manifest.plugin.version
|
||||
);
|
||||
println!("abi: {} ({abi})", manifest.plugin.abi);
|
||||
println!("target: {}", host_target.triple().as_str());
|
||||
println!(
|
||||
"artifact: {} (sha256 verified: {})",
|
||||
artifact_path.display(),
|
||||
artifact_info.sha256
|
||||
);
|
||||
println!("exports:");
|
||||
for export in &manifest.plugin.exports {
|
||||
println!(" {} {}", export.name, export.signature);
|
||||
}
|
||||
println!("loaded: false (inspection never executes plugin code)");
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
fn report_plugin_error(error: &marqdo_plugin_abi::PluginError, json: bool) {
|
||||
if json {
|
||||
output::print_json(&json!({
|
||||
"command": "plugin.inspect",
|
||||
"success": false,
|
||||
"error": {
|
||||
"kind": error.kind,
|
||||
"code": error.code,
|
||||
"message": error.message,
|
||||
}
|
||||
}));
|
||||
} else {
|
||||
eprintln!("error[{}]: {}", error.code, error.message);
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ use crate::resource::{ResourceProvider, ResourceRead, ResourceTable, SharedResou
|
||||
use crate::trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState};
|
||||
use marqdo_sandbox::{PlatformCapabilities, SandboxMode};
|
||||
|
||||
mod dispatch;
|
||||
mod effects;
|
||||
mod providers;
|
||||
mod resource_ops;
|
||||
@@ -519,19 +520,7 @@ impl StdHost {
|
||||
args: Vec<Value>,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
match op {
|
||||
HostOp::FsRead => self.op_fs_read(args, ctx),
|
||||
HostOp::FsWrite => self.op_fs_write(args, ctx),
|
||||
HostOp::MathParse
|
||||
| HostOp::MathEval
|
||||
| HostOp::MathSubstitute
|
||||
| HostOp::MathSimplify
|
||||
| HostOp::MathDifferentiate => crate::kernels::math(self, op, args, ctx),
|
||||
HostOp::ForeignRun | HostOp::ForeignCall => {
|
||||
crate::kernels::foreign(self, op, args, ctx)
|
||||
}
|
||||
HostOp::PluginInvoke => self.op_plugin_invoke(args, ctx),
|
||||
}
|
||||
dispatch::dispatch(self, op, args, ctx)
|
||||
}
|
||||
|
||||
fn op_fs_read(
|
||||
@@ -616,56 +605,7 @@ impl Host for StdHost {
|
||||
args: Vec<Value>,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
// Addressable memory is language-local state. Handles must not reach a
|
||||
// plugin, foreign kernel or file adapter, where they could not be
|
||||
// interpreted safely (RFC-CM-0001 §8, ADR-0022 §4).
|
||||
if args.iter().any(Value::contains_memory) {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Type,
|
||||
ctx.span,
|
||||
format!(
|
||||
"Memory values cannot cross the host boundary (`{}`); copy bytes into \
|
||||
Text explicitly first",
|
||||
op.name()
|
||||
),
|
||||
));
|
||||
}
|
||||
if args.iter().any(Value::contains_resource) {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Type,
|
||||
ctx.span,
|
||||
format!(
|
||||
"Resource handles cannot cross the generic host boundary (`{}`); use \
|
||||
resource.* operations",
|
||||
op.name()
|
||||
),
|
||||
));
|
||||
}
|
||||
let started = Instant::now();
|
||||
let result = self.dispatch(op, args, ctx);
|
||||
let summary = match &result {
|
||||
Ok(_) => "ok".to_string(),
|
||||
Err(error) => error.code().to_string(),
|
||||
};
|
||||
let estimate = TraceState::estimate(
|
||||
"effect",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
Some(&summary),
|
||||
Some(op.name()),
|
||||
);
|
||||
if self.trace_state.accept(estimate) {
|
||||
let seq = self.next_seq();
|
||||
self.trace.record(
|
||||
seq,
|
||||
op.name(),
|
||||
ctx.module_id.clone(),
|
||||
ctx.span,
|
||||
started.elapsed(),
|
||||
summary,
|
||||
);
|
||||
}
|
||||
result
|
||||
dispatch::invoke(self, op, args, ctx)
|
||||
}
|
||||
|
||||
fn resource_open(
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
//! `Host::invoke` dispatch table.
|
||||
//!
|
||||
//! Child module of `host`: it may call the parent's private capability,
|
||||
//! resource and trace helpers. `StdHost` remains the only host implementation.
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(crate) fn invoke(
|
||||
host: &mut StdHost,
|
||||
op: HostOp,
|
||||
args: Vec<Value>,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
// Addressable memory is language-local state. Handles must not reach a
|
||||
// plugin, foreign kernel or file adapter, where they could not be
|
||||
// interpreted safely (RFC-CM-0001 §8, ADR-0022 §4).
|
||||
if args.iter().any(Value::contains_memory) {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Type,
|
||||
ctx.span,
|
||||
format!(
|
||||
"Memory values cannot cross the host boundary (`{}`); copy bytes into \
|
||||
Text explicitly first",
|
||||
op.name()
|
||||
),
|
||||
));
|
||||
}
|
||||
if args.iter().any(Value::contains_resource) {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Type,
|
||||
ctx.span,
|
||||
format!(
|
||||
"Resource handles cannot cross the generic host boundary (`{}`); use \
|
||||
resource.* operations",
|
||||
op.name()
|
||||
),
|
||||
));
|
||||
}
|
||||
let started = Instant::now();
|
||||
let result = host.dispatch(op, args, ctx);
|
||||
let summary = match &result {
|
||||
Ok(_) => "ok".to_string(),
|
||||
Err(error) => error.code().to_string(),
|
||||
};
|
||||
let estimate = TraceState::estimate(
|
||||
"effect",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
Some(&summary),
|
||||
Some(op.name()),
|
||||
);
|
||||
if host.trace_state.accept(estimate) {
|
||||
let seq = host.next_seq();
|
||||
host.trace.record(
|
||||
seq,
|
||||
op.name(),
|
||||
ctx.module_id.clone(),
|
||||
ctx.span,
|
||||
started.elapsed(),
|
||||
summary,
|
||||
);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) fn dispatch(
|
||||
host: &mut StdHost,
|
||||
op: HostOp,
|
||||
args: Vec<Value>,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
match op {
|
||||
HostOp::FsRead => host.op_fs_read(args, ctx),
|
||||
HostOp::FsWrite => host.op_fs_write(args, ctx),
|
||||
HostOp::MathParse
|
||||
| HostOp::MathEval
|
||||
| HostOp::MathSubstitute
|
||||
| HostOp::MathSimplify
|
||||
| HostOp::MathDifferentiate => crate::kernels::math(host, op, args, ctx),
|
||||
HostOp::ForeignRun | HostOp::ForeignCall => crate::kernels::foreign(host, op, args, ctx),
|
||||
HostOp::PluginInvoke => host.op_plugin_invoke(args, ctx),
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -242,10 +242,10 @@ This is still a **local VM lane**, not a self-hosted GitHub Actions security URL
|
||||
`0d40de7`; later docs-only commits keep code/test bytes identical. Evidence:
|
||||
[`docs-and-test-migration`](evidence/2026-11-21-docs-and-test-migration.md).
|
||||
- Module-boundary refactor (review RFC-CM P1): CLI split into
|
||||
`commands/{sandbox,run,check,inspect}.rs`; host split into
|
||||
`host/{resource_ops,providers,effects}.rs` plus `process.rs`. `commands.rs`
|
||||
still owns init/fmt/lock/sync/package/tool and `host.rs` still owns the
|
||||
`Host::invoke` dispatch and capability checks; this is a behavior-preserving
|
||||
`commands/{sandbox,run,check,inspect,init,package,tool}.rs`; host split into
|
||||
`host/{resource_ops,providers,effects,dispatch}.rs` plus `process.rs`.
|
||||
`commands.rs` keeps shared project/runtime helpers and `host.rs` keeps the
|
||||
`Host` trait methods and capability checks; this is a behavior-preserving
|
||||
split, not a new crate or backend.
|
||||
- Minimal structure observation/construction (RFC-CM CM-A04, ADR-0023):
|
||||
value-semantics `list.append/concat`, `map.keys/has/get/set/remove`,
|
||||
|
||||
@@ -62,10 +62,10 @@ Layer rules:
|
||||
human/machine output. It is not a semantic policy centre.
|
||||
5. Callable Plugin and Resource Provider share one registry/authorization/audit
|
||||
mechanism, but keep different capability types.
|
||||
6. CLI policy/commands are `commands/{sandbox,run,check,inspect}.rs`; host
|
||||
open-path/providers/effects are `host/{resource_ops,providers,effects}.rs`;
|
||||
process execution is `process.rs`. These are child modules, not new crates
|
||||
or a second backend.
|
||||
6. CLI policy/commands are `commands/{sandbox,run,check,inspect,init,package,tool}.rs`;
|
||||
host open-path/providers/effects/dispatch are
|
||||
`host/{resource_ops,providers,effects,dispatch}.rs`; process execution is
|
||||
`process.rs`. These are child modules, not new crates or a second backend.
|
||||
|
||||
## 3. Dependency direction and public contracts
|
||||
|
||||
@@ -128,7 +128,7 @@ that a phase is complete.
|
||||
| P1 | `std:fs/file` read/write/copy and `resource.request` fs metadata/directory operations are implemented; append/seek/watch/recursive walk remain open | open |
|
||||
| P1 | No file append/seek/watch/recursive directory walk | open; future Resource Operation extension |
|
||||
| P1 | JSON/CSV product parsers are implemented; no streaming/multi-line CSV or depth-bounded JSON walker | open |
|
||||
| P1 | CLI split into `commands/{sandbox,run,check,inspect}.rs`; host split into `host/{resource_ops,providers,effects}.rs` plus `process.rs`; `commands.rs` still owns init/fmt/lock/sync/package/tool and `host.rs` still owns `Host::invoke` dispatch | mostly split; package/tool/lock/sync and invoke dispatch remain |
|
||||
| P1 | CLI split into `commands/{sandbox,run,check,inspect,init,package,tool}.rs`; host split into `host/{resource_ops,providers,effects,dispatch}.rs` plus `process.rs`; `commands.rs` keeps shared project/runtime helpers and `host.rs` keeps the `Host` trait methods and capability checks | split; shared helpers and trait methods remain by design |
|
||||
| P2 | HTTP parsing is Unicode-codepoint oriented; a general byte body is not the only path | open; convert before a general network release |
|
||||
| P2 | No DNS, TLS, listener or UDP provider | open |
|
||||
| P2 | `std:path`, a regex subset, `std:datetime`, `std:clock`, `std:env` and `std:process` are implemented; no secure random or compression | open |
|
||||
|
||||
@@ -13,15 +13,19 @@ RFC item: P1 module boundaries
|
||||
| `crates/cli/src/commands/run.rs` | `execute` run-session assembly and `read_stdin` |
|
||||
| `crates/cli/src/commands/check.rs` | `check` command |
|
||||
| `crates/cli/src/commands/inspect.rs` | `inspect` command and `InspectFlags` |
|
||||
| `crates/cli/src/commands/init.rs` | `init` command |
|
||||
| `crates/cli/src/commands/package.rs` | `lock`/`sync`/`add`/`remove` and atomic writes |
|
||||
| `crates/cli/src/commands/tool.rs` | `fmt` and `plugin-inspect` commands |
|
||||
| `crates/marqdo-host/src/host/resource_ops.rs` | `open_resource_stream` stdio/file/tcp/provider dispatch; child module of `host` |
|
||||
| `crates/marqdo-host/src/host/providers.rs` | trusted in-process/worker/C-ABI/package provider registration |
|
||||
| `crates/marqdo-host/src/host/effects.rs` | `next_seq` and `record_resource_effect` trace helpers |
|
||||
| `crates/marqdo-host/src/host/dispatch.rs` | `Host::invoke` argument/effect wrapper and `StdHost::dispatch` match |
|
||||
| `crates/marqdo-host/src/process.rs` | explicitly granted `process.run` execution, timeout and output caps |
|
||||
|
||||
This is a **behavior-preserving** refactor: no public CLI flag, host trait
|
||||
method, builtin, spec or stdlib API changed. No new crate was added.
|
||||
`commands.rs` still owns init/fmt/lock/sync/package/tool and `host.rs` still
|
||||
owns `Host::invoke` dispatch and capability checks.
|
||||
`commands.rs` keeps shared project/runtime helpers and `parse_named_args`;
|
||||
`host.rs` keeps the `Host` trait methods and capability checks.
|
||||
|
||||
## Commands
|
||||
|
||||
@@ -36,7 +40,7 @@ python3 tools/pack-stdlib.py PASS
|
||||
|
||||
## Not covered
|
||||
|
||||
`commands.rs` still contains init/fmt/lock/sync/package/tool command bodies
|
||||
and `host.rs` still contains `Host::invoke` dispatch, capability checks and
|
||||
register entry points. A complete split needs a later behavior-preserving
|
||||
change; it is not claimed here.
|
||||
`commands.rs` still contains shared project/runtime helpers and
|
||||
`parse_named_args`; `host.rs` still contains the `Host` trait methods,
|
||||
capability checks and struct definitions. That is intentional module surface,
|
||||
not a second backend.
|
||||
Reference in new issue
Block a user