use std::path::Path;
use crate::store::{MergeSide, Store, merge_files};
use super::git;
use super::{Error, NETWORK_TIMEOUT};
pub(super) const DEFAULT_BRANCH: &str = "main";
pub(super) fn board_store(repo: &Path) -> Store {
Store::new(repo.join("todos.json"))
}
pub(super) fn ensure_repo(repo: &Path, remote: Option<&str>) -> Result<(), Error> {
if repo.join(".git").exists() {
return reconcile(repo, remote);
}
let Some(url) = remote else {
return Ok(());
};
std::fs::create_dir_all(repo).map_err(|err| Error::io(err.to_string()))?;
if is_empty_dir(repo) {
clone(url, repo)?;
return adopt_clone(repo, url);
}
graft(repo, url)
}
fn reconcile(repo: &Path, remote: Option<&str>) -> Result<(), Error> {
ensure_gitignore(repo)?;
let Some(url) = remote else {
return Ok(());
};
set_origin(repo, url)?;
if !is_settled(repo, url)
&& let Ok(branch) = remote_default_branch_result(url)
{
if let Some(branch) = branch {
name_branch(repo, &branch)?;
}
mark_settled(repo, url)?;
}
Ok(())
}
fn adopt_clone(repo: &Path, url: &str) -> Result<(), Error> {
settle_head(repo, &target_branch(url))?;
ensure_gitignore(repo)?;
mark_settled(repo, url)
}
pub(super) struct RemoteTip {
pub fetched: bool,
pub board: Option<Vec<u8>>,
}
pub(super) fn fetch_remote_tip(repo: &Path, branch: &str) -> Result<RemoteTip, Error> {
let named = format!("+refs/heads/{branch}:refs/tasu/remote");
let mut cmd = git::in_repo(repo, &["fetch", "--quiet", "origin", &named]);
if let Err(err) = git::bounded(&mut cmd, NETWORK_TIMEOUT) {
let mut head = git::in_repo(
repo,
&["fetch", "--quiet", "origin", "+HEAD:refs/tasu/remote"],
);
if git::bounded(&mut head, NETWORK_TIMEOUT).is_err() {
return Err(err);
}
}
let board = git::bytes(repo, &["show", "refs/tasu/remote:todos.json"]);
Ok(RemoteTip {
fetched: true,
board,
})
}
fn graft(repo: &Path, url: &str) -> Result<(), Error> {
let branch = target_branch(url);
git::run(repo, &["init", "-q"])?;
name_branch(repo, &branch)?;
set_origin(repo, url)?;
let tip = fetch_remote_tip(repo, &branch).unwrap_or(RemoteTip {
fetched: false,
board: None,
});
let remote_board = tip.board;
let local_board = board_store(repo)
.read_bytes()
.map_err(|err| Error::io(format!("could not read the local board: {err}")))?;
let board = match (local_board, remote_board) {
(Some(local), Some(remote)) => Some(
merge_files(&local, &remote)
.map_err(|side| Error::io(unreadable_board(side, "local", "remote")))?,
),
(board, None) => board,
(None, board) => board,
};
if tip.fetched {
git::run(repo, &["reset", "--hard", "refs/tasu/remote"])?;
}
if let Some(bytes) = board.filter(|bytes| !bytes.is_empty()) {
board_store(repo)
.write_bytes(&bytes)
.map_err(|err| Error::io(err.to_string()))?;
}
commit_all(repo, "tasu: local")?;
mark_settled(repo, url)
}
fn is_empty_dir(repo: &Path) -> bool {
std::fs::read_dir(repo)
.map(|mut entries| entries.next().is_none())
.unwrap_or(false)
}
fn clone(url: &str, repo: &Path) -> Result<(), Error> {
let mut cmd = git::program();
cmd.args(["clone", "--quiet", url]).arg(repo);
git::bounded(&mut cmd, NETWORK_TIMEOUT).map(|_| ())
}
pub(super) fn commit_all(repo: &Path, message: &str) -> Result<(), Error> {
ensure_gitignore(repo)?;
git::run(repo, &["add", "-A"])?;
if git::ok(repo, &["diff", "--cached", "--quiet"]) {
return Ok(());
}
git::run(
repo,
&[
"-c",
"user.name=tasu",
"-c",
"user.email=tasu@localhost",
"commit",
"--quiet",
"-m",
message,
],
)
}
fn set_origin(repo: &Path, url: &str) -> Result<(), Error> {
git::run(repo, &["remote", "set-url", "origin", url])
.or_else(|_| git::run(repo, &["remote", "add", "origin", url]))
}
fn target_branch(remote: &str) -> String {
remote_default_branch_result(remote)
.ok()
.flatten()
.unwrap_or_else(|| DEFAULT_BRANCH.to_string())
}
fn remote_default_branch_result(remote: &str) -> Result<Option<String>, Error> {
let mut cmd = git::program();
cmd.args(["ls-remote", "--symref", remote, "HEAD"]);
let output = git::bounded(&mut cmd, NETWORK_TIMEOUT)?;
Ok(output.lines().find_map(|line| {
let name = line
.strip_prefix("ref:")?
.trim()
.strip_prefix("refs/heads/")?;
name.split_whitespace().next().map(str::to_string)
}))
}
fn mark_settled(repo: &Path, url: &str) -> Result<(), Error> {
git::run(repo, &["config", "tasu.remote", url])
}
pub(super) fn is_settled(repo: &Path, url: &str) -> bool {
git::text(repo, &["config", "--get", "tasu.remote"]).as_deref() == Some(url)
}
pub(super) fn current_branch(repo: &Path) -> Option<String> {
let output = git::in_repo(repo, &["symbolic-ref", "--short", "-q", "HEAD"])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
(!name.is_empty()).then_some(name)
}
fn settle_head(repo: &Path, target: &str) -> Result<(), Error> {
if git::ok(repo, &["rev-parse", "--verify", "--quiet", "HEAD"]) {
return name_branch(repo, target);
}
if git::ok(
repo,
&[
"show-ref",
"--verify",
"--quiet",
&format!("refs/remotes/origin/{target}"),
],
) {
git::run(repo, &["checkout", "--quiet", target])
} else if let Some(branch) = first_remote_branch(repo) {
git::run(repo, &["checkout", "--quiet", &branch])
} else {
name_branch(repo, target)
}
}
fn first_remote_branch(repo: &Path) -> Option<String> {
let output = git::in_repo(
repo,
&[
"for-each-ref",
"--format=%(refname:short)",
"refs/remotes/origin/",
],
)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8_lossy(&output.stdout)
.lines()
.map(str::trim)
.filter(|name| !name.is_empty() && *name != "origin/HEAD")
.filter_map(|name| name.strip_prefix("origin/"))
.map(str::to_string)
.next()
}
pub(super) fn name_branch(repo: &Path, target: &str) -> Result<(), Error> {
let Some(current) = current_branch(repo) else {
return point_head(repo, target);
};
if current == target {
return Ok(());
}
if !git::ok(repo, &["rev-parse", "--verify", "--quiet", "HEAD"]) {
return point_head(repo, target);
}
git::run(repo, &["branch", "-m", target])
.or_else(|_| git::run(repo, &["checkout", "--quiet", target]))
}
fn unreadable_board(side: MergeSide, base: &str, other: &str) -> String {
let name = match side {
MergeSide::Base => base,
MergeSide::Other => other,
};
format!("{name} board could not be read; sync stopped to avoid dropping tasks")
}
fn point_head(repo: &Path, target: &str) -> Result<(), Error> {
git::run(
repo,
&["symbolic-ref", "HEAD", &format!("refs/heads/{target}")],
)
}
pub(super) fn ensure_gitignore(repo: &Path) -> Result<(), Error> {
let path = repo.join(".gitignore");
let mut text = match std::fs::read_to_string(&path) {
Ok(text) => text,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(err) => {
return Err(Error::io(format!(
"could not read {}: {err}",
path.display()
)));
}
};
let mut changed = false;
for entry in ["*.tmp", "*.corrupt-*"] {
if !text.lines().any(|line| line.trim() == entry) {
if !text.is_empty() && !text.ends_with('\n') {
text.push('\n');
}
text.push_str(entry);
text.push('\n');
changed = true;
}
}
if changed {
std::fs::write(&path, &text)
.map_err(|err| Error::io(format!("could not write {}: {err}", path.display())))?;
}
Ok(())
}