use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use crate::cli::fail_return;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct Identity {
#[serde(default = "default_version")]
pub version: String,
pub actor_id: String,
#[serde(default = "default_actor_type")]
pub actor_type: String,
pub key_path: String,
pub pubkey: String,
}
fn default_version() -> String {
"1.0".to_string()
}
fn default_actor_type() -> String {
"human".to_string()
}
pub(crate) fn vela_home() -> PathBuf {
let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
PathBuf::from(home).join(".vela")
}
pub(crate) fn identity_path() -> PathBuf {
vela_home().join("identity.json")
}
pub(crate) fn load_identity() -> Option<Identity> {
let path = identity_path();
let text = std::fs::read_to_string(&path).ok()?;
serde_json::from_str(&text).ok()
}
pub(crate) fn save_identity(identity: &Identity) -> Result<(), String> {
let dir = vela_home();
std::fs::create_dir_all(&dir).map_err(|e| format!("create {}: {e}", dir.display()))?;
let path = identity_path();
let json =
serde_json::to_string_pretty(identity).map_err(|e| format!("serialize identity: {e}"))?;
let temporary = path.with_extension(format!("json.tmp-{}", std::process::id()));
std::fs::write(&temporary, format!("{json}\n"))
.map_err(|e| format!("write {}: {e}", temporary.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&temporary, std::fs::Permissions::from_mode(0o600))
.map_err(|e| format!("protect {}: {e}", temporary.display()))?;
}
std::fs::rename(&temporary, &path).map_err(|e| format!("install {}: {e}", path.display()))
}
const SETUP_HINT: &str = "no identity configured — run `vela id create --handle <your-name>` once \
(generates a key, stores it, prints the line a maintainer runs to register you)";
pub(crate) fn resolve_actor(flag: Option<&str>) -> String {
if let Some(a) = flag.filter(|s| !s.trim().is_empty()) {
return a.to_string();
}
if let Ok(a) = std::env::var("VELA_ACTOR_ID")
&& !a.trim().is_empty()
{
return a;
}
match load_identity() {
Some(id) => id.actor_id,
None => fail_return(SETUP_HINT),
}
}