opencode-windows-scheduler 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/CROSS_PLATFORM.md +113 -0
- package/LICENSE +21 -0
- package/README.md +173 -2
- package/README.ru.md +131 -0
- package/ROADMAP-STRATEGY.md +217 -0
- package/ROADMAP.md +90 -0
- package/dist/core/analytics.d.ts +119 -0
- package/dist/core/analytics.d.ts.map +1 -0
- package/dist/core/analytics.js +265 -0
- package/dist/core/cron-to-schtasks.d.ts +20 -0
- package/dist/core/cron-to-schtasks.d.ts.map +1 -0
- package/dist/core/cron-to-schtasks.js +233 -0
- package/dist/core/dry-run.d.ts +44 -0
- package/dist/core/dry-run.d.ts.map +1 -0
- package/dist/core/dry-run.js +252 -0
- package/dist/core/file-watcher.d.ts +31 -0
- package/dist/core/file-watcher.d.ts.map +1 -0
- package/dist/core/file-watcher.js +128 -0
- package/dist/core/lock.d.ts +43 -0
- package/dist/core/lock.d.ts.map +1 -0
- package/dist/core/lock.js +118 -0
- package/dist/core/matrix.d.ts +167 -0
- package/dist/core/matrix.d.ts.map +1 -0
- package/dist/core/matrix.js +687 -0
- package/dist/core/ps-wrapper.d.ts +60 -0
- package/dist/core/ps-wrapper.d.ts.map +1 -0
- package/dist/core/ps-wrapper.js +538 -0
- package/dist/core/record-history.d.ts +14 -0
- package/dist/core/record-history.d.ts.map +1 -0
- package/dist/core/record-history.js +360 -0
- package/dist/core/retention.d.ts +29 -0
- package/dist/core/retention.d.ts.map +1 -0
- package/dist/core/retention.js +98 -0
- package/dist/core/scheduler/index.d.ts +20 -0
- package/dist/core/scheduler/index.d.ts.map +1 -0
- package/dist/core/scheduler/index.js +32 -0
- package/dist/core/scheduler/linux.d.ts +32 -0
- package/dist/core/scheduler/linux.d.ts.map +1 -0
- package/dist/core/scheduler/linux.js +115 -0
- package/dist/core/scheduler/logs.d.ts +11 -0
- package/dist/core/scheduler/logs.d.ts.map +1 -0
- package/dist/core/scheduler/logs.js +34 -0
- package/dist/core/scheduler/mac.d.ts +39 -0
- package/dist/core/scheduler/mac.d.ts.map +1 -0
- package/dist/core/scheduler/mac.js +175 -0
- package/dist/core/scheduler/posix.d.ts +40 -0
- package/dist/core/scheduler/posix.d.ts.map +1 -0
- package/dist/core/scheduler/posix.js +86 -0
- package/dist/core/scheduler/registry.d.ts +36 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -0
- package/dist/core/scheduler/registry.js +56 -0
- package/dist/core/scheduler/types.d.ts +63 -0
- package/dist/core/scheduler/types.d.ts.map +1 -0
- package/dist/core/scheduler/types.js +1 -0
- package/dist/core/scheduler/windows.d.ts +47 -0
- package/dist/core/scheduler/windows.d.ts.map +1 -0
- package/dist/core/scheduler/windows.js +375 -0
- package/dist/core/wrappers/bash.d.ts +58 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -0
- package/dist/core/wrappers/bash.js +223 -0
- package/dist/db/history-repo.d.ts +102 -0
- package/dist/db/history-repo.d.ts.map +1 -0
- package/dist/db/history-repo.js +215 -0
- package/dist/db/index.d.ts +47 -0
- package/dist/db/index.d.ts.map +1 -0
- package/dist/db/index.js +120 -0
- package/dist/db/metrics-repo.d.ts +43 -0
- package/dist/db/metrics-repo.d.ts.map +1 -0
- package/dist/db/metrics-repo.js +95 -0
- package/dist/db/migrate.d.ts +24 -0
- package/dist/db/migrate.d.ts.map +1 -0
- package/dist/db/migrate.js +237 -0
- package/dist/db/recovery.d.ts +11 -0
- package/dist/db/recovery.d.ts.map +1 -0
- package/dist/db/recovery.js +38 -0
- package/dist/db/schema.d.ts +24 -0
- package/dist/db/schema.d.ts.map +1 -0
- package/dist/db/schema.js +97 -0
- package/dist/db/settings-repo.d.ts +8 -0
- package/dist/db/settings-repo.d.ts.map +1 -0
- package/dist/db/settings-repo.js +27 -0
- package/dist/db/tasks-repo.d.ts +26 -0
- package/dist/db/tasks-repo.d.ts.map +1 -0
- package/dist/db/tasks-repo.js +120 -0
- package/dist/db/templates-repo.d.ts +17 -0
- package/dist/db/templates-repo.d.ts.map +1 -0
- package/dist/db/templates-repo.js +57 -0
- package/dist/history.d.ts +53 -0
- package/dist/history.d.ts.map +1 -0
- package/dist/history.js +57 -0
- package/dist/index.d.ts +156 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2159 -0
- package/dist/notifications.d.ts +45 -0
- package/dist/notifications.d.ts.map +1 -0
- package/dist/notifications.js +135 -0
- package/dist/rpc.d.ts +2186 -0
- package/dist/rpc.d.ts.map +1 -0
- package/dist/rpc.js +924 -0
- package/dist/schtasks.d.ts +32 -0
- package/dist/schtasks.d.ts.map +1 -0
- package/dist/schtasks.js +45 -0
- package/dist/server.d.ts +106 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +1668 -0
- package/dist/settings.d.ts +66 -0
- package/dist/settings.d.ts.map +1 -0
- package/dist/settings.js +137 -0
- package/dist/shared/jobs-view.d.ts +21 -0
- package/dist/shared/jobs-view.d.ts.map +1 -0
- package/dist/shared/jobs-view.js +28 -0
- package/dist/skill.d.ts +15 -0
- package/dist/skill.d.ts.map +1 -0
- package/dist/skill.js +93 -0
- package/dist/task-transfer.d.ts +176 -0
- package/dist/task-transfer.d.ts.map +1 -0
- package/dist/task-transfer.js +442 -0
- package/dist/templates.d.ts +57 -0
- package/dist/templates.d.ts.map +1 -0
- package/dist/templates.js +16 -0
- package/dist/types.d.ts +78 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +88 -0
- package/dist/version.d.ts +8 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +27 -0
- package/dist/workspaces.d.ts +55 -0
- package/dist/workspaces.d.ts.map +1 -0
- package/dist/workspaces.js +183 -0
- package/docs/ARCHITECTURE.md +314 -0
- package/docs/FEATURES.md +300 -0
- package/docs/MIGRATION.md +266 -0
- package/docs/dashboard.png +0 -0
- package/gui-experimental.cjs +2 -0
- package/index.js +1 -0
- package/package.json +94 -4
- package/scripts/demo-dashboard.mjs +199 -0
- package/skills/scheduled-job-best-practices/SKILL.md +155 -0
- package/skills/scheduled-job-best-practices/references/recipes.md +123 -0
- package/src/core/analytics.ts +378 -0
- package/src/core/cron-to-schtasks.ts +269 -0
- package/src/core/dry-run.ts +315 -0
- package/src/core/file-watcher.ts +171 -0
- package/src/core/lock.ts +134 -0
- package/src/core/matrix.ts +907 -0
- package/src/core/ps-wrapper.ts +572 -0
- package/src/core/record-history.ts +493 -0
- package/src/core/retention.ts +141 -0
- package/src/core/scheduler/index.ts +44 -0
- package/src/core/scheduler/linux.ts +125 -0
- package/src/core/scheduler/logs.ts +37 -0
- package/src/core/scheduler/mac.ts +222 -0
- package/src/core/scheduler/posix.ts +111 -0
- package/src/core/scheduler/registry.ts +93 -0
- package/src/core/scheduler/types.ts +67 -0
- package/src/core/scheduler/windows.ts +469 -0
- package/src/core/wrappers/bash.ts +282 -0
- package/src/db/history-repo.ts +396 -0
- package/src/db/index.ts +166 -0
- package/src/db/metrics-repo.ts +158 -0
- package/src/db/migrate.ts +322 -0
- package/src/db/recovery.ts +46 -0
- package/src/db/schema.ts +109 -0
- package/src/db/settings-repo.ts +31 -0
- package/src/db/tasks-repo.ts +162 -0
- package/src/db/templates-repo.ts +77 -0
- package/src/gui.tsx +2868 -0
- package/src/history.ts +107 -0
- package/src/index.ts +2768 -0
- package/src/notifications.ts +174 -0
- package/src/rpc.ts +999 -0
- package/src/schtasks.ts +75 -0
- package/src/server.ts +1879 -0
- package/src/settings.ts +228 -0
- package/src/shared/jobs-view.ts +38 -0
- package/src/skill.ts +113 -0
- package/src/task-transfer.ts +648 -0
- package/src/templates.ts +67 -0
- package/src/tui.tsx +46 -0
- package/src/types.ts +145 -0
- package/src/version.ts +27 -0
- package/src/workspaces.ts +236 -0
package/dist/types.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
/** Префикс всех задач плагина (историческое имя, сохраняется для совместимости). */
|
|
5
|
+
export const TASK_PREFIX = "OpenCode\\windows-scheduler";
|
|
6
|
+
/** Папка задач плагина в планировщике ОС (Windows). */
|
|
7
|
+
export const TASK_FOLDER = "OpenCode";
|
|
8
|
+
export const TASK_FOLDER_NAME = "windows-scheduler";
|
|
9
|
+
/**
|
|
10
|
+
* Директория для хранения файлов плагина (обёртки, логи, блокировки, история).
|
|
11
|
+
*
|
|
12
|
+
* Windows: %APPDATA%\opencode\windows-scheduler (как раньше — без миграции).
|
|
13
|
+
* macOS/Linux: $XDG_CONFIG_HOME/opencode/windows-scheduler или
|
|
14
|
+
* ~/.config/opencode/windows-scheduler.
|
|
15
|
+
*/
|
|
16
|
+
function resolvePluginDir() {
|
|
17
|
+
// Explicit override (tests, custom installations). Takes precedence on every platform.
|
|
18
|
+
const custom = process.env.OPENCODE_SCHEDULER_HOME?.trim();
|
|
19
|
+
if (custom)
|
|
20
|
+
return path.resolve(custom);
|
|
21
|
+
if (process.platform === "win32") {
|
|
22
|
+
const base = process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming");
|
|
23
|
+
return path.join(base, "opencode", TASK_FOLDER_NAME);
|
|
24
|
+
}
|
|
25
|
+
const configHome = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
|
|
26
|
+
return path.join(configHome, "opencode", TASK_FOLDER_NAME);
|
|
27
|
+
}
|
|
28
|
+
export const PLUGIN_DIR = resolvePluginDir();
|
|
29
|
+
export const LOCK_DIR = path.join(PLUGIN_DIR, "locks");
|
|
30
|
+
export const LOG_DIR = path.join(PLUGIN_DIR, "logs");
|
|
31
|
+
export const WRAPPER_DIR = path.join(PLUGIN_DIR, "wrappers");
|
|
32
|
+
/** true, если плагин запущен на Windows. */
|
|
33
|
+
export const IS_WINDOWS = process.platform === "win32";
|
|
34
|
+
/** Порог возраста lock-файла, после которого он считается зависшим (24 часа). */
|
|
35
|
+
export const STALE_LOCK_MAX_AGE_MS = 24 * 60 * 60 * 1000;
|
|
36
|
+
/**
|
|
37
|
+
* Приводит имя задачи к безопасному виду для имён файлов (обёртка, промпт, lock, лог).
|
|
38
|
+
* Кириллица транслитерируется, прочие спецсимволы заменяются на дефис.
|
|
39
|
+
* Используется единообразно при создании задачи (index.ts) и при чтении логов (schtasks.ts).
|
|
40
|
+
*/
|
|
41
|
+
export function sanitizeName(name) {
|
|
42
|
+
const translit = {
|
|
43
|
+
а: "a", б: "b", в: "v", г: "g", д: "d", е: "e", ё: "e",
|
|
44
|
+
ж: "zh", з: "z", и: "i", й: "y", к: "k", л: "l", м: "m",
|
|
45
|
+
н: "n", о: "o", п: "p", р: "r", с: "s", т: "t", у: "u",
|
|
46
|
+
ф: "f", х: "h", ц: "ts", ч: "ch", ш: "sh", щ: "sch",
|
|
47
|
+
ъ: "", ы: "y", ь: "", э: "e", ю: "yu", я: "ya",
|
|
48
|
+
};
|
|
49
|
+
let result = name.toLowerCase();
|
|
50
|
+
result = result.split("").map((c) => translit[c] || c).join("");
|
|
51
|
+
result = result.replace(/[^a-z0-9_\-]/g, "-");
|
|
52
|
+
result = result.replace(/-+/g, "-").replace(/^-+|-+$/g, "");
|
|
53
|
+
return result || "task";
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Схема аргументов для schedule_job.
|
|
57
|
+
* schedule принимает только 5-полевые cron-выражения.
|
|
58
|
+
*/
|
|
59
|
+
export const ScheduleJobArgs = z.object({
|
|
60
|
+
name: z
|
|
61
|
+
.string()
|
|
62
|
+
.min(1)
|
|
63
|
+
.regex(/^[A-Za-z0-9_\-]+$/, "Имя задачи должно содержать только буквы, цифры, подчёркивание и дефис")
|
|
64
|
+
.describe("Имя задачи (уникально в рамках префикса OpenCode\\windows-scheduler)"),
|
|
65
|
+
schedule: z
|
|
66
|
+
.string()
|
|
67
|
+
.min(1)
|
|
68
|
+
.describe("5-полевое cron-выражение (минута час день_месяца месяц день_недели)"),
|
|
69
|
+
prompt: z.string().min(1).describe("Промпт, который передаётся в opencode run при запуске задачи"),
|
|
70
|
+
timeoutSeconds: z
|
|
71
|
+
.number()
|
|
72
|
+
.int()
|
|
73
|
+
.positive()
|
|
74
|
+
.optional()
|
|
75
|
+
.default(3600)
|
|
76
|
+
.describe("Таймаут выполнения задачи в секундах (по умолчанию 3600)"),
|
|
77
|
+
workdir: z
|
|
78
|
+
.string()
|
|
79
|
+
.optional()
|
|
80
|
+
.describe("Рабочая директория для выполнения opencode run (по умолчанию текущая)"),
|
|
81
|
+
});
|
|
82
|
+
export const DeleteJobArgs = z.object({
|
|
83
|
+
name: z.string().min(1).describe("Имя задачи для удаления"),
|
|
84
|
+
});
|
|
85
|
+
export const RunJobNowArgs = z.object({
|
|
86
|
+
name: z.string().min(1).describe("Имя задачи для немедленного запуска"),
|
|
87
|
+
});
|
|
88
|
+
export const ListJobsArgs = z.object({});
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Версия плагина из package.json.
|
|
3
|
+
*
|
|
4
|
+
* Читается в рантайме из корня пакета рядом со скомпилированным модулем
|
|
5
|
+
* (dist/version.js -> ../package.json). Если файл недоступен — «unknown».
|
|
6
|
+
*/
|
|
7
|
+
export declare function getPluginVersion(): string;
|
|
8
|
+
//# sourceMappingURL=version.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAMA;;;;;GAKG;AACH,wBAAgB,gBAAgB,IAAI,MAAM,CAczC"}
|
package/dist/version.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
let cached = null;
|
|
5
|
+
/**
|
|
6
|
+
* Версия плагина из package.json.
|
|
7
|
+
*
|
|
8
|
+
* Читается в рантайме из корня пакета рядом со скомпилированным модулем
|
|
9
|
+
* (dist/version.js -> ../package.json). Если файл недоступен — «unknown».
|
|
10
|
+
*/
|
|
11
|
+
export function getPluginVersion() {
|
|
12
|
+
if (cached)
|
|
13
|
+
return cached;
|
|
14
|
+
try {
|
|
15
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
16
|
+
const raw = fs.readFileSync(path.join(here, "..", "package.json"), "utf8");
|
|
17
|
+
const pkg = JSON.parse(raw);
|
|
18
|
+
cached =
|
|
19
|
+
typeof pkg.version === "string" && pkg.version.trim()
|
|
20
|
+
? pkg.version.trim()
|
|
21
|
+
: "unknown";
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
cached = "unknown";
|
|
25
|
+
}
|
|
26
|
+
return cached;
|
|
27
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Multi-repo workspaces.
|
|
3
|
+
*
|
|
4
|
+
* Одна задача = один workspace = один cwd. Workspace — это просто
|
|
5
|
+
* зарегистрированный путь к репозиторию; плагин никогда не «угадывает»,
|
|
6
|
+
* куда мержить и не выполняет cross-repo операции самостоятельно.
|
|
7
|
+
*/
|
|
8
|
+
export interface Workspace {
|
|
9
|
+
id: string;
|
|
10
|
+
name: string;
|
|
11
|
+
path: string;
|
|
12
|
+
gitRemote?: string;
|
|
13
|
+
color?: string;
|
|
14
|
+
createdAt: string;
|
|
15
|
+
}
|
|
16
|
+
export interface AddWorkspaceInput {
|
|
17
|
+
name?: string;
|
|
18
|
+
path: string;
|
|
19
|
+
color?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface UpdateWorkspacePatch {
|
|
22
|
+
name?: string;
|
|
23
|
+
path?: string;
|
|
24
|
+
color?: string;
|
|
25
|
+
gitRemote?: string | null;
|
|
26
|
+
}
|
|
27
|
+
/** Палитра цветных маркеров для GUI/дашборда. */
|
|
28
|
+
export declare const WORKSPACE_COLORS: string[];
|
|
29
|
+
/** Проверяет, что путь существует и является директорией. */
|
|
30
|
+
export declare function validateWorkspacePath(workspacePath: string): void;
|
|
31
|
+
/**
|
|
32
|
+
* Читает git remote origin. Если путь не git-репозиторий или remote не
|
|
33
|
+
* настроен — возвращает undefined (это не ошибка).
|
|
34
|
+
*/
|
|
35
|
+
export declare function readGitRemote(workspacePath: string): string | undefined;
|
|
36
|
+
/** Текущая git-ветка (для dry-run preview); undefined вне git-репозитория. */
|
|
37
|
+
export declare function readGitBranch(workspacePath: string): string | undefined;
|
|
38
|
+
/** Все workspace (по имени). */
|
|
39
|
+
export declare function listWorkspaces(): Workspace[];
|
|
40
|
+
/** Workspace по id. */
|
|
41
|
+
export declare function getWorkspace(id: string): Workspace | undefined;
|
|
42
|
+
/** Workspace по пути (без учёта регистра, как в Windows). */
|
|
43
|
+
export declare function getWorkspaceByPath(workspacePath: string): Workspace | undefined;
|
|
44
|
+
/** Регистрирует новый workspace. Путь должен существовать. */
|
|
45
|
+
export declare function addWorkspace(input: AddWorkspaceInput): Workspace;
|
|
46
|
+
/** Обновляет имя/путь/цвет workspace. */
|
|
47
|
+
export declare function updateWorkspace(id: string, patch: UpdateWorkspacePatch): Workspace;
|
|
48
|
+
/**
|
|
49
|
+
* Удаляет workspace. Задачи не удаляются — у них просто очищается
|
|
50
|
+
* workspaceId (с предупреждением в логе).
|
|
51
|
+
*/
|
|
52
|
+
export declare function deleteWorkspace(id: string): boolean;
|
|
53
|
+
/** Количество workspace (для сводок и тестов). */
|
|
54
|
+
export declare function countWorkspaces(): number;
|
|
55
|
+
//# sourceMappingURL=workspaces.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"workspaces.d.ts","sourceRoot":"","sources":["../src/workspaces.ts"],"names":[],"mappings":"AAOA;;;;;;GAMG;AACH,MAAM,WAAW,SAAS;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,iBAAiB;IAChC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,oBAAoB;IACnC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B;AAED,iDAAiD;AACjD,eAAO,MAAM,gBAAgB,UAO5B,CAAC;AAiBF,6DAA6D;AAC7D,wBAAgB,qBAAqB,CAAC,aAAa,EAAE,MAAM,GAAG,IAAI,CAOjE;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAavE;AAED,8EAA8E;AAC9E,wBAAgB,aAAa,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAavE;AAED,gCAAgC;AAChC,wBAAgB,cAAc,IAAI,SAAS,EAAE,CAK5C;AAED,uBAAuB;AACvB,wBAAgB,YAAY,CAAC,EAAE,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS,CAI9D;AAED,6DAA6D;AAC7D,wBAAgB,kBAAkB,CAAC,aAAa,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS,CAM/E;AAED,8DAA8D;AAC9D,wBAAgB,YAAY,CAAC,KAAK,EAAE,iBAAiB,GAAG,SAAS,CAgChE;AAED,yCAAyC;AACzC,wBAAgB,eAAe,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,oBAAoB,GAAG,SAAS,CA0ClF;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAenD;AAED,kDAAkD;AAClD,wBAAgB,eAAe,IAAI,MAAM,CAGxC"}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { statSync } from "node:fs";
|
|
3
|
+
import { basename, resolve } from "node:path";
|
|
4
|
+
import { spawnSync } from "node:child_process";
|
|
5
|
+
import { getDb } from "./db/index.js";
|
|
6
|
+
import { clearWorkspaceAssignments } from "./db/tasks-repo.js";
|
|
7
|
+
/** Палитра цветных маркеров для GUI/дашборда. */
|
|
8
|
+
export const WORKSPACE_COLORS = [
|
|
9
|
+
"#5b8def",
|
|
10
|
+
"#2fb67c",
|
|
11
|
+
"#e0a03a",
|
|
12
|
+
"#d15c8a",
|
|
13
|
+
"#8b6fe8",
|
|
14
|
+
"#3aa8b8",
|
|
15
|
+
];
|
|
16
|
+
function rowToWorkspace(row) {
|
|
17
|
+
return {
|
|
18
|
+
id: String(row.id),
|
|
19
|
+
name: String(row.name),
|
|
20
|
+
path: String(row.path),
|
|
21
|
+
gitRemote: row.git_remote == null ? undefined : String(row.git_remote),
|
|
22
|
+
color: row.color == null ? undefined : String(row.color),
|
|
23
|
+
createdAt: String(row.created_at),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function normalizePath(value) {
|
|
27
|
+
return resolve(value.trim());
|
|
28
|
+
}
|
|
29
|
+
/** Проверяет, что путь существует и является директорией. */
|
|
30
|
+
export function validateWorkspacePath(workspacePath) {
|
|
31
|
+
try {
|
|
32
|
+
const stat = statSync(workspacePath);
|
|
33
|
+
if (!stat.isDirectory())
|
|
34
|
+
throw new Error("not a directory");
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
throw new Error(`Путь workspace недоступен: ${workspacePath}`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Читает git remote origin. Если путь не git-репозиторий или remote не
|
|
42
|
+
* настроен — возвращает undefined (это не ошибка).
|
|
43
|
+
*/
|
|
44
|
+
export function readGitRemote(workspacePath) {
|
|
45
|
+
try {
|
|
46
|
+
const result = spawnSync("git", ["-C", workspacePath, "remote", "get-url", "origin"], {
|
|
47
|
+
encoding: "utf8",
|
|
48
|
+
timeout: 5000,
|
|
49
|
+
windowsHide: true,
|
|
50
|
+
});
|
|
51
|
+
if (result.status !== 0)
|
|
52
|
+
return undefined;
|
|
53
|
+
const remote = String(result.stdout || "").trim();
|
|
54
|
+
return remote || undefined;
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** Текущая git-ветка (для dry-run preview); undefined вне git-репозитория. */
|
|
61
|
+
export function readGitBranch(workspacePath) {
|
|
62
|
+
try {
|
|
63
|
+
const result = spawnSync("git", ["-C", workspacePath, "rev-parse", "--abbrev-ref", "HEAD"], { encoding: "utf8", timeout: 5000, windowsHide: true });
|
|
64
|
+
if (result.status !== 0)
|
|
65
|
+
return undefined;
|
|
66
|
+
const branch = String(result.stdout || "").trim();
|
|
67
|
+
return branch || undefined;
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/** Все workspace (по имени). */
|
|
74
|
+
export function listWorkspaces() {
|
|
75
|
+
const rows = getDb()
|
|
76
|
+
.prepare("SELECT * FROM workspaces ORDER BY name COLLATE NOCASE ASC")
|
|
77
|
+
.all();
|
|
78
|
+
return rows.map(rowToWorkspace);
|
|
79
|
+
}
|
|
80
|
+
/** Workspace по id. */
|
|
81
|
+
export function getWorkspace(id) {
|
|
82
|
+
if (!id)
|
|
83
|
+
return undefined;
|
|
84
|
+
const row = getDb().prepare("SELECT * FROM workspaces WHERE id = ?").get(id);
|
|
85
|
+
return row ? rowToWorkspace(row) : undefined;
|
|
86
|
+
}
|
|
87
|
+
/** Workspace по пути (без учёта регистра, как в Windows). */
|
|
88
|
+
export function getWorkspaceByPath(workspacePath) {
|
|
89
|
+
const normalized = normalizePath(workspacePath);
|
|
90
|
+
const row = getDb()
|
|
91
|
+
.prepare("SELECT * FROM workspaces WHERE lower(path) = lower(?) LIMIT 1")
|
|
92
|
+
.get(normalized);
|
|
93
|
+
return row ? rowToWorkspace(row) : undefined;
|
|
94
|
+
}
|
|
95
|
+
/** Регистрирует новый workspace. Путь должен существовать. */
|
|
96
|
+
export function addWorkspace(input) {
|
|
97
|
+
const workspacePath = normalizePath(input.path || "");
|
|
98
|
+
if (!workspacePath) {
|
|
99
|
+
throw new Error("Путь workspace не может быть пустым.");
|
|
100
|
+
}
|
|
101
|
+
const name = (input.name || basename(workspacePath) || workspacePath).trim();
|
|
102
|
+
try {
|
|
103
|
+
validateWorkspacePath(workspacePath);
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
throw new Error(`Workspace '${name}' недоступен по пути '${workspacePath}'`);
|
|
107
|
+
}
|
|
108
|
+
const existing = getWorkspaceByPath(workspacePath);
|
|
109
|
+
if (existing) {
|
|
110
|
+
throw new Error(`Workspace с путём '${workspacePath}' уже существует.`);
|
|
111
|
+
}
|
|
112
|
+
const id = randomUUID();
|
|
113
|
+
const color = input.color?.trim() ||
|
|
114
|
+
WORKSPACE_COLORS[listWorkspaces().length % WORKSPACE_COLORS.length];
|
|
115
|
+
const createdAt = new Date().toISOString();
|
|
116
|
+
const gitRemote = readGitRemote(workspacePath);
|
|
117
|
+
getDb()
|
|
118
|
+
.prepare(`INSERT INTO workspaces (id, name, path, git_remote, color, created_at)
|
|
119
|
+
VALUES (?, ?, ?, ?, ?, ?)`)
|
|
120
|
+
.run(id, name, workspacePath, gitRemote ?? null, color, createdAt);
|
|
121
|
+
return { id, name, path: workspacePath, gitRemote, color, createdAt };
|
|
122
|
+
}
|
|
123
|
+
/** Обновляет имя/путь/цвет workspace. */
|
|
124
|
+
export function updateWorkspace(id, patch) {
|
|
125
|
+
const existing = getWorkspace(id);
|
|
126
|
+
if (!existing)
|
|
127
|
+
throw new Error(`Workspace '${id}' не найден.`);
|
|
128
|
+
const nextName = patch.name?.trim() || existing.name;
|
|
129
|
+
const nextPath = patch.path?.trim() ? normalizePath(patch.path) : existing.path;
|
|
130
|
+
if (nextPath !== existing.path) {
|
|
131
|
+
try {
|
|
132
|
+
validateWorkspacePath(nextPath);
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
throw new Error(`Workspace '${nextName}' недоступен по пути '${nextPath}'`);
|
|
136
|
+
}
|
|
137
|
+
const duplicate = getWorkspaceByPath(nextPath);
|
|
138
|
+
if (duplicate && duplicate.id !== id) {
|
|
139
|
+
throw new Error(`Workspace с путём '${nextPath}' уже существует.`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const nextColor = patch.color?.trim() || existing.color;
|
|
143
|
+
const nextRemote = patch.gitRemote === null
|
|
144
|
+
? undefined
|
|
145
|
+
: patch.gitRemote !== undefined
|
|
146
|
+
? patch.gitRemote.trim() || undefined
|
|
147
|
+
: nextPath !== existing.path
|
|
148
|
+
? readGitRemote(nextPath)
|
|
149
|
+
: existing.gitRemote;
|
|
150
|
+
getDb()
|
|
151
|
+
.prepare("UPDATE workspaces SET name = ?, path = ?, git_remote = ?, color = ? WHERE id = ?")
|
|
152
|
+
.run(nextName, nextPath, nextRemote ?? null, nextColor ?? null, id);
|
|
153
|
+
return {
|
|
154
|
+
id,
|
|
155
|
+
name: nextName,
|
|
156
|
+
path: nextPath,
|
|
157
|
+
gitRemote: nextRemote,
|
|
158
|
+
color: nextColor,
|
|
159
|
+
createdAt: existing.createdAt,
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Удаляет workspace. Задачи не удаляются — у них просто очищается
|
|
164
|
+
* workspaceId (с предупреждением в логе).
|
|
165
|
+
*/
|
|
166
|
+
export function deleteWorkspace(id) {
|
|
167
|
+
const workspace = getWorkspace(id);
|
|
168
|
+
if (!workspace)
|
|
169
|
+
return false;
|
|
170
|
+
const affected = clearWorkspaceAssignments(id);
|
|
171
|
+
if (affected.length > 0) {
|
|
172
|
+
console.warn(`[workspace] Удалён workspace '${workspace.name}'. ` +
|
|
173
|
+
`Отвязано задач: ${affected.length} (${affected.join(", ")}). ` +
|
|
174
|
+
`Задачи не удалены, workspaceId очищен.`);
|
|
175
|
+
}
|
|
176
|
+
const result = getDb().prepare("DELETE FROM workspaces WHERE id = ?").run(id);
|
|
177
|
+
return Number(result.changes) > 0;
|
|
178
|
+
}
|
|
179
|
+
/** Количество workspace (для сводок и тестов). */
|
|
180
|
+
export function countWorkspaces() {
|
|
181
|
+
const row = getDb().prepare("SELECT COUNT(*) AS count FROM workspaces").get();
|
|
182
|
+
return Number(row?.count) || 0;
|
|
183
|
+
}
|