use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
pub const PROJECT_COLUMNS: &[(&str, &str)] = &[
("backlog", "Backlog"),
("in_progress", "In Progress"),
("review", "Review"),
("done", "Done"),
];
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct ForgeStore {
pub next_id: u64,
pub issues: Vec<ForgeIssue>,
#[serde(default)]
pub pr_comments: Vec<PrComment>,
#[serde(default)]
pub next_card_id: u64,
#[serde(default)]
pub project_cards: Vec<ProjectCard>,
#[serde(default)]
pub wiki_pages: Vec<WikiPage>,
#[serde(default)]
pub next_run_id: u64,
#[serde(default)]
pub workflow_runs: Vec<WorkflowRun>,
#[serde(default)]
pub users: Vec<UserAccount>,
#[serde(default)]
pub sessions: Vec<SessionRecord>,
#[serde(default)]
pub next_pat_id: u64,
#[serde(default)]
pub pats: Vec<PatRecord>,
#[serde(default)]
pub device_codes: Vec<DeviceCodeRecord>,
#[serde(default)]
pub next_pr_number: u64,
#[serde(default)]
pub pull_requests: Vec<PullRequestRecord>,
#[serde(default)]
pub next_release_id: u64,
#[serde(default)]
pub releases: Vec<ReleaseRecord>,
#[serde(default)]
pub next_webhook_id: u64,
#[serde(default)]
pub webhooks: Vec<WebhookRecord>,
#[serde(default)]
pub webhook_deliveries: Vec<WebhookDelivery>,
#[serde(default)]
pub branch_rules: Vec<BranchRule>,
#[serde(default)]
pub pr_reviews: Vec<PrReviewVerdict>,
#[serde(default)]
pub visibility: String,
#[serde(default)]
pub org_name: Option<String>,
#[serde(default)]
pub collaborators: Vec<String>,
#[serde(default)]
pub watchers: Vec<String>,
#[serde(default)]
pub read_notifications: Vec<String>,
#[serde(default)]
pub audit_log: Vec<AuditEntry>,
#[serde(default)]
pub action_artifacts: Vec<ActionArtifact>,
#[serde(default)]
pub action_secrets: BTreeMap<String, String>,
#[serde(default)]
pub archived: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AuditEntry {
pub id: u64,
pub actor: String,
pub action: String,
pub target: String,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ActionArtifact {
pub run_id: u64,
pub name: String,
pub sha256: String,
pub size_bytes: usize,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PrReviewVerdict {
pub id: u64,
pub branch: String,
pub author: String,
pub state: String,
pub body: String,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ForgeIssue {
pub id: u64,
pub title: String,
pub body: String,
pub state: String,
pub author: String,
pub created_at: i64,
#[serde(default)]
pub labels: Vec<String>,
#[serde(default)]
pub assignee: Option<String>,
#[serde(default)]
pub comments: Vec<ForgeComment>,
#[serde(default)]
pub reactions: BTreeMap<String, Vec<String>>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ForgeComment {
pub author: String,
pub body: String,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PrComment {
pub branch: String,
pub author: String,
pub body: String,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ProjectCard {
pub id: u64,
pub title: String,
pub column: String,
#[serde(default)]
pub issue_id: Option<u64>,
#[serde(default)]
pub assignee: Option<String>,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WikiPage {
pub slug: String,
pub title: String,
pub body: String,
pub author: String,
pub updated_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WorkflowRun {
pub id: u64,
pub workflow: String,
pub status: String,
pub exit_code: i32,
pub log: String,
pub started_at: i64,
pub finished_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UserAccount {
pub username: String,
pub password_hash: String,
pub role: String,
#[serde(default)]
pub ssh_keys: Vec<SshKeyRecord>,
pub created_at: i64,
#[serde(default)]
pub totp_secret_b32: Option<String>,
#[serde(default)]
pub recovery_codes: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SshKeyRecord {
pub title: String,
pub public_key: String,
pub added_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SessionRecord {
pub token: String,
pub username: String,
pub csrf_token: String,
pub expires_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PatRecord {
pub id: u64,
pub username: String,
pub name: String,
pub token_hash: String,
pub prefix: String,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeviceCodeRecord {
pub device_code: String,
pub user_code: String,
#[serde(default)]
pub approved_user: Option<String>,
pub expires_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PullRequestRecord {
pub number: u64,
pub title: String,
pub body: String,
pub head_branch: String,
pub base_branch: String,
#[serde(default)]
pub draft: bool,
pub state: String,
pub author: String,
pub created_at: i64,
#[serde(default)]
pub inline_comments: Vec<InlineComment>,
#[serde(default)]
pub reviewers: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct InlineComment {
pub id: u64,
pub path: String,
pub line: usize,
pub author: String,
pub body: String,
#[serde(default)]
pub resolved: bool,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ReleaseRecord {
pub id: u64,
pub tag: String,
pub title: String,
pub notes: String,
#[serde(default)]
pub draft: bool,
#[serde(default)]
pub prerelease: bool,
pub author: String,
pub created_at: i64,
#[serde(default)]
pub assets: Vec<ReleaseAsset>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ReleaseAsset {
pub name: String,
pub size: u64,
pub sha256: String,
pub uploaded_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WebhookRecord {
pub id: u64,
pub url: String,
pub secret: String,
#[serde(default)]
pub events: Vec<String>,
#[serde(default)]
pub active: bool,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WebhookDelivery {
pub id: u64,
pub webhook_id: u64,
pub event: String,
pub status: u16,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BranchRule {
pub pattern: String,
#[serde(default)]
pub require_pr: bool,
#[serde(default)]
pub block_force_push: bool,
#[serde(default)]
pub block_delete: bool,
#[serde(default)]
pub required_reviews: u32,
}
fn store_path(git_dir: &Path) -> PathBuf {
git_dir.join("arks-forge").join("store.json")
}
pub fn now_unix() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
pub fn sanitize_slug(input: &str) -> String {
let mut out = String::with_capacity(input.len());
let mut prev_dash = false;
for ch in input.trim().chars() {
let c = ch.to_ascii_lowercase();
if c.is_ascii_alphanumeric() {
out.push(c);
prev_dash = false;
} else if (c == '-' || c == '_' || c == ' ') && !prev_dash && !out.is_empty() {
out.push('-');
prev_dash = true;
}
}
out.trim_end_matches('-').to_string()
}
pub fn parse_labels_csv(raw: &str) -> Vec<String> {
let mut out = Vec::new();
for part in raw.split(',') {
let trimmed = part.trim();
if !trimmed.is_empty() && !out.iter().any(|existing: &String| existing == trimmed) {
out.push(trimmed.to_string());
}
}
out
}
pub fn is_valid_project_column(col: &str) -> bool {
PROJECT_COLUMNS.iter().any(|(key, _)| *key == col)
}
fn store_mutex(git_dir: &Path) -> std::sync::Arc<std::sync::Mutex<()>> {
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};
static LOCKS: OnceLock<Mutex<HashMap<PathBuf, Arc<Mutex<()>>>>> = OnceLock::new();
let map_lock = LOCKS.get_or_init(|| Mutex::new(HashMap::new()));
let key = store_path(git_dir);
let mut map = map_lock.lock().unwrap_or_else(|e| e.into_inner());
map.entry(key)
.or_insert_with(|| Arc::new(Mutex::new(())))
.clone()
}
impl ForgeStore {
pub fn load(git_dir: &Path) -> Self {
let lock = store_mutex(git_dir);
let _guard = lock.lock().unwrap_or_else(|e| e.into_inner());
let path = store_path(git_dir);
let Ok(raw) = fs::read_to_string(&path) else {
return Self {
next_id: 1,
next_card_id: 1,
next_run_id: 1,
..Self::default()
};
};
let mut s: Self = serde_json::from_str(&raw).unwrap_or_default();
if s.next_id == 0 {
s.next_id = s.issues.iter().map(|i| i.id).max().unwrap_or(0) + 1;
}
if s.next_card_id == 0 {
s.next_card_id = s.project_cards.iter().map(|c| c.id).max().unwrap_or(0) + 1;
}
if s.next_run_id == 0 {
s.next_run_id = s.workflow_runs.iter().map(|r| r.id).max().unwrap_or(0) + 1;
}
s
}
pub fn save(&self, git_dir: &Path) -> std::io::Result<()> {
use std::sync::atomic::{AtomicU64, Ordering};
static SAVE_SEQ: AtomicU64 = AtomicU64::new(1);
let lock = store_mutex(git_dir);
let _guard = lock.lock().unwrap_or_else(|e| e.into_inner());
let path = store_path(git_dir);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let seq = SAVE_SEQ.fetch_add(1, Ordering::Relaxed);
let tmp = path.with_extension(format!("json.{}.{seq}.tmp", std::process::id()));
let data = serde_json::to_vec_pretty(self)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
fs::write(&tmp, data)?;
fs::rename(&tmp, &path)?;
Ok(())
}
pub fn create_issue(
&mut self,
title: String,
body: String,
author: String,
labels: Vec<String>,
assignee: Option<String>,
) -> u64 {
let id = self.next_id.max(1);
self.next_id = id + 1;
self.issues.push(ForgeIssue {
id,
title,
body,
state: "open".into(),
author,
created_at: now_unix(),
labels,
assignee,
comments: Vec::new(),
reactions: BTreeMap::new(),
});
id
}
pub fn update_issue_meta(
&mut self,
id: u64,
labels: Vec<String>,
assignee: Option<String>,
) -> bool {
let Some(issue) = self.issues.iter_mut().find(|i| i.id == id) else {
return false;
};
issue.labels = labels;
issue.assignee = assignee;
true
}
pub fn add_issue_comment(&mut self, id: u64, author: String, body: String) -> bool {
let Some(issue) = self.issues.iter_mut().find(|i| i.id == id) else {
return false;
};
issue.comments.push(ForgeComment {
author,
body,
created_at: now_unix(),
});
true
}
pub fn toggle_issue_state(&mut self, id: u64) -> Option<&str> {
let issue = self.issues.iter_mut().find(|i| i.id == id)?;
issue.state = if issue.state == "open" {
"closed".into()
} else {
"open".into()
};
Some(issue.state.as_str())
}
pub fn add_pr_comment(&mut self, branch: String, author: String, body: String) {
self.pr_comments.push(PrComment {
branch,
author,
body,
created_at: now_unix(),
});
}
pub fn create_card(
&mut self,
title: String,
column: String,
issue_id: Option<u64>,
assignee: Option<String>,
) -> u64 {
let id = self.next_card_id.max(1);
self.next_card_id = id + 1;
let col = if is_valid_project_column(&column) {
column
} else {
"backlog".to_string()
};
self.project_cards.push(ProjectCard {
id,
title,
column: col,
issue_id,
assignee,
created_at: now_unix(),
});
id
}
pub fn move_card(&mut self, id: u64, column: &str) -> bool {
if !is_valid_project_column(column) {
return false;
}
let Some(card) = self.project_cards.iter_mut().find(|c| c.id == id) else {
return false;
};
card.column = column.to_string();
true
}
pub fn delete_card(&mut self, id: u64) -> bool {
let before = self.project_cards.len();
self.project_cards.retain(|c| c.id != id);
self.project_cards.len() < before
}
pub fn upsert_wiki_page(
&mut self,
slug: String,
title: String,
body: String,
author: String,
) -> String {
let clean_slug = sanitize_slug(if slug.is_empty() { &title } else { &slug });
let final_slug = if clean_slug.is_empty() {
"home".to_string()
} else {
clean_slug
};
let now = now_unix();
if let Some(existing) = self.wiki_pages.iter_mut().find(|p| p.slug == final_slug) {
existing.title = title;
existing.body = body;
existing.author = author;
existing.updated_at = now;
} else {
self.wiki_pages.push(WikiPage {
slug: final_slug.clone(),
title,
body,
author,
updated_at: now,
});
}
final_slug
}
pub fn delete_wiki_page(&mut self, slug: &str) -> bool {
let before = self.wiki_pages.len();
self.wiki_pages.retain(|p| p.slug != slug);
self.wiki_pages.len() < before
}
#[allow(dead_code)]
pub fn record_workflow_run(
&mut self,
workflow: String,
status: String,
exit_code: i32,
log: String,
started_at: i64,
finished_at: i64,
) -> u64 {
let id = self.next_run_id.max(1);
self.next_run_id = id + 1;
self.workflow_runs.push(WorkflowRun {
id,
workflow,
status,
exit_code,
log,
started_at,
finished_at,
});
id
}
}
pub fn parse_form_urlencoded(body: &[u8]) -> BTreeMap<String, String> {
let text = String::from_utf8_lossy(body);
let mut map = BTreeMap::new();
for pair in text.split('&') {
if let Some((k, v)) = pair.split_once('=') {
map.insert(percent_decode(k), percent_decode(v));
}
}
map
}
fn percent_decode(input: &str) -> String {
let mut bytes = Vec::with_capacity(input.len());
let raw = input.as_bytes();
let mut i = 0;
while i < raw.len() {
if raw[i] == b'+' {
bytes.push(b' ');
i += 1;
} else if raw[i] == b'%' && i + 2 < raw.len() {
if let Ok(val) = u8::from_str_radix(&input[i + 1..i + 3], 16) {
bytes.push(val);
i += 3;
continue;
}
bytes.push(b'%');
i += 1;
} else {
bytes.push(raw[i]);
i += 1;
}
}
String::from_utf8_lossy(&bytes).into_owned()
}