use crate::identity::IdentityFlags;
use clap::{ArgGroup, Args};
use graphforge_api::{GfError, ResearchRegistry};
use serde_json::{Value, json};
use std::io::Write;
use std::path::PathBuf;
use uuid::Uuid;
mod local;
pub(crate) mod remote;
mod render;
#[cfg(test)]
mod tests;
#[derive(Args, Default, Clone)]
pub(crate) struct BranchSelect {
#[arg(long)]
pub branch: Option<String>,
}
#[derive(Args, Default, Clone)]
pub(crate) struct HubFlags {
#[arg(long)]
pub hub: Option<String>,
#[arg(long)]
pub token_env: Option<String>,
#[arg(long)]
pub protection_bypass_env: Option<String>,
}
#[derive(Args)]
pub(crate) struct StatusArgs {
#[command(flatten)]
pub select: BranchSelect,
}
#[derive(Args)]
pub(crate) struct LogArgs {
pub version: Option<String>,
#[command(flatten)]
pub select: BranchSelect,
#[arg(long, num_args = 0..=1, default_missing_value = "")]
pub remote: Option<String>,
#[arg(long = "ref")]
pub git_ref: Option<String>,
#[arg(short = 'n', long = "max-count")]
pub max_count: Option<usize>,
#[arg(long)]
pub all: bool,
#[command(flatten)]
pub hub: HubFlags,
}
#[derive(Args)]
#[command(group(ArgGroup::new("change").required(true).args(["query", "file"])))]
pub(crate) struct CommitArgs {
#[arg(short = 'm', long = "message")]
pub message: String,
#[arg(long)]
pub query: Option<String>,
#[arg(long)]
pub file: Option<PathBuf>,
#[arg(long)]
pub operation_uuid: Option<String>,
#[command(flatten)]
pub select: BranchSelect,
#[command(flatten)]
pub identity: IdentityFlags,
}
#[derive(Args)]
pub(crate) struct BranchArgs {
pub name: Option<String>,
#[arg(long)]
pub from: Option<String>,
#[arg(long)]
pub operation_uuid: Option<String>,
#[command(flatten)]
pub select: BranchSelect,
#[command(flatten)]
pub identity: IdentityFlags,
}
#[derive(Args)]
pub(crate) struct SwitchArgs {
pub reference: String,
#[arg(long)]
pub operation_uuid: Option<String>,
}
#[derive(Args)]
pub(crate) struct TagArgs {
pub name: Option<String>,
pub version: Option<String>,
#[arg(short = 'd', long = "delete", conflicts_with_all = ["name", "version"])]
pub delete: Option<String>,
#[arg(long)]
pub operation_uuid: Option<String>,
#[command(flatten)]
pub select: BranchSelect,
}
#[derive(Args)]
pub(crate) struct PushArgs {
pub repository: Option<String>,
#[arg(long = "ref")]
pub git_ref: Option<String>,
#[arg(long)]
pub rewrite: bool,
#[arg(long)]
pub prune: bool,
#[arg(long)]
pub operation_uuid: Option<String>,
#[arg(long)]
pub staging_directory: Option<PathBuf>,
#[command(flatten)]
pub select: BranchSelect,
#[command(flatten)]
pub hub: HubFlags,
}
#[derive(Args)]
pub(crate) struct PullArgs {
pub repository: Option<String>,
#[arg(long = "ref")]
pub git_ref: Option<String>,
#[arg(long)]
pub operation_uuid: Option<String>,
#[command(flatten)]
pub select: BranchSelect,
#[command(flatten)]
pub identity: IdentityFlags,
#[command(flatten)]
pub hub: HubFlags,
}
pub(crate) use local::run_local;
pub(crate) use remote::run_remote;
pub(crate) fn resolve_branch(
registry: &ResearchRegistry,
flag: Option<&str>,
) -> Result<Uuid, GfError> {
if let Some(reference) = flag {
let mut named = registry
.branches
.iter()
.filter(|(_, record)| record.label == reference);
let (uuid, _) = named
.next()
.ok_or_else(|| GfError::Validation(format!("no Branch is labelled '{reference}'")))?;
return if named.next().is_some() {
Err(GfError::Validation(format!(
"more than one Branch is labelled '{reference}'"
)))
} else {
Ok(*uuid)
};
}
if let Some(current) = registry
.current_branch
.filter(|uuid| registry.branches.contains_key(uuid))
{
return Ok(current);
}
let mut all = registry.branches.keys();
match (all.next(), all.next()) {
(Some(only), None) => Ok(*only),
_ => Err(GfError::Validation(
"GF_RESEARCH_BRANCH_UNSELECTED: no Branch is selected; run `gf switch <ref>`".into(),
)),
}
}
pub(crate) fn resolve_version(registry: &ResearchRegistry, text: &str) -> Result<Uuid, GfError> {
let version = match registry.tags.get(text) {
Some(tagged) => *tagged,
None => Uuid::parse_str(text).map_err(|_| {
GfError::Validation(format!("'{text}' is neither a tag nor a Version UUID"))
})?,
};
if registry.identities.contains_key(&version) {
Ok(version)
} else {
Err(GfError::Validation(format!(
"'{text}' names a Version this Project does not know"
)))
}
}
pub(crate) fn operation_uuid(given: Option<&str>) -> Result<Uuid, GfError> {
let Some(text) = given else {
return Ok(Uuid::now_v7());
};
let uuid = Uuid::parse_str(text)
.map_err(|_| GfError::Validation("operation UUID is invalid".into()))?;
if uuid.get_version_num() != 7 {
return Err(GfError::Validation(
"an operation UUID must be a UUIDv7".into(),
));
}
Ok(uuid)
}
pub(crate) fn report_operation(
given: Option<&str>,
json_output: bool,
output: &mut dyn Write,
) -> Result<Uuid, GfError> {
let operation = operation_uuid(given)?;
if !json_output {
writeln!(output, "Operation UUID: {operation}")
.and_then(|()| output.flush())
.map_err(|error| GfError::Execution(error.to_string()))?;
}
Ok(operation)
}
pub(crate) fn created_at(operation: Uuid) -> i64 {
operation.get_timestamp().map_or(0, |timestamp| {
let (seconds, nanos) = timestamp.to_unix();
i64::try_from(seconds).unwrap_or(i64::MAX / 2_000_000) * 1_000_000
+ i64::from(nanos / 1_000)
})
}
pub(crate) fn intent_digest(kind: &str, fields: &Value) -> [u8; 32] {
use sha2::Digest as _;
let mut digest = sha2::Sha256::new();
digest.update(b"graphforge-porcelain-intent/1");
digest.update(kind.as_bytes());
digest.update(fields.to_string().as_bytes());
digest.finalize().into()
}
pub(crate) fn hex(bytes: &[u8]) -> String {
use std::fmt::Write as _;
bytes.iter().fold(String::new(), |mut text, byte| {
let _ = write!(text, "{byte:02x}");
text
})
}
pub(crate) fn bound_uuid(operation: Uuid, role: &str, intent: &[u8; 32]) -> Uuid {
derived_uuid(operation, &format!("{role}/{}", hex(intent)))
}
pub(crate) fn idempotency_conflict() -> GfError {
GfError::Project {
code: graphforge_api::ProjectErrorCode::TransactionConflict,
message: "operation identity has conflicting request content".into(),
}
}
pub(crate) fn derived_uuid(operation: Uuid, role: &str) -> Uuid {
use sha2::Digest as _;
let mut digest = sha2::Sha256::new();
digest.update(b"graphforge-porcelain/1");
digest.update(operation.as_bytes());
digest.update(role.as_bytes());
let bytes: [u8; 32] = digest.finalize().into();
let mut first = [0_u8; 16];
first.copy_from_slice(&bytes[..16]);
uuid::Builder::from_custom_bytes(first).into_uuid()
}
pub(crate) fn emit(
output: &mut dyn Write,
json_output: bool,
value: &Value,
human: &str,
) -> Result<(), GfError> {
let io = |error: std::io::Error| GfError::Execution(error.to_string());
if json_output {
serde_json::to_writer(&mut *output, value)
.map_err(|error| GfError::Execution(error.to_string()))?;
writeln!(output).map_err(io)
} else {
writeln!(output, "{human}").map_err(io)
}
}
pub(crate) fn short(uuid: &impl std::fmt::Display) -> String {
uuid.to_string().chars().take(8).collect()
}
pub(crate) fn receipt_json(
receipt: &graphforge_api::ResearchOperationReceipt,
replayed: bool,
) -> Value {
json!({
"operation_uuid": receipt.operation_uuid,
"generation_uuid": receipt.generation_uuid,
"version_uuid": receipt.version_uuid,
"replayed": replayed,
})
}