Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## 0.47.2 - Unreleased

- Backup: keep new backups local until a remote is configured; preserve saved remotes and existing Git origins, and explain local-only operation. (#1287) — thanks @NasAndNora.

- Gmail: treat a whitespace-only `text/plain` part as missing when choosing a message body, so `gmail get`, `gmail thread get` and `--sanitize-content` output fall back to the HTML part instead of returning an empty body (seen in Meetup notifications). (#1279) — thanks @Flamefork.

- Release: require SSH-signed annotated tags authorized by the committed signer policy before builds and publication; preserve tagless dry runs.
Expand Down
26 changes: 17 additions & 9 deletions docs/backup.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,35 @@ summary: "Encrypted Google account backups"
read_when:
- Adding a new gog backup service adapter
- Changing encrypted backup layout, manifest fields, or age identity handling
- Debugging backup-gog push, status, or verify
- Debugging backup push, status, or verify
---

# Encrypted Backups

`gog backup` writes Google account data into a Git repository as age-encrypted
JSONL gzip shards. The intended repository is private, for example
`https://github.com/steipete/backup-gog`, but service payloads are encrypted
before Git sees them.
JSONL gzip shards. Backups stay local by default: there is no built-in remote.
Service payloads are encrypted before Git sees them. Choose a private repository
you control if you want to push backups.

## Commands

Initialize local config, create an age identity if needed, seed the backup repo,
and print the public recipient:
Initialize local config, create an age identity if needed, seed the local backup
repo, and print the public recipient:

```bash
gog backup init \
--repo ~/Projects/backup-gog \
--remote https://github.com/steipete/backup-gog.git
gog backup init --repo ~/Projects/backup-gog
```

To enable pushing, explicitly configure your own remote:

```bash
gog backup init --remote https://github.com/your-account/your-private-backup.git
```

`init` and `push` commit locally and explain that no upload happened when no
remote is configured. Explicitly saved remotes and existing Git `origin` URLs
continue to work without rewriting them. Checkpoint pushes follow the same rule.

Back up all supported services:

```bash
Expand Down
46 changes: 46 additions & 0 deletions internal/backup/backup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1025,3 +1025,49 @@ func readFile(t *testing.T, path string) []byte {
}
return data
}

func TestBackupLocalDefaultAndPushWithoutRemote(t *testing.T) {
if got := DefaultConfig().Remote; got != "" {
t.Fatalf("unexpected default remote: %q", got)
}
ctx, repo, config, _ := initTestBackup(t)
result, err := PushSnapshot(ctx, Snapshot{Services: []string{"gmail"}}, testOptions(t, Options{ConfigPath: config, Push: true}))
if err != nil {
t.Fatalf("local snapshot with push enabled: %v", err)
}
if !result.Changed {
t.Fatal("local snapshot was not committed")
}
if HasRemote(ctx, repo) {
t.Fatal("local backup acquired a remote")
}
if _, err := PushCheckpoint(ctx, Snapshot{Services: []string{"gmail"}}, Checkpoint{RunID: "local", Service: "gmail", Done: 1, Total: 2}, testOptions(t, Options{ConfigPath: config, Push: true})); err != nil {
t.Fatalf("local checkpoint: %v", err)
}
}

func TestBackupExistingOriginPreservedAndPushed(t *testing.T) {
ctx, repo, config, _ := initTestBackup(t)
remote := filepath.Join(t.TempDir(), "remote.git")
if err := git(ctx, "", "init", "--bare", remote); err != nil {
t.Fatal(err)
}
if err := git(ctx, repo, "remote", "add", "origin", remote); err != nil {
t.Fatal(err)
}
if _, err := PushSnapshot(ctx, Snapshot{Services: []string{"gmail"}}, testOptions(t, Options{ConfigPath: config, Push: true})); err != nil {
t.Fatal(err)
}
got, err := gitOutput(ctx, repo, "remote", "get-url", "origin")
if err != nil || strings.TrimSpace(got) != remote {
t.Fatalf("origin changed: %q %v", got, err)
}
localHead, err := gitOutput(ctx, repo, "rev-parse", "HEAD")
if err != nil {
t.Fatal(err)
}
remoteHead, err := gitOutput(ctx, remote, "rev-parse", strings.TrimSpace(localHead))
if err != nil || localHead != remoteHead {
t.Fatalf("snapshot not pushed: %q %v", remoteHead, err)
}
}
28 changes: 11 additions & 17 deletions internal/backup/config.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
package backup

const (
defaultRemote = "https://github.com/steipete/backup-gog.git"
)

type Config struct {
Repo string `json:"repo"`
Remote string `json:"remote"`
Expand All @@ -12,24 +8,22 @@ type Config struct {
}

type Options struct {
ConfigStore *ConfigStore
ConfigPath string
Repo string
Remote string
Identity string
Recipients []string
SuppressDefaultRemote bool
Push bool
SkipPull bool
AsyncPush bool
PushQueueLimit int
Progress func(format string, args ...any)
ConfigStore *ConfigStore
ConfigPath string
Repo string
Remote string
Identity string
Recipients []string
Push bool
SkipPull bool
AsyncPush bool
PushQueueLimit int
Progress func(format string, args ...any)
}

func DefaultConfig() Config {
return Config{
Repo: "~/Projects/backup-gog",
Remote: defaultRemote,
Identity: "~/.gog/age.key",
}
}
10 changes: 5 additions & 5 deletions internal/backup/config_more_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func TestConfigStoreLoadsLegacyConfigAndExpandsPaths(t *testing.T) {
t.Fatalf("NewConfigStore: %v", err)
}

cfg, err := store.ResolveOptions(Options{SuppressDefaultRemote: true})
cfg, err := store.ResolveOptions(Options{})
if err != nil {
t.Fatalf("ResolveOptions: %v", err)
}
Expand Down Expand Up @@ -146,7 +146,7 @@ func TestConfigStoreSuppressesOnlyImplicitDefaultRemote(t *testing.T) {
t.Fatalf("NewConfigStore: %v", err)
}

cfg, err := store.ResolveOptions(Options{SuppressDefaultRemote: true})
cfg, err := store.ResolveOptions(Options{})
if err != nil {
t.Fatalf("ResolveOptions default: %v", err)
}
Expand All @@ -155,16 +155,16 @@ func TestConfigStoreSuppressesOnlyImplicitDefaultRemote(t *testing.T) {
t.Fatalf("implicit default remote = %q", cfg.Remote)
}

if saveErr := store.Save("", Config{Repo: "~/repo", Remote: defaultRemote, Identity: "~/.gog/age.key"}); saveErr != nil {
if saveErr := store.Save("", Config{Repo: "~/repo", Remote: "https://github.com/steipete/backup-gog.git", Identity: "~/.gog/age.key"}); saveErr != nil {
t.Fatalf("Save: %v", saveErr)
}

cfg, err = store.ResolveOptions(Options{SuppressDefaultRemote: true})
cfg, err = store.ResolveOptions(Options{})
if err != nil {
t.Fatalf("ResolveOptions explicit: %v", err)
}

if cfg.Remote != defaultRemote {
if cfg.Remote != "https://github.com/steipete/backup-gog.git" {
t.Fatalf("explicit default remote = %q", cfg.Remote)
}
}
21 changes: 2 additions & 19 deletions internal/backup/config_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@ type ConfigStore struct {
}

type configDocument struct {
config Config
remoteExplicit bool
config Config
}

func NewConfigStore(layout appconfig.Layout, resolveHome func() (string, error)) (*ConfigStore, error) {
Expand Down Expand Up @@ -98,9 +97,6 @@ func (s *ConfigStore) ResolveOptions(opts Options) (Config, error) {
if strings.TrimSpace(opts.Remote) != "" {
cfg.Remote = opts.Remote
}
if opts.SuppressDefaultRemote && !doc.remoteExplicit && cfg.Remote == defaultRemote {
cfg.Remote = ""
}
if strings.TrimSpace(opts.Identity) != "" {
cfg.Identity = opts.Identity
}
Expand Down Expand Up @@ -159,11 +155,7 @@ func (s *ConfigStore) loadDocument(path string) (configDocument, error) {
if unmarshalErr := json.Unmarshal(data, &cfg); unmarshalErr != nil {
return configDocument{}, fmt.Errorf("read backup config: %w", unmarshalErr)
}
remoteExplicit, err := jsonObjectHasKey(data, "remote")
if err != nil {
return configDocument{}, err
}
return configDocument{config: cfg, remoteExplicit: remoteExplicit}, nil
return configDocument{config: cfg}, nil
}

func (s *ConfigStore) resolvePath(path string) (string, bool, error) {
Expand Down Expand Up @@ -215,12 +207,3 @@ func (s *ConfigStore) home() (string, error) {
})
return s.userHome, s.homeErr
}

func jsonObjectHasKey(data []byte, key string) (bool, error) {
var raw map[string]json.RawMessage
if err := json.Unmarshal(data, &raw); err != nil {
return false, fmt.Errorf("read backup config: %w", err)
}
_, ok := raw[key]
return ok, nil
}
12 changes: 11 additions & 1 deletion internal/backup/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,9 +157,15 @@ func pullRepo(ctx context.Context, repo string) error {
return pullErr
}

// HasRemote reports whether the repository has an origin without exposing its URL.
func HasRemote(ctx context.Context, repo string) bool {
remote, err := gitOutput(ctx, repo, "remote", "get-url", "origin")
return err == nil && strings.TrimSpace(remote) != ""
}

func commitAndPush(ctx context.Context, cfg Config, message string, push bool) (bool, error) {
changed, _, err := commitChanges(ctx, cfg, message)
if err != nil || !changed || !push {
if err != nil || !changed || !push || !HasRemote(ctx, cfg.Repo) {
return changed, err
Comment on lines +168 to 169

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Install the configured origin before silently skipping uploads

After a default local-only initialization, following the new instruction to run gog backup init --remote <URL> saves the URL but never installs an origin: ensureRepo returns through pullRepo immediately when .git already exists. Subsequent backups therefore hit this new guard and return success without uploading anything. Because the saved cfg.Remote is nonempty, prepareBackupPush also stops printing the local-only warning, leaving users believing remote backups are enabled. Add the explicitly configured origin when an existing repository has none, while preserving any existing origin.

Useful? React with 👍 / 👎.

}
if err := git(ctx, cfg.Repo, "push", "-u", "origin", "HEAD"); err != nil {
Expand Down Expand Up @@ -189,6 +195,10 @@ func commitChanges(ctx context.Context, cfg Config, message string) (bool, strin
}

func pushCommit(ctx context.Context, cfg Config, sha string) error {
if !HasRemote(ctx, cfg.Repo) {
return nil
}

branch, err := gitOutput(ctx, cfg.Repo, "symbolic-ref", "--quiet", "--short", "HEAD")
if err != nil || strings.TrimSpace(branch) == "" {
branch = "main"
Expand Down
28 changes: 25 additions & 3 deletions internal/cmd/backup.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"os"
"sort"
"strconv"
Expand Down Expand Up @@ -121,6 +122,21 @@ func backupCommandContext(ctx context.Context, flags *RootFlags) context.Context
return ctx
}

func prepareBackupPush(ctx context.Context, opts *backup.Options) error {
if !opts.Push {
return nil
}
cfg, err := backup.ResolveOptions(*opts)
if err != nil {
return err
}
if strings.TrimSpace(cfg.Remote) == "" && !backup.HasRemote(ctx, cfg.Repo) {
opts.Push = false
fmt.Fprintln(stderrWriter(ctx), "No backup remote configured; committing locally only. Configure a remote with gog backup init --remote <URL> to enable pushing.")
}
return nil
}

type BackupInitCmd struct {
backupFlags
}
Expand All @@ -131,9 +147,6 @@ func (c *BackupInitCmd) Run(ctx context.Context, flags *RootFlags) error {
if err := bindBackupConfigStore(ctx, &opts); err != nil {
return err
}
if c.NoPush && strings.TrimSpace(c.Remote) == "" {
opts.SuppressDefaultRemote = true
}
if flags != nil && flags.DryRun {
cfg, err := backup.ResolveOptions(opts)
if err != nil {
Expand All @@ -148,6 +161,9 @@ func (c *BackupInitCmd) Run(ctx context.Context, flags *RootFlags) error {
})
}

if err := prepareBackupPush(ctx, &opts); err != nil {
return err
}
cfg, recipient, err := backup.Init(ctx, opts)
if err != nil {
return err
Expand Down Expand Up @@ -230,6 +246,9 @@ func (c *BackupPushCmd) Run(ctx context.Context, flags *RootFlags) error {
if err := bindBackupConfigStore(ctx, &backupOpts); err != nil {
return err
}
if err := prepareBackupPush(ctx, &backupOpts); err != nil {
return err
}
backupOpts.AsyncPush = c.GmailCheckpoints
backupOpts.Progress = func(format string, args ...any) { gmailBackupProgressf(ctx, format, args...) }
snapshots, err := buildBackupSnapshots(services, c.snapshotBuilders(ctx, flags, backupOpts))
Expand Down Expand Up @@ -322,6 +341,9 @@ func (c *BackupGmailPushCmd) Run(ctx context.Context, flags *RootFlags) error {
if err := bindBackupConfigStore(ctx, &backupOpts); err != nil {
return err
}
if err := prepareBackupPush(ctx, &backupOpts); err != nil {
return err
}
backupOpts.AsyncPush = c.Checkpoints
backupOpts.Progress = func(format string, args ...any) { gmailBackupProgressf(ctx, format, args...) }
snapshot, err := buildGmailBackupSnapshot(ctx, flags, gmailBackupOptions{
Expand Down
11 changes: 11 additions & 0 deletions internal/cmd/backup_cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -595,3 +595,14 @@ func TestBackupExportReportsManifestCountsForSemanticCollisions(t *testing.T) {
}
}
}

func TestBackupInitDefaultsToLocalOnly(t *testing.T) {
dir := t.TempDir()
result := executeWithTestRuntime(t, []string{"--home", filepath.Join(dir, "home"), "backup", "init", "--repo", filepath.Join(dir, "repo"), "--identity", filepath.Join(dir, "age.key")}, nil)
if result.err != nil {
t.Fatalf("init: %v; %s", result.err, result.stderr)
}
if !strings.Contains(result.stderr, "committing locally only") {
t.Fatalf("missing local-only explanation: %s", result.stderr)
}
}
Loading