use std::borrow::Cow;
use std::env;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use clap::{Args, Subcommand};
use super::mounts::{Mount, Refusal};
use crate::home::project_mounts;
use crate::repr::repr;
use crate::store::grammar::Actor;
pub const SCOPE_ENV: &str = "NEOSIAN_SCOPE";
pub const SUGAR_MOUNT_PATH: &str = "memories";
#[derive(Args)]
pub struct Flags {
#[arg(long)]
pub root: Option<PathBuf>,
#[arg(long)]
scope: Option<String>,
#[arg(long, value_name = "scope=...,path=...[,ro|,eo]")]
mount: Vec<String>,
#[arg(long, default_value = "cli:local")]
actor: String,
#[arg(long)]
pub json: bool,
}
#[derive(Subcommand)]
pub enum Command {
View {
#[arg(default_value = "/")]
path: String,
#[arg(long, num_args = 2, value_names = ["START", "END"], allow_negative_numbers = true)]
view_range: Option<Vec<i64>>,
#[command(flatten)]
flags: Flags,
},
Create {
path: String,
#[arg(long, allow_hyphen_values = true)]
content: String,
#[command(flatten)]
flags: Flags,
},
#[command(name = "str_replace")]
StrReplace {
path: String,
#[arg(long, allow_hyphen_values = true)]
old_str: String,
#[arg(long, allow_hyphen_values = true)]
new_str: String,
#[command(flatten)]
flags: Flags,
},
Insert {
path: String,
#[arg(long, allow_negative_numbers = true)]
insert_line: i64,
#[arg(long, allow_hyphen_values = true)]
insert_text: String,
#[command(flatten)]
flags: Flags,
},
Delete {
path: String,
#[command(flatten)]
flags: Flags,
},
Rename {
#[arg(value_name = "OLD")]
old_path: String,
#[arg(value_name = "NEW")]
new_path: String,
#[command(flatten)]
flags: Flags,
},
Versions {
path: String,
#[arg(
long,
value_name = "N",
default_value_t = 50,
allow_negative_numbers = true
)]
limit: i64,
#[command(flatten)]
flags: Flags,
},
Redact {
path: String,
#[arg(long)]
all: bool,
#[command(flatten)]
flags: Flags,
},
Revert {
path: String,
#[arg(long, value_name = "N", allow_negative_numbers = true)]
version: i64,
#[command(flatten)]
flags: Flags,
},
}
impl Command {
pub fn flags(&self) -> &Flags {
match self {
Self::View { flags, .. }
| Self::Create { flags, .. }
| Self::StrReplace { flags, .. }
| Self::Insert { flags, .. }
| Self::Delete { flags, .. }
| Self::Rename { flags, .. }
| Self::Versions { flags, .. }
| Self::Redact { flags, .. }
| Self::Revert { flags, .. } => flags,
}
}
fn guard(&self) -> Result<(), Refusal> {
let refuse = |message: String| Err(Refusal::Usage(message));
match self {
Self::Versions { limit, .. } if *limit < 1 => {
refuse("--limit must be at least 1".to_string())
}
Self::Revert { version, .. } if *version < 1 => {
refuse("--version must be at least 1 (versions start at 1)".to_string())
}
Self::Redact { path, all, .. } => {
let root = !path.trim_matches('/').contains('/');
match (root, all) {
(true, false) => refuse(format!(
"{} names a whole mount: pass --all to redact its entire scope \
(irreversible)",
repr(path)
)),
(false, true) => refuse(
"--all redacts a whole mount: pass the mount root, not a document"
.to_string(),
),
_ => Ok(()),
}
}
_ => Ok(()),
}
}
pub fn payload(&self) -> io::Result<Cow<'_, str>> {
let value = match self {
Self::Create { content, .. } => content,
Self::StrReplace { new_str, .. } => new_str,
Self::Insert { insert_text, .. } => insert_text,
_ => return Ok(Cow::Borrowed("")),
};
if value != "-" {
return Ok(Cow::Borrowed(value));
}
let mut text = String::new();
io::stdin().read_to_string(&mut text)?;
if cfg!(windows) {
text = text.replace("\r\n", "\n").replace('\r', "\n");
}
Ok(Cow::Owned(text))
}
pub fn settings(&self, cwd: &Path) -> Result<(Vec<Mount>, Actor), Refusal> {
let flags = self.flags();
if flags.scope.is_some() && !flags.mount.is_empty() {
let sugar = "--scope is the single-mount sugar; use --mount for multi-mount";
return Err(Refusal::Usage(sugar.to_string()));
}
let named = env::var(SCOPE_ENV).ok().filter(|scope| !scope.is_empty());
let mounts = match flags.scope.as_ref().or(named.as_ref()) {
_ if !flags.mount.is_empty() => {
let parsed: Result<Vec<_>, _> =
flags.mount.iter().map(|m| Mount::parse(m)).collect();
parsed?
}
Some(scope) => vec![Mount::new(scope, SUGAR_MOUNT_PATH, (false, false), "")?],
None => project_mounts(cwd)?,
};
let twice = |mount: &Mount| {
mounts
.iter()
.filter(|other| other.path == mount.path)
.count()
> 1
};
if mounts.iter().any(twice) {
return Err(Refusal::Usage("mount paths must be unique".to_string()));
}
let actor = Actor::parse(&flags.actor).map_err(|reason| {
let actor = repr(&flags.actor);
Refusal::Usage(format!("--actor {actor}: {reason} (e.g. cli:claude-code)"))
})?;
self.guard()?;
Ok((mounts, actor))
}
}