Skip to content

armgit / kanzo

Public Imported from GitHub
0

Self-hosted, sharable kanban for humans and agents. One 4.7 MB binary, 5 MB of RAM, 10 to 60 tokens per agent reply, starts in 3 ms, zero setup.

Sync from the board, and set up the repo there

emanuele-emaa93071b9cd1
diff --git a/README.md b/README.md
index 0cda480..7623ccf 100644
--- a/README.md
+++ b/README.md
@@ -32,7 +32,7 @@ For macOS and Linux, including every Raspberry Pi. Or build it: `cargo install -
| `kanzo` | Starts the board at http://localhost:4242 and opens it; `--port` for another port, `--no-open` to not open it |
| `kanzo service install` | Keeps the board running and starts it at login; `uninstall` removes it |
| `kanzo mcp` | The MCP server for agents: they start it, not you |
-| `kanzo sync` | Commits the board and pulls or pushes it; `--keep-local` or `--keep-remote` when both sides changed |
+| `kanzo sync` | Commits the board and pulls or pushes it; `--repo <url>` sets the repo, `--keep-local` or `--keep-remote` when both sides changed |
| `kanzo export` | Prints the board as Markdown; `-f json` for JSON, `-p <project>` for one project, `-o <file>` to save it |
| `kanzo init` | Creates the data folder; the first run does this too |
| `kanzo --version` | Prints the version |
diff --git a/src/app.js b/src/app.js
index 348a47f..fcfc626 100644
--- a/src/app.js
+++ b/src/app.js
@@ -66,6 +66,7 @@ const ICONS = {
plus: '<path d="M5 12h14M12 5v14"/>',
trash: '<path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6M10 11v6M14 11v6"/>',
check: '<path d="M20 6 9 17l-5-5"/>',
+ sync: '<path d="M12 13v8"/><path d="M4 14.9A7 7 0 1 1 15.7 8h1.8a4.5 4.5 0 0 1 2.5 8.2"/><path d="m8 17 4-4 4 4"/>',
collapse: '<path d="m13 17 5-5-5-5M6 17l5-5-5-5"/>',
expand: '<path d="m11 17-5-5 5-5M18 17l-5-5 5-5"/>',
rename: '<path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/>',
@@ -423,7 +424,7 @@ document.addEventListener("mousedown", (e) => {
// A click outside the task panel closes it. Cards are left to open their own task,
// and the project menu to do its job.
document.addEventListener("mousedown", (e) => {
- if (state.task && e.button === 0 && !e.target.closest("#panel, .card, .menu, #search-dialog")) closeTask();
+ if (state.task && e.button === 0 && !e.target.closest("#panel, .card, .menu, #search-dialog, #sync-dialog")) closeTask();
});
window.addEventListener("resize", closeMenu);
window.addEventListener("blur", closeMenu);
@@ -1066,6 +1067,109 @@ function schedulePoll() {
}
schedulePoll();
+// ---------- sync ----------
+
+// The sync button runs `kanzo sync`: it commits the board and pulls or pushes it through
+// the data folder's git remote. When both machines changed it, the board asks which to keep.
+async function syncNow(keep) {
+ const button = $("#sync");
+ button.disabled = true;
+ button.classList.add("syncing");
+ let diverged = null;
+ try {
+ const res = await fetch("/api/sync", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ keep }) });
+ const reply = await res.json().catch(() => ({}));
+ if (res.ok) { toast(reply.message); loadBoard(); }
+ else if (reply.diverged) diverged = reply;
+ else toast(reply.error || res.statusText);
+ } catch (err) { toast(err.message); }
+ button.disabled = false;
+ button.classList.remove("syncing");
+ if (diverged) chooseSide(diverged);
+}
+
+function chooseSide({ first }) {
+ const repo = repoName(syncRemote);
+ if (first) {
+ // A repo another machine already syncs with: most likely, this machine is joining it.
+ if (confirm(`${repo} already has a board. Use it on this machine?\n\nThis machine's current board is kept in kanzo.db.bak.`)) syncNow("remote");
+ else if (confirm(`Replace the board in ${repo} with this machine's board instead?`)) syncNow("local");
+ return;
+ }
+ if (confirm("This machine and another one both changed the board since the last sync, and boards can't be merged.\n\nKeep THIS machine's board, and overwrite the other one?")) syncNow("local");
+ else if (confirm("Take the other machine's board instead? This machine's board is kept in kanzo.db.bak.")) syncNow("remote");
+}
+
+// The repo the board syncs with, shown at the bottom of the sidebar; null before it's set up.
+let syncRemote = null;
+
+// "you/kanzo-data" from any of its URLs.
+function repoName(url) {
+ return (url || "").replace(/\.git$/, "").split(/[/:]/).filter(Boolean).slice(-2).join("/");
+}
+
+function showSyncRemote(remote) {
+ syncRemote = remote;
+ $("#sync-repo").hidden = !remote;
+ $("#sync-repo-name").textContent = repoName(remote);
+ $("#sync-repo").title = remote ? `Syncs with ${remote}. Click to change.` : "";
+}
+
+async function loadSyncRemote() {
+ try { showSyncRemote((await api("GET", "/sync")).remote); } catch {}
+ return syncRemote;
+}
+
+// Sync asks for a repo the first time; after that, the repo in the sidebar changes it.
+function openSyncDialog() {
+ closeMenu();
+ $("#sync-dialog").hidden = false;
+ $("#sync-title").textContent = syncRemote ? "Sync with another repo" : "Sync your board";
+ $("#sync-create").hidden = !!syncRemote;
+ $("#sync-url").value = syncRemote || "";
+ $("#sync-error").hidden = true;
+ $("#sync-url").focus();
+ $("#sync-url").select();
+}
+
+function closeSyncDialog() {
+ $("#sync-dialog").hidden = true;
+}
+
+$("#sync-form").addEventListener("submit", async (e) => {
+ e.preventDefault();
+ const save = $("#sync-save");
+ save.disabled = true;
+ save.textContent = "Checking…";
+ try {
+ const res = await fetch("/api/sync", { method: "PUT", headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ url: $("#sync-url").value }) });
+ const reply = await res.json().catch(() => ({}));
+ if (res.ok) {
+ showSyncRemote(reply.remote);
+ closeSyncDialog();
+ syncNow();
+ } else {
+ $("#sync-error").textContent = reply.error || res.statusText;
+ $("#sync-error").hidden = false;
+ }
+ } catch (err) {
+ $("#sync-error").textContent = err.message;
+ $("#sync-error").hidden = false;
+ }
+ save.disabled = false;
+ save.textContent = "Save and sync";
+});
+$("#sync-cancel").addEventListener("click", closeSyncDialog);
+$("#sync-dialog").addEventListener("mousedown", (e) => { if (e.target.id === "sync-dialog") closeSyncDialog(); });
+$("#sync-dialog").addEventListener("keydown", (e) => { if (e.key === "Escape") { e.stopPropagation(); closeSyncDialog(); } });
+
+$("#sync").addEventListener("click", async () => {
+ if (await loadSyncRemote()) syncNow();
+ else openSyncDialog();
+});
+$("#sync-repo").addEventListener("click", openSyncDialog);
+
// ---------- update ----------
// Kanzo checks GitHub for a newer release once a day and offers it at the bottom of the
@@ -1133,6 +1237,7 @@ async function installUpdate(available) {
checkUpdate();
setInterval(checkUpdate, 24 * 60 * 60 * 1000);
+loadSyncRemote();
// Relative times ("5m ago") drift; refresh them now and then.
setInterval(() => {
diff --git a/src/index.html b/src/index.html
index fbe91a6..37de09a 100644
--- a/src/index.html
+++ b/src/index.html
@@ -49,6 +49,9 @@ aside {
.brand img { width: 28px; height: 28px; margin: -4px 0; }
.brand .ghost { width: auto; margin: -6px 0 -6px auto; padding: 6px; color: var(--muted); }
.brand .ghost:hover, .brand .ghost:focus-visible { color: var(--text); }
+.brand .ghost + .ghost { margin-left: 0; }
+.syncing svg { animation: pulse 1s ease-in-out infinite; }
+@keyframes pulse { 50% { opacity: .3; } }
.nav { overflow-y: auto; flex: 1; display: flex; flex-direction: column; gap: 2px; }
.ghost, .nav a {
display: flex; align-items: center; gap: 10px; width: 100%; padding: 8px 10px; border: 0; border-radius: 10px;
@@ -106,6 +109,10 @@ aside {
.about .ghost { width: auto; margin-left: -6px; padding: 2px 6px; font-size: 12px; color: var(--faint); }
.about .ghost:hover, .about .ghost:focus-visible { color: var(--text); }
.about .ghost:disabled { cursor: default; }
+#sync-repo { display: inline-flex; align-items: center; gap: 5px; margin: 0 -6px 0 auto; min-width: 0; }
+#sync-repo[hidden] { display: none; }
+#sync-repo-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+#sync-repo .icon svg { width: 13px; height: 13px; }
form.new-project { display: flex; flex-direction: column; gap: 6px; padding: 4px 2px 10px; }
form.new-project .row { display: flex; gap: 6px; margin-top: 2px; }
@@ -309,6 +316,17 @@ header .sub a:hover { color: var(--text); }
.search-field input { flex: 1; min-width: 0; border: 0; background: none; font-size: 16px; }
.search-field input::-webkit-search-cancel-button { display: none; }
.results { overflow-y: auto; padding: 6px; }
+.sync-window {
+ width: min(520px, 100%); display: flex; flex-direction: column; gap: 12px; padding: 22px 22px 18px;
+ background: var(--menu); border: 1px solid var(--border); border-radius: 18px; box-shadow: var(--shadow);
+}
+.sync-window h2 { margin: 0; font-size: 17px; font-weight: 600; }
+.sync-window p { margin: 0; color: var(--muted); line-height: 1.45; }
+.sync-window .error { color: var(--danger); white-space: pre-line; font-size: 13px; }
+.sync-window .row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: 4px; }
+.sync-window .row a { margin-right: auto; color: var(--muted); font-size: 13px; }
+.sync-window .row a:hover { color: var(--text); }
+.sync-window .btn:disabled { opacity: .6; cursor: default; }
.results .label { color: var(--faint); font-size: 12px; padding: 8px 12px 4px; }
.results .note { color: var(--faint); padding: 14px 12px; }
.result {
@@ -320,6 +338,7 @@ header .sub a:hover { color: var(--text); }
.result .meta { flex: none; display: flex; align-items: center; gap: 8px; color: var(--faint); font-size: 12px; }
.toast {
+ white-space: pre-line; max-width: min(640px, calc(100vw - 32px));
position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); background: var(--text); color: var(--bg);
padding: 9px 16px; border-radius: 99px; z-index: 20; box-shadow: var(--shadow); font-weight: 500;
}
@@ -344,6 +363,7 @@ header .sub a:hover { color: var(--text); }
<div class="brand">
<img src="/logo.png" alt="">
Kanzo
+ <button class="ghost" id="sync" title="Sync with your other machines" aria-label="Sync"><span class="icon" data-icon="sync"></span></button>
<button class="ghost" id="search-open" title="Search (/ or ⌘K)" aria-label="Search tasks"><span class="icon" data-icon="search"></span></button>
</div>
<button class="ghost" id="new-project-toggle"><span class="icon" data-icon="newProject"></span>New project</button>
@@ -360,6 +380,7 @@ header .sub a:hover { color: var(--text); }
<button class="ghost update" id="update" hidden><span class="icon" data-icon="update"></span><span id="update-label"></span></button>
<div class="about">
<button class="ghost" id="version" title="Check for updates"></button>
+ <button class="ghost" id="sync-repo" hidden><span class="icon" data-icon="sync"></span><span id="sync-repo-name"></span></button>
</div>
</aside>
@@ -403,6 +424,19 @@ header .sub a:hover { color: var(--text); }
</div>
</div>
+<div class="search-dialog" id="sync-dialog" hidden>
+ <form class="sync-window" id="sync-form" role="dialog" aria-labelledby="sync-title">
+ <h2 id="sync-title">Sync your board</h2>
+ <p>Keep this board the same on all your machines through a private git repo you own. Use the same repo on each machine.</p>
+ <input class="field" id="sync-url" placeholder="https://github.com/you/kanzo-data" autocomplete="off" spellcheck="false" aria-label="Repository URL">
+ <p class="error" id="sync-error" hidden></p>
+ <div class="row">
+ <a id="sync-create" href="https://github.com/new?name=kanzo-data&amp;visibility=private" target="_blank" rel="noopener">Create a private repo on GitHub</a>
+ <button class="btn" type="button" id="sync-cancel">Cancel</button>
+ <button class="btn primary" type="submit" id="sync-save">Save and sync</button>
+ </div>
+ </form>
+</div>
<div class="search-dialog" id="search-dialog" hidden>
<div class="search-window" role="dialog" aria-label="Search tasks">
<label class="search-field"><span class="icon" data-icon="search"></span><input id="search" type="search" placeholder="Search tasks" autocomplete="off" spellcheck="false" aria-label="Search tasks"></label>
diff --git a/src/main.rs b/src/main.rs
index 4789d12..e74432b 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -47,6 +47,9 @@ enum Command {
},
/// Commit the data folder and pull or push it with its git remote
Sync {
+ /// Sync with this git repo from now on, like https://github.com/you/kanzo-data or you/kanzo-data
+ #[arg(long, value_name = "URL")]
+ repo: Option<String>,
/// When both sides changed, keep this machine's board and overwrite the remote
#[arg(long, conflicts_with = "keep_remote")]
keep_local: bool,
@@ -114,13 +117,17 @@ async fn run(cli: Cli) -> anyhow::Result<()> {
println!("Kanzo data folder ready at {}", home.dir.display());
Ok(())
}
- Some(Command::Sync { keep_local, keep_remote }) => {
+ Some(Command::Sync { repo, keep_local, keep_remote }) => {
+ if let Some(url) = repo {
+ println!("The board syncs with {}.", sync::set_remote(&home, &url, true)?);
+ }
let keep = match (keep_local, keep_remote) {
(true, _) => Some(sync::Keep::Local),
(_, true) => Some(sync::Keep::Remote),
_ => None,
};
- sync::sync(&home, keep)
+ println!("{}", sync::sync(&home, keep, true)?);
+ Ok(())
}
Some(Command::Export { format, project, output }) => {
export::export(&home, format, project.as_deref(), output.as_deref())
diff --git a/src/sync.rs b/src/sync.rs
index 9d6cbe5..cbfe3eb 100644
--- a/src/sync.rs
+++ b/src/sync.rs
@@ -12,23 +12,123 @@ pub enum Keep {
Remote,
}
-pub fn sync(home: &Home, keep: Option<Keep>) -> Result<()> {
+/// The error when both sides changed the board: the caller asks which one to keep.
+/// `first` when this is the first sync with that repo, which already holds a board.
+#[derive(Debug)]
+pub struct Diverged {
+ pub message: String,
+ pub first: bool,
+}
+
+impl std::fmt::Display for Diverged {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.message)
+ }
+}
+
+/// The URL of the repo the board syncs with, or `None` before it's set up.
+pub fn remote_url(home: &Home) -> Option<String> {
+ let remote = remote_name(&home.dir).ok()??;
+ git(&home.dir, false, &["remote", "get-url", &remote]).ok()
+}
+
+/// Points the board at the git repo `url`, once this machine can reach it: the first
+/// time, it makes the data folder a git repo; later, it replaces the old repo, and the
+/// next sync asks which board to keep if the new one already holds one. `owner/repo`
+/// is short for that repo on GitHub. Returns the URL saved.
+pub fn set_remote(home: &Home, url: &str, prompt: bool) -> Result<String> {
let dir = &home.dir;
+ let url = url.trim().trim_end_matches('/');
+ if url.is_empty() {
+ bail!("Paste the URL of a git repository, like https://github.com/you/kanzo-data");
+ }
+ let mut failure = String::new();
+ let mut found = None;
+ for candidate in candidates(url) {
+ match git(dir, prompt, &["ls-remote", "--symref", &candidate, "HEAD"]) {
+ Ok(out) => {
+ found = Some((candidate, out));
+ break;
+ }
+ Err(e) => failure = reason(&format!("{e:#}")),
+ }
+ }
+ let Some((url, head)) = found else {
+ bail!("Can't reach that repo. Check the URL, and that this machine can push to it.\n{failure}");
+ };
if !dir.join(".git").exists() {
- bail!(
- "{0} is not a git repo yet. Set it up once with:\n cd {0} && git init && gh repo create kanzo-data --private --source . --push",
- dir.display()
- );
+ // The repo's own branch, so this machine joins the board already there.
+ let branch =
+ head.lines().find_map(|l| l.strip_prefix("ref: refs/heads/")?.split('\t').next()).unwrap_or("main");
+ git(dir, prompt, &["init", "--quiet", "--initial-branch", branch])?;
+ }
+ if remote_url(home).as_deref() != Some(url.as_str()) {
+ // Removing the old remote forgets its branches, so the next sync starts afresh.
+ if let Some(old) = remote_name(dir)? {
+ git(dir, prompt, &["remote", "remove", &old])?;
+ }
+ git(dir, prompt, &["remote", "add", "origin", &url])?;
+ }
+ Ok(url)
+}
+
+/// The line of git's error that says what went wrong, in a few words.
+fn reason(error: &str) -> String {
+ let lines: Vec<&str> = error.lines().map(str::trim).collect();
+ if error.contains("terminal prompts disabled") {
+ return "Git asked to sign in: sign in on this machine first (`gh auth login` for GitHub), \
+ or use the repo's SSH URL."
+ .into();
+ }
+ let pick = |prefix: &str| lines.iter().find(|l| l.starts_with(prefix)).copied();
+ let line = pick("ERROR:")
+ .or_else(|| pick("Permission denied"))
+ .or_else(|| pick("Host key verification failed"))
+ .or_else(|| pick("fatal:"))
+ .unwrap_or_else(|| lines.last().copied().unwrap_or_default());
+ line.trim_start_matches("ERROR:").trim_start_matches("fatal:").trim().to_string()
+}
+
+/// The URLs `url` may mean: itself, or for `owner/repo` that repo on GitHub, by SSH and
+/// then HTTPS, as either may be the one this machine can push with.
+fn candidates(url: &str) -> Vec<String> {
+ let short = url.strip_prefix("github.com/").unwrap_or(url);
+ let shorthand = !short.contains(':')
+ && short.split('/').filter(|p| !p.is_empty()).count() == 2
+ && !short.starts_with(['.', '/', '~'])
+ && !short.contains(char::is_whitespace);
+ if !shorthand {
+ return vec![url.to_string()];
+ }
+ let repo = short.trim_end_matches(".git");
+ vec![format!("[email protected]:{repo}.git"), format!("https://github.com/{repo}.git")]
+}
+
+/// The remote the board syncs with: `origin`, or the only one there is.
+fn remote_name(dir: &Path) -> Result<Option<String>> {
+ if !dir.join(".git").exists() {
+ return Ok(None);
}
- let remotes = git(dir, &["remote"])?;
- let Some(remote) = remotes.lines().find(|r| *r == "origin").or_else(|| remotes.lines().next()) else {
+ let remotes = git(dir, false, &["remote"])?;
+ Ok(remotes.lines().find(|r| *r == "origin").or_else(|| remotes.lines().next()).map(String::from))
+}
+
+impl std::error::Error for Diverged {}
+
+/// Commits the board, then pulls or pushes it, and says what it did. With `prompt`
+/// false, as from the board's button, git never waits for a password; a missing
+/// credential fails with git's message instead.
+pub fn sync(home: &Home, keep: Option<Keep>, prompt: bool) -> Result<String> {
+ let dir = &home.dir;
+ let git = |args: &[&str]| git(dir, prompt, args);
+ let git_ok = |args: &[&str]| git_ok(dir, prompt, args);
+ let Some(remote) = remote_name(dir)? else {
bail!(
- "{} has no git remote. Add one with:\n gh repo create kanzo-data --private --source . --push",
- dir.display()
+ "Sync isn't set up yet. Create an empty private repo, on GitHub for example, then press the \
+ sync button on the board and paste its URL, or run:\n kanzo sync --repo <url>"
);
};
- let remote = remote.to_string();
- git(dir, &["fetch", "--quiet", &remote])?;
+ git(&["fetch", "--quiet", "--prune", &remote])?;
// Wait for open connections to finish and keep new ones out while the
// database is staged. The lock is held only while git reads or replaces
@@ -36,83 +136,118 @@ pub fn sync(home: &Home, keep: Option<Keep>) -> Result<()> {
{
let _lock = home.lock_exclusive()?;
crate::store::Store::open(&home.db_path(), home.config.statuses.clone(), None)?.settle()?;
- git(dir, &["add", "--all"])?;
+ git(&["add", "--all"])?;
}
- if !git_ok(dir, &["diff", "--cached", "--quiet"]) {
- git(dir, &["commit", "--quiet", "--message", &format!("kanzo sync from {}", hostname())])?;
+ if !git_ok(&["diff", "--cached", "--quiet"]) {
+ let message = format!("kanzo sync from {}", hostname());
+ // A machine where git doesn't know the user yet still syncs.
+ let named = git_ok(&["config", "user.email"]);
+ let anonymous = ["-c", "user.name=Kanzo", "-c", "user.email=kanzo@localhost"];
+ let mut args: Vec<&str> = if named { vec![] } else { anonymous.to_vec() };
+ args.extend(["commit", "--quiet", "--message", &message]);
+ git(&args)?;
}
- let branch = git(dir, &["symbolic-ref", "--short", "HEAD"])?;
- let upstream = format!("{remote}/{branch}");
- if !git_ok(dir, &["rev-parse", "--verify", "--quiet", &format!("refs/remotes/{upstream}")]) {
- // Pushing would start a second, separate board next to the one already there.
+ let mut branch = git(&["symbolic-ref", "--short", "HEAD"])?;
+ if !git_ok(&["rev-parse", "--verify", "--quiet", &format!("refs/remotes/{remote}/{branch}")]) {
let prefix = format!("{remote}/");
- let others: Vec<String> = git(dir, &["branch", "--remotes", "--format=%(refname:short)"])?
+ let others: Vec<String> = git(&["branch", "--remotes", "--format=%(refname:short)"])?
.lines()
- .filter(|b| b.starts_with(&prefix) && *b != format!("{remote}/HEAD") && *b != remote)
+ .filter_map(|b| b.strip_prefix(&prefix))
+ .filter(|b| *b != "HEAD" && !b.is_empty())
.map(String::from)
.collect();
- if !others.is_empty() {
- bail!(
- "{remote} already holds a board on {}, but this folder is on branch {branch}. \
- To use that board here, move this folder aside and `git clone` the repo in its place.",
+ match &others[..] {
+ [] => {
+ git(&["push", "--quiet", "--set-upstream", &remote, &branch])?;
+ return Ok(format!("Pushed the board to {remote}/{branch} for the first time."));
+ }
+ // The repo's board is on another branch, like master: follow it, rather than
+ // start a second board next to it.
+ [other] => {
+ git(&["branch", "--move", other])?;
+ branch = other.clone();
+ }
+ _ => bail!(
+ "{remote} has several branches ({}), and none is {branch}, so it's not clear which holds \
+ the board. Sync with an empty repo, or one used only by Kanzo.",
others.join(", ")
- );
+ ),
}
- git(dir, &["push", "--quiet", "--set-upstream", &remote, &branch])?;
- println!("Pushed the board to {upstream} for the first time.");
- return Ok(());
}
- if !git_ok(dir, &["rev-parse", "--verify", "--quiet", "@{upstream}"]) {
- git(dir, &["branch", "--quiet", "--set-upstream-to", &upstream])?;
+ let upstream = format!("{remote}/{branch}");
+ let first = !git_ok(&["rev-parse", "--verify", "--quiet", "@{upstream}"]);
+ if first {
+ git(&["branch", "--quiet", "--set-upstream-to", &upstream])?;
}
- let counts = git(dir, &["rev-list", "--left-right", "--count", "HEAD...@{upstream}"])?;
+ let counts = git(&["rev-list", "--left-right", "--count", "HEAD...@{upstream}"])?;
let (ahead, behind) = match counts.split_whitespace().collect::<Vec<_>>()[..] {
[a, b] => (a.parse::<u32>()?, b.parse::<u32>()?),
_ => bail!("unexpected git output: {counts}"),
};
- match (ahead, behind, keep) {
- (0, 0, _) => println!("Already in sync with {upstream}."),
+ Ok(match (ahead, behind, keep) {
+ (0, 0, _) => format!("Already in sync with {upstream}."),
(_, 0, _) => {
- git(dir, &["push", "--quiet"])?;
- println!("Pushed this machine's changes to {upstream}.");
+ git(&["push", "--quiet"])?;
+ format!("Pushed this machine's changes to {upstream}.")
}
(0, _, _) => {
{
let _lock = home.lock_exclusive()?;
- git(dir, &["merge", "--quiet", "--ff-only", "@{upstream}"])?;
+ git(&["merge", "--quiet", "--ff-only", "@{upstream}"])?;
}
home.store()?.migrate()?;
- println!("Pulled the latest board from {upstream}.");
+ format!("Pulled the latest board from {upstream}.")
+ }
+ (_, _, None) => {
+ let what = if first {
+ format!("{upstream} already holds a board.")
+ } else {
+ format!(
+ "This machine and {upstream} both changed the board since the last sync, and a database file can't be merged."
+ )
+ };
+ return Err(Diverged {
+ message: format!(
+ "{what} Keep one side:\n \
+ kanzo sync --keep-remote use the board in {upstream} here (this machine's is kept in kanzo.db.bak)\n \
+ kanzo sync --keep-local overwrite {upstream} with this machine's board"
+ ),
+ first,
+ }
+ .into());
}
- (_, _, None) => bail!(
- "This machine and {upstream} both changed the board since the last sync, and a database file \
- can't be merged. Keep one side:\n \
- kanzo sync --keep-local overwrite {upstream} with this machine's board\n \
- kanzo sync --keep-remote replace this machine's board with {upstream} (a copy is kept in kanzo.db.bak)"
- ),
(_, _, Some(Keep::Local)) => {
- git(dir, &["push", "--quiet", "--force-with-lease"])?;
- println!("Overwrote {upstream} with this machine's board.");
+ git(&["push", "--quiet", "--force-with-lease"])?;
+ format!("Overwrote {upstream} with this machine's board.")
}
(_, _, Some(Keep::Remote)) => {
{
let _lock = home.lock_exclusive()?;
std::fs::copy(home.db_path(), dir.join("kanzo.db.bak")).context("cannot back up kanzo.db")?;
- git(dir, &["reset", "--quiet", "--hard", "@{upstream}"])?;
+ git(&["reset", "--quiet", "--hard", "@{upstream}"])?;
}
home.store()?.migrate()?;
- println!("Took the board from {upstream}; this machine's old board is in kanzo.db.bak.");
+ format!("Took the board from {upstream}; this machine's old board is in kanzo.db.bak.")
}
+ })
+}
+
+/// Git in `dir`; without `prompt` it fails rather than ask for a password or passphrase.
+fn command(dir: &Path, prompt: bool, args: &[&str]) -> Command {
+ let mut cmd = Command::new("git");
+ cmd.arg("-C").arg(dir).args(args);
+ if !prompt {
+ cmd.env("GIT_TERMINAL_PROMPT", "0").env("GIT_SSH_COMMAND", "ssh -o BatchMode=yes");
}
- Ok(())
+ cmd
}
/// Runs git in `dir` and returns its trimmed output, or fails with git's own message.
-fn git(dir: &Path, args: &[&str]) -> Result<String> {
- let out = Command::new("git").arg("-C").arg(dir).args(args).output().context("cannot run git; is it installed?")?;
+fn git(dir: &Path, prompt: bool, args: &[&str]) -> Result<String> {
+ let out = command(dir, prompt, args).output().context("cannot run git; is it installed?")?;
if !out.status.success() {
let err = String::from_utf8_lossy(&out.stderr);
bail!("git {} failed:\n{}", args.join(" "), err.trim());
@@ -120,8 +255,8 @@ fn git(dir: &Path, args: &[&str]) -> Result<String> {
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}
-fn git_ok(dir: &Path, args: &[&str]) -> bool {
- Command::new("git").arg("-C").arg(dir).args(args).output().is_ok_and(|o| o.status.success())
+fn git_ok(dir: &Path, prompt: bool, args: &[&str]) -> bool {
+ command(dir, prompt, args).output().is_ok_and(|o| o.status.success())
}
/// The machine's name for commit messages, like "Ada's MacBook Air".
@@ -137,3 +272,35 @@ fn hostname() -> String {
};
run("scutil", &["--get", "ComputerName"]).or_else(|| run("hostname", &[])).unwrap_or_else(|| "unknown".into())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn urls() {
+ let ssh = "[email protected]:you/kanzo-data.git";
+ let https = "https://github.com/you/kanzo-data.git";
+ assert_eq!(candidates("you/kanzo-data"), [ssh, https]);
+ assert_eq!(candidates("github.com/you/kanzo-data.git"), [ssh, https]);
+ assert_eq!(candidates("https://github.com/you/kanzo-data"), ["https://github.com/you/kanzo-data"]);
+ assert_eq!(candidates(ssh), [ssh]);
+ assert_eq!(candidates("/srv/git/kanzo.git"), ["/srv/git/kanzo.git"]);
+ assert_eq!(candidates("../kanzo.git"), ["../kanzo.git"]);
+ }
+
+ #[test]
+ fn reasons() {
+ let missing = "git ls-remote failed:\nERROR: Repository not found.\nfatal: Could not read from remote repository.\n\n\
+ Please make sure you have the correct access rights\nand the repository exists.";
+ assert_eq!(reason(missing), "Repository not found.");
+ assert_eq!(
+ reason("git ls-remote failed:\nfatal: '/x' does not appear to be a git repository"),
+ "'/x' does not appear to be a git repository"
+ );
+ assert!(
+ reason("fatal: could not read Username for 'https://github.com': terminal prompts disabled")
+ .contains("gh auth login")
+ );
+ }
+}
diff --git a/src/web.rs b/src/web.rs
index f440d9d..9d53f82 100644
--- a/src/web.rs
+++ b/src/web.rs
@@ -18,7 +18,7 @@ use tokio_util::sync::CancellationToken;
use crate::home::Home;
use crate::store::{self, Error, ImagesOf, Store, TaskPatch};
-use crate::update;
+use crate::{sync, update};
const INDEX: &str = include_str!("index.html");
/// The largest image the board takes from a paste.
@@ -139,6 +139,7 @@ fn router(home: Home, guard: Guard, shutdown: CancellationToken) -> Router {
.route("/api/images/{id}", delete(delete_image))
.route("/api/tasks/{id}/images", post(attach_image))
.route("/api/update", get(update_status).post(update_now))
+ .route("/api/sync", get(sync_status).post(sync_now).put(sync_repo))
.layer(middleware::from_fn_with_state(Arc::new(guard), protect))
.with_state(Arc::new(home))
}
@@ -540,6 +541,52 @@ async fn save_image(State(home): Shared, headers: HeaderMap, body: Bytes) -> Res
}
}
+#[derive(Deserialize)]
+struct SyncRequest {
+ /// "local" or "remote", once the board has asked which side to keep.
+ #[serde(default)]
+ keep: Option<String>,
+}
+
+/// The board's sync button: the same as `kanzo sync`, without git ever prompting. When
+/// both sides changed, answers 409 with `diverged`, and the board asks which side to keep.
+async fn sync_now(State(home): Shared, Json(r): Json<SyncRequest>) -> Response {
+ let keep = match r.keep.as_deref() {
+ Some("local") => Some(sync::Keep::Local),
+ Some("remote") => Some(sync::Keep::Remote),
+ _ => None,
+ };
+ match tokio::task::spawn_blocking(move || sync::sync(&home, keep, false)).await {
+ Ok(Ok(message)) => Json(json!({ "message": message })).into_response(),
+ Ok(Err(e)) => match e.downcast_ref::<sync::Diverged>() {
+ Some(d) => (StatusCode::CONFLICT, Json(json!({ "error": d.message, "diverged": true, "first": d.first })))
+ .into_response(),
+ None => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": format!("{e:#}") }))).into_response(),
+ },
+ Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() }))).into_response(),
+ }
+}
+
+/// The repo the board syncs with, `null` before sync is set up.
+async fn sync_status(State(home): Shared) -> Response {
+ let remote = tokio::task::spawn_blocking(move || sync::remote_url(&home)).await.ok().flatten();
+ Json(json!({ "remote": remote })).into_response()
+}
+
+#[derive(Deserialize)]
+struct SyncRepo {
+ url: String,
+}
+
+/// Sets up sync with a repo, or moves it to another one.
+async fn sync_repo(State(home): Shared, Json(r): Json<SyncRepo>) -> Response {
+ match tokio::task::spawn_blocking(move || sync::set_remote(&home, &r.url, false)).await {
+ Ok(Ok(remote)) => Json(json!({ "remote": remote })).into_response(),
+ Ok(Err(e)) => (StatusCode::BAD_REQUEST, Json(json!({ "error": format!("{e:#}") }))).into_response(),
+ Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() }))).into_response(),
+ }
+}
+
#[derive(Deserialize)]
struct UpdateQuery {
/// Present to check GitHub now rather than reuse today's answer.