Skip to content

Commit 594c549

Browse files
committed
refactor(backup): unify required path resolution
1 parent ac65c91 commit 594c549

6 files changed

Lines changed: 74 additions & 53 deletions

File tree

‎src/commands/backup-git.ts‎

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import fs from "node:fs/promises";
2-
import path from "node:path";
32
import { resolveConfiguredAgentId } from "../agents/agent-scope-config.js";
43
import { getRuntimeConfig } from "../config/config.js";
54
import { resolveStateDir } from "../config/paths.js";
@@ -18,7 +17,8 @@ import { recordBackupRunOutcome } from "../state/backup-run-records.js";
1817
import { listOpenClawRegisteredAgentDatabases } from "../state/openclaw-agent-db.js";
1918
import { resolveOpenClawAgentSqlitePath } from "../state/openclaw-agent-db.paths.js";
2019
import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths.js";
21-
import { resolveUserPath, shortenHomePath } from "../utils.js";
20+
import { shortenHomePath } from "../utils.js";
21+
import { resolveRequiredBackupPath } from "./backup-shared.js";
2222

2323
type BackupGitCreateOptions = {
2424
repository?: string;
@@ -38,14 +38,6 @@ type BackupGitScopeOptions = {
3838
export const GIT_BACKUP_PUSH_CREDENTIAL_WARNING =
3939
"Warning: pushed backup history contains credential material; keep the Git remote private.";
4040

41-
function resolveRequiredPath(value: string | undefined, label: string): string {
42-
const trimmed = value?.trim();
43-
if (!trimmed) {
44-
throw new Error(`Missing required ${label} value.`);
45-
}
46-
return path.resolve(resolveUserPath(trimmed));
47-
}
48-
4941
async function resolveCreateDatabases(runtime: RuntimeEnv, options: BackupGitCreateOptions) {
5042
const normalizedAgents = [
5143
...new Set(
@@ -151,7 +143,7 @@ export async function backupGitInitCommand(
151143
options: { repository?: string; remote?: string; json?: boolean },
152144
): Promise<{ repositoryPath: string }> {
153145
const result = await initializeGitBackupRepository({
154-
repositoryPath: resolveRequiredPath(options.repository, "--repository"),
146+
repositoryPath: resolveRequiredBackupPath(options.repository, "--repository"),
155147
stateDir: resolveStateDir(),
156148
remote: options.remote,
157149
});
@@ -164,7 +156,7 @@ export async function backupGitInitCommand(
164156
}
165157

166158
export async function backupGitCreateCommand(runtime: RuntimeEnv, options: BackupGitCreateOptions) {
167-
const repositoryPath = resolveRequiredPath(options.repository, "--repository");
159+
const repositoryPath = resolveRequiredBackupPath(options.repository, "--repository");
168160
if (options.push && !options.excludeSecrets) {
169161
runtime.error(GIT_BACKUP_PUSH_CREDENTIAL_WARNING);
170162
}
@@ -211,7 +203,7 @@ export async function backupGitLogCommand(
211203
runtime: RuntimeEnv,
212204
options: { repository?: string; limit?: number; json?: boolean },
213205
) {
214-
const repositoryPath = resolveRequiredPath(options.repository, "--repository");
206+
const repositoryPath = resolveRequiredBackupPath(options.repository, "--repository");
215207
const limit = options.limit ?? 20;
216208
if (!Number.isSafeInteger(limit) || limit < 1) {
217209
throw new Error("--limit must be a positive integer.");
@@ -234,7 +226,7 @@ export async function backupGitVerifyCommand(
234226
options: BackupGitScopeOptions & { repository?: string; ref?: string; json?: boolean },
235227
) {
236228
const result = await verifyGitBackupRef({
237-
repositoryPath: resolveRequiredPath(options.repository, "--repository"),
229+
repositoryPath: resolveRequiredBackupPath(options.repository, "--repository"),
238230
identity: resolveOneIdentity(options),
239231
ref: options.ref,
240232
});
@@ -259,10 +251,10 @@ export async function backupGitRestoreCommand(
259251
},
260252
) {
261253
const result = await restoreGitBackupRef({
262-
repositoryPath: resolveRequiredPath(options.repository, "--repository"),
254+
repositoryPath: resolveRequiredBackupPath(options.repository, "--repository"),
263255
identity: resolveOneIdentity(options),
264256
ref: options.ref,
265-
targetPath: resolveRequiredPath(options.target, "--target"),
257+
targetPath: resolveRequiredBackupPath(options.target, "--target"),
266258
});
267259
if (options.json) {
268260
writeRuntimeJson(runtime, result);

‎src/commands/backup-restore.ts‎

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,12 @@ import * as tar from "tar";
55
import { resolveStateDir } from "../config/config.js";
66
import { formatErrorMessage } from "../infra/errors.js";
77
import { type RuntimeEnv, writeRuntimeJson } from "../runtime.js";
8-
import { resolveUserPath, shortenHomePath } from "../utils.js";
9-
import { BACKUP_MAX_DECOMPRESSION_RATIO, canonicalizePathForContainment } from "./backup-shared.js";
8+
import { shortenHomePath } from "../utils.js";
9+
import {
10+
BACKUP_MAX_DECOMPRESSION_RATIO,
11+
canonicalizePathForContainment,
12+
resolveRequiredBackupPath,
13+
} from "./backup-shared.js";
1014
import { verifyBackupArchive } from "./backup-verify.js";
1115
import { isPathWithin } from "./cleanup-utils.js";
1216

@@ -37,14 +41,6 @@ type BackupRestoreResult = {
3741
warnings: string[];
3842
};
3943

40-
function resolveRequiredTarget(value: string | undefined): string {
41-
const trimmed = value?.trim();
42-
if (!trimmed) {
43-
throw new Error("Missing required --target value.");
44-
}
45-
return path.resolve(resolveUserPath(trimmed));
46-
}
47-
4844
async function assertTargetOutsideLiveState(targetPath: string): Promise<void> {
4945
const [canonicalTarget, canonicalStateDir] = await Promise.all([
5046
canonicalizePathForContainment(targetPath),
@@ -127,7 +123,7 @@ export async function backupRestoreCommand(
127123
runtime: RuntimeEnv,
128124
options: BackupRestoreOptions,
129125
): Promise<BackupRestoreResult> {
130-
const targetPath = resolveRequiredTarget(options.target);
126+
const targetPath = resolveRequiredBackupPath(options.target, "--target");
131127
await assertTargetOutsideLiveState(targetPath);
132128
const verified = await verifyBackupArchive(options.archive);
133129
const target = await prepareRestoreTarget(targetPath);

‎src/commands/backup-schedule.ts‎

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import path from "node:path";
21
import { resolveConfiguredAgentId } from "../agents/agent-scope-config.js";
32
import {
43
callGatewayFromCli,
@@ -11,8 +10,9 @@ import type { CronJob } from "../cron/types.js";
1110
import { executeGitCommand } from "../infra/git-exec.js";
1211
import { normalizeAgentId } from "../routing/session-key.js";
1312
import type { RuntimeEnv } from "../runtime.js";
14-
import { resolveUserPath, shortenHomePath } from "../utils.js";
13+
import { shortenHomePath } from "../utils.js";
1514
import { GIT_BACKUP_PUSH_CREDENTIAL_WARNING } from "./backup-git.js";
15+
import { resolveRequiredBackupPath } from "./backup-shared.js";
1616

1717
const BACKUP_CRON_JOB_NAME = "openclaw-backup-scheduled";
1818
const LOCAL_GATEWAY_REQUIRED_ERROR =
@@ -44,14 +44,6 @@ function resolveScheduledRedaction(options: BackupScheduleOptions): boolean {
4444
return options.includeSecrets !== true;
4545
}
4646

47-
function resolveRepository(value: string | undefined): string {
48-
const trimmed = value?.trim();
49-
if (!trimmed) {
50-
throw new Error("Missing required --repository value.");
51-
}
52-
return path.resolve(resolveUserPath(trimmed));
53-
}
54-
5547
function buildScheduledArgv(
5648
options: BackupScheduleOptions,
5749
repositoryPath: string,
@@ -106,7 +98,7 @@ export async function backupEnableCommand(
10698
options: BackupScheduleOptions,
10799
): Promise<{ id: string; updated: boolean }> {
108100
await assertLocalGatewayScheduleTarget(options);
109-
const repositoryPath = resolveRepository(options.repository);
101+
const repositoryPath = resolveRequiredBackupPath(options.repository, "--repository");
110102
const every = options.every?.trim() || "24h";
111103
const everyMs = parseDurationMs(every, { defaultUnit: "ms" });
112104
if (!Number.isSafeInteger(everyMs) || everyMs <= 0) {

‎src/commands/backup-shared.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import path from "node:path";
2+
import { afterEach, describe, expect, it, vi } from "vitest";
3+
import { resolveRequiredBackupPath } from "./backup-shared.js";
4+
5+
afterEach(() => {
6+
vi.unstubAllEnvs();
7+
});
8+
9+
describe("resolveRequiredBackupPath", () => {
10+
it.each([
11+
[undefined, "--repository"],
12+
["", "--target"],
13+
[" ", "<snapshot>"],
14+
["\t", "--scratch"],
15+
] as const)("rejects %j for %s", (value, label) => {
16+
expect(() => resolveRequiredBackupPath(value, label)).toThrow(
17+
`Missing required ${label} value.`,
18+
);
19+
});
20+
21+
it("trims and resolves relative paths from cwd", () => {
22+
expect(resolveRequiredBackupPath(" backups/archive ", "--target")).toBe(
23+
path.resolve("backups/archive"),
24+
);
25+
});
26+
27+
it("expands tilde from the effective home", () => {
28+
const home = path.resolve("effective-home");
29+
vi.stubEnv("OPENCLAW_HOME", home);
30+
expect(resolveRequiredBackupPath("~/backups", "--repository")).toBe(path.join(home, "backups"));
31+
});
32+
33+
it("preserves absolute paths", () => {
34+
const absolute = path.resolve("absolute-backup");
35+
expect(resolveRequiredBackupPath(` ${absolute} `, "--scratch")).toBe(absolute);
36+
});
37+
});

‎src/commands/backup-shared.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,25 @@ import {
77
resolveOAuthDir,
88
resolveStateDir,
99
} from "../config/config.js";
10-
import { pathExists, shortenHomePath } from "../utils.js";
10+
import { pathExists, resolveUserPath, shortenHomePath } from "../utils.js";
1111
import { buildCleanupPlan, isPathWithin } from "./cleanup-utils.js";
1212
import { planUpgradeConfigRepair } from "./doctor/shared/automatic-upgrade-config-repair.js";
1313

1414
// DEFLATE can legitimately encode zero-filled sparse ranges just over 1000:1.
1515
// Keep bounded headroom without disabling node-tar's decompression bomb guard.
1616
export const BACKUP_MAX_DECOMPRESSION_RATIO = 1100;
1717

18+
export function resolveRequiredBackupPath(
19+
value: string | undefined,
20+
label: "--repository" | "--target" | "<snapshot>" | "--scratch",
21+
): string {
22+
const trimmed = value?.trim();
23+
if (!trimmed) {
24+
throw new Error(`Missing required ${label} value.`);
25+
}
26+
return resolveUserPath(trimmed);
27+
}
28+
1829
type BackupAssetKind = "state" | "config" | "credentials" | "workspace";
1930
type BackupSkipReason = "covered" | "missing";
2031

‎src/commands/backup-sqlite.ts‎

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ import type {
1515
import { recordBackupRunOutcome } from "../state/backup-run-records.js";
1616
import { resolveOpenClawAgentSqlitePath } from "../state/openclaw-agent-db.paths.js";
1717
import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths.js";
18-
import { resolveUserPath, shortenHomePath } from "../utils.js";
18+
import { shortenHomePath } from "../utils.js";
19+
import { resolveRequiredBackupPath } from "./backup-shared.js";
1920

2021
type BackupSqliteCreateOptions = {
2122
global?: boolean;
@@ -76,7 +77,7 @@ export async function backupSqliteCreateCommand(
7677
runtime: RuntimeEnv,
7778
options: BackupSqliteCreateOptions,
7879
): Promise<BackupSqliteCreateResult> {
79-
const repositoryPath = resolveRequiredPath(options.repository, "--repository");
80+
const repositoryPath = resolveRequiredBackupPath(options.repository, "--repository");
8081
try {
8182
const database = await resolveSnapshotDatabase(options);
8283
const result = await createLocalSqliteSnapshotProvider({ repositoryPath }).create(database);
@@ -118,7 +119,7 @@ export async function backupSqliteListCommand(
118119
runtime: RuntimeEnv,
119120
options: BackupSqliteRepositoryOptions,
120121
): Promise<BackupSqliteListResult> {
121-
const repositoryPath = resolveRequiredPath(options.repository, "--repository");
122+
const repositoryPath = resolveRequiredBackupPath(options.repository, "--repository");
122123
const snapshots = await createLocalSqliteSnapshotProvider({
123124
repositoryPath,
124125
...OPENCLAW_SNAPSHOT_READ_OPTIONS,
@@ -154,7 +155,7 @@ export async function backupSqliteRestoreCommand(
154155
options: BackupSqliteRestoreOptions,
155156
): Promise<BackupSqliteRestoreResult> {
156157
const resolved = resolveSnapshot(snapshot);
157-
const targetPath = resolveRequiredPath(options.target, "--target");
158+
const targetPath = resolveRequiredBackupPath(options.target, "--target");
158159
const restored = await resolved.provider.restoreFresh(resolved.ref, targetPath);
159160
const report: BackupSqliteRestoreResult = {
160161
ok: true,
@@ -202,10 +203,10 @@ function resolveSnapshot(
202203
provider: ReturnType<typeof createLocalSqliteSnapshotProvider>;
203204
ref: SnapshotRef;
204205
} {
205-
const snapshotPath = resolveRequiredPath(snapshot, "<snapshot>");
206+
const snapshotPath = resolveRequiredBackupPath(snapshot, "<snapshot>");
206207
const repositoryPath = path.dirname(snapshotPath);
207208
const validationRootPath = scratch
208-
? resolveRequiredPath(scratch, "--scratch")
209+
? resolveRequiredBackupPath(scratch, "--scratch")
209210
: path.dirname(repositoryPath);
210211
return {
211212
provider: createLocalSqliteSnapshotProvider({
@@ -217,14 +218,6 @@ function resolveSnapshot(
217218
};
218219
}
219220

220-
function resolveRequiredPath(value: string | undefined, label: string): string {
221-
const trimmed = value?.trim();
222-
if (!trimmed) {
223-
throw new Error(`Missing required ${label} value.`);
224-
}
225-
return path.resolve(resolveUserPath(trimmed));
226-
}
227-
228221
function formatDatabaseIdentity(database: SnapshotDatabaseManifest): string {
229222
if (database.role === "global") {
230223
return "global";

0 commit comments

Comments
 (0)