Files
magpie/backup_cmd.go
T
AronnaxandClaude Opus 5.5 7931723d79 cli: 新增 magpie webdav,在终端里开启、修改和触发 WebDAV 同步 / add magpie webdav to turn on, change and run WebDAV sync from the terminal (#127)
* cli: magpie webdav — WebDAV sync from the terminal, what Settings › WebDAV sync does, for a machine with no window (WSL, a server over SSH)

magpie webdav shows it; on <address> [user=…] [password=…] [keys=no] [agents=no] [library=no] turns it on and syncs at once, asking for the passphrase (and the password, when a user has none); set k=v… changes what is given and keeps the rest; now, dismiss and off are the page's Sync now, OK and Turn off. Through the same davsync.Configure, Now, Dismiss and Off.

A sync, Off and Dismiss hold a lock the system keeps on sync.lock (flock; LockFileEx on Windows): the gateway's sync every 3 minutes and one from a terminal — or from the app's window while magpie serve has the gateway — would each save sync-state.json over the other's. The system lets it go when the magpie holding it ends, however it ends.

Configure keeps the saved password only for the same server (scheme and host) and user: an address moved to another server, or another user, no longer takes it there — in the app too, where a new address with the password left empty was sent the old one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* davsync, cli: from the review of #127 — the setup read again under the lock, Configure locked too, the password never an argument, one left behind asked for, a wait that runs out said in the status

Now reads the setup again once it has the lock: one that waited while another magpie turned sync off went on with the setup it had read, and saved sync-state.json back after the Off. Configure takes mu and the lock too, after a sync in progress.

magpie webdav takes neither the password nor the passphrase as an argument: password= asks for it, as passphrase= does.

Configure with the saved password left behind — another server or user, the password empty — says to type it and saves nothing, where the Settings page dropped it and the sync failed with 401 under a field that still said saved.

A wait for the lock that runs out is davsync.ErrBusy. Dismiss returns it, and the davsync routes put ErrBusy from a sync in the status they answer with, where the page shows a sync's failures; Save's own errors stay in its form, what was typed in it kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* davsync, cli: the lock before mu, a wait bounded under the page's, one called off not called busy, the password rule in one place, a bare address with = in it

The lock comes before mu everywhere, so a wait for another magpie never holds mu, and Configure, Off and Dismiss wait for it 30 seconds at most, less than the Settings page gives a request: before, a request could hang on mu and then on the lock for minutes.

A wait for the lock called off, as when the page is closed or the gateway stops, is its context's error, not ErrBusy: nothing said another magpie was syncing.

What becomes of the saved password is decided in one place, davsync.SavedPassword, which Configure and magpie webdav both go by, where the two had rules of their own that had come apart: an account with a password and no user name, moved to another server, had its password dropped with nothing asked, and the sync failed with 401. It is asked for now, as for an account with a user.

magpie webdav takes a bare argument with :// in it as the address, = in it or not: https://host/dav?token=… was read as a field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 14:54:04 +08:00

177 lines
4.7 KiB
Go

package main
import (
"bufio"
"errors"
"fmt"
"os"
"strings"
"golang.org/x/term"
"github.com/yetone/magpie/internal/backup"
"github.com/yetone/magpie/internal/edit"
)
// backupCmd writes every provider, setting, profile and agent model, and
// the library, to one file sealed with a passphrase:
// magpie backup [--no-keys] [--no-library] [file].
func backupCmd(args []string) error {
keys, lib, file := true, true, ""
for _, a := range args {
switch {
case a == "--no-keys":
keys = false
case a == "--no-library":
lib = false
case strings.HasPrefix(a, "-"):
return fmt.Errorf("unknown flag %s (magpie backup [--no-keys] [--no-library] [file])", a)
case file == "":
file = a
default:
return errors.New("usage: magpie backup [--no-keys] [--no-library] [file]")
}
}
if file == "" {
file = "magpie" + backup.Ext
}
b, err := backup.Collect(keys, version)
if err != nil {
return err
}
if !lib {
b.Library = nil
}
pass, err := passphrase("Passphrase for the backup: ", true)
if err != nil {
return err
}
data, err := backup.Seal(b, pass)
if err != nil {
return err
}
if err := edit.WriteAtomic(file, data); err != nil {
return err
}
os.Chmod(file, 0o600)
what := "with their keys"
if !keys {
what = "without keys"
}
fmt.Printf("%s %s: %d providers %s, %d profiles, %d agent settings",
green.Render("saved"), file, len(b.Providers), what, len(b.Profiles), len(b.Agents))
if l := b.Library; l != nil {
fmt.Printf("; library: %d MCP servers, %d skills", len(l.MCP), len(l.Skills))
}
fmt.Println()
fmt.Println(muted.Render("Subscriptions are not in it: sign in to them on the other machine. Keep the passphrase: without it the file can't be opened."))
return nil
}
// restoreCmd puts a backup in: magpie restore [--no-agents] [--no-library] <file>.
func restoreCmd(args []string) error {
parts, file := backup.All, ""
for _, a := range args {
switch {
case a == "--no-agents":
parts.Agents = false
case a == "--no-library":
parts.Library = false
case strings.HasPrefix(a, "-"):
return fmt.Errorf("unknown flag %s (magpie restore [--no-agents] [--no-library] <file>)", a)
case file == "":
file = a
default:
return errors.New("usage: magpie restore [--no-agents] [--no-library] <file>")
}
}
if file == "" {
return errors.New("usage: magpie restore [--no-agents] [--no-library] <file>")
}
data, err := os.ReadFile(file)
if err != nil {
return err
}
pass, err := passphrase("Passphrase: ", false)
if err != nil {
return err
}
b, err := backup.Open(data, pass)
if err != nil {
return err
}
r, err := backup.Restore(b, parts)
if err != nil {
return err
}
fmt.Printf("%s providers: %d added, %d replaced", green.Render("restored"), r.Added, r.Replaced)
if r.Settings {
fmt.Print("; settings")
}
fmt.Printf("; %d profiles; %d agent settings changed", r.Profiles, r.Agents)
if r.Library {
fmt.Print("; library")
}
fmt.Println()
if len(r.NeedKey) > 0 {
fmt.Println(muted.Render("Needs a key (magpie provider key <id>): " + strings.Join(r.NeedKey, ", ")))
}
for _, p := range r.LibraryProblems {
fmt.Println(muted.Render(fmt.Sprintf("Library: %s couldn't get %s: %s", p.Agent, p.What, p.Error)))
}
if len(r.Skipped) > 0 {
fmt.Println(muted.Render("Left as they are (agent not here, or its model can't be reached yet): " + strings.Join(r.Skipped, ", ")))
}
return nil
}
// passphrase reads one from the terminal without echo, asked twice when
// it is being set; piped in, it is the next line of stdin.
func passphrase(prompt string, confirm bool) (string, error) {
return secret("passphrase", prompt, confirm)
}
// stdin is read through one reader, so a second secret piped in is the
// second line and not lost to the first one's buffer.
var stdin = bufio.NewReader(os.Stdin)
// secret reads what (a passphrase, a password) as passphrase does; piped
// in, it is the next line of stdin.
func secret(what, prompt string, confirm bool) (string, error) {
fd := int(os.Stdin.Fd())
if !term.IsTerminal(fd) {
line, err := stdin.ReadString('\n')
line = strings.TrimRight(line, "\r\n")
if line == "" {
if err != nil {
return "", fmt.Errorf("no %s on stdin: %w", what, err)
}
return "", fmt.Errorf("the %s is empty", what)
}
return line, nil
}
read := func(p string) (string, error) {
fmt.Fprint(os.Stderr, p)
b, err := term.ReadPassword(fd)
fmt.Fprintln(os.Stderr)
return string(b), err
}
pass, err := read(prompt)
if err != nil {
return "", err
}
if pass == "" {
return "", fmt.Errorf("the %s is empty", what)
}
if confirm {
again, err := read("Again: ")
if err != nil {
return "", err
}
if again != pass {
return "", fmt.Errorf("the %ss differ", what)
}
}
return pass, nil
}