use std::path::Path;
use crate::assignee::git_identity;
use crate::board_store::BoardStore;
use crate::config::{Config, PlanningConfig, PlanningCycle, Team, starter_board};
use crate::error::{Result, TixError};
use crate::planning::Planner;
pub fn run(cwd: &Path) -> Result<()> {
let path = cwd.join("tix.toml");
if path.exists() {
return Err(TixError::Config(format!(
"{} already exists — refusing to overwrite (delete it first if you want to re-init)",
path.display()
)));
}
let mut config = Config::starter();
seed_planning(&mut config);
seed_board(cwd)?;
write_init_config(&config, &path)?;
seed_milestone(cwd)?;
seed_gitignore(cwd)?;
println!("Created {}", path.display());
Ok(())
}
const GITIGNORE_START: &str = "# tix:start";
const GITIGNORE_END: &str = "# tix:end";
fn seed_gitignore(cwd: &Path) -> Result<()> {
let path = cwd.join(".gitignore");
let block = format!("{GITIGNORE_START}\n*.tixbak\n*.md.bak\n{GITIGNORE_END}");
let existing = std::fs::read_to_string(&path).unwrap_or_default();
let updated = crate::commands::upsert_block(&existing, &block, GITIGNORE_START, GITIGNORE_END);
if updated == existing {
return Ok(());
}
crate::commands::atomic_write(&path, &updated)?;
println!("Updated {}", path.display());
Ok(())
}
fn seed_board(cwd: &Path) -> Result<()> {
let store = BoardStore::new(cwd);
if store.dir().join("default.md").exists() {
return Ok(());
}
store.save(
"default",
&starter_board(),
Some("Only cards whose ordering differs from the default are listed in `card_order`."),
)
}
fn write_init_config(config: &Config, path: &Path) -> Result<()> {
let dir = match path.parent() {
Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
_ => Path::new(".").to_path_buf(),
};
std::fs::create_dir_all(&dir)?;
let mut disk = config.clone();
disk.kanban = crate::config::KanbanSection::default();
let mut contents = toml::to_string_pretty(&disk)
.map_err(|e| TixError::Config(format!("cannot serialize tix.toml: {e}")))?;
contents.push_str(
"\n# Optional TUI overrides; all other actions keep their defaults.\n# See docs/key-bindings.md for the complete reference.\n# [keybindings.board]\n# new_issue = [\"ctrl+n\"]\n",
);
contents.push_str(
"\n# Optional new-issue templates for the F4 New Issue mode; selecting one\n\
# pre-fills the form. Every field is optional; the title stays required.\n\
# See docs/for-users/new-issue.md.\n\
# [templates.bug]\n\
# labels = [\"bug\"]\n\
# body = \"## Steps to reproduce\\n\\n## Expected\\n\"\n",
);
contents.push_str(
"\n# Frontmatter keys this project uses on purpose. An undeclared key is\n\
# preserved on write but `tix lint` warns about it (usually a typo);\n\
# declaring it here once stops the warning. Top-level names only.\n\
# [custom_attributes]\n\
# keys = [\"build_id\", \"reviewed_by\"]\n",
);
contents.push_str(
"\n# Configurable on-disk issue layout, relative to issues_dir. Directory\n\
# tokens: {assignee} {type} {status} {priority} {cycle} {milestone}.\n\
# Filename tokens: {date} {slug} {number} {title}. Defaults shown.\n\
# `move_on_change` relocates a file when a templated value changes.\n\
# Inspect with `tix layout show`; relocate with `tix layout migrate`.\n\
# [layout]\n\
# directory = \"{assignee}/{type}/{status}\"\n\
# filename = \"{date}-{slug}.md\"\n\
# move_on_change = true\n",
);
let file_name = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("tix.toml");
let tmp = dir.join(format!("{file_name}.tmp-{}", std::process::id()));
let write_result = (|| -> std::io::Result<()> {
let mut f = std::fs::File::create(&tmp)?;
use std::io::Write;
f.write_all(contents.as_bytes())?;
f.sync_all()?;
Ok(())
})();
if let Err(e) = write_result {
let _ = std::fs::remove_file(&tmp);
return Err(TixError::Io(e));
}
if let Err(e) = std::fs::rename(&tmp, path) {
let _ = std::fs::remove_file(&tmp);
return Err(TixError::Io(e));
}
Ok(())
}
fn seed_planning(config: &mut Config) {
config.milestones_dir = Some("docs/milestones".into());
config.planning = PlanningConfig {
default_cycle: Some(crate::cycle_store::DEFAULT_CYCLE_NAME.into()),
default_milestone: Some("Backlog".into()),
default_team: None,
..PlanningConfig::default()
};
config.cycles.insert(
crate::cycle_store::DEFAULT_CYCLE_NAME.into(),
PlanningCycle::default(),
);
if let Some(identity) = git_identity() {
config.teams.insert(
"default".into(),
Team {
members: vec![identity.to_string()],
},
);
config.planning.default_team = Some("default".into());
}
}
fn seed_milestone(cwd: &Path) -> Result<()> {
let planner = Planner::from_config(Config::default(), cwd.to_path_buf());
match planner.create_milestone_file(
"Backlog",
None,
Some("Default milestone for unscheduled work"),
) {
Ok(_) => Ok(()),
Err(TixError::InvalidInput(_)) => Ok(()),
Err(e) => Err(e),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::TempDir;
#[test]
fn seed_gitignore_creates_the_block_and_keeps_other_rules() {
let tmp = TempDir::new().unwrap();
let path = tmp.path().join(".gitignore");
fs::write(&path, "/target\nnode_modules\n").unwrap();
seed_gitignore(tmp.path()).unwrap();
let first = fs::read_to_string(&path).unwrap();
assert!(
first.contains("# tix:start\n*.tixbak\n*.md.bak\n# tix:end"),
"the marked block is written: {first}"
);
assert!(
first.contains("/target\nnode_modules"),
"unrelated rules are kept: {first}"
);
seed_gitignore(tmp.path()).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), first);
}
#[test]
fn seed_gitignore_replaces_a_stale_block_in_place() {
let tmp = TempDir::new().unwrap();
let path = tmp.path().join(".gitignore");
fs::write(&path, "keep\n# tix:start\nold-rule\n# tix:end\ntail\n").unwrap();
seed_gitignore(tmp.path()).unwrap();
let got = fs::read_to_string(&path).unwrap();
assert!(
got.contains("# tix:start\n*.tixbak\n*.md.bak\n# tix:end"),
"the block is refreshed: {got}"
);
assert!(!got.contains("old-rule"), "the stale rule is gone: {got}");
assert!(
got.contains("keep") && got.contains("tail"),
"text around the block survives: {got}"
);
}
}