opencode-windows-scheduler 1.3.0 → 1.5.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 +47 -1
- package/README.md +11 -5
- package/ROADMAP-STRATEGY.md +45 -26
- package/ROADMAP.md +279 -35
- package/dist/core/audit.d.ts +68 -0
- package/dist/core/audit.d.ts.map +1 -0
- package/dist/core/audit.js +206 -0
- package/dist/core/dry-run.d.ts +31 -0
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +129 -1
- package/dist/core/file-watcher.d.ts.map +1 -1
- package/dist/core/file-watcher.js +53 -10
- package/dist/core/git-trigger.d.ts +80 -0
- package/dist/core/git-trigger.d.ts.map +1 -0
- package/dist/core/git-trigger.js +288 -0
- package/dist/core/glob.d.ts +38 -0
- package/dist/core/glob.d.ts.map +1 -0
- package/dist/core/glob.js +233 -0
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +7 -0
- package/dist/core/schedule-gate.js +55 -30
- package/dist/core/schedule-v2.d.ts +29 -1
- package/dist/core/schedule-v2.d.ts.map +1 -1
- package/dist/core/schedule-v2.js +81 -3
- package/dist/core/scheduler/types.d.ts +1 -1
- package/dist/core/scheduler/types.d.ts.map +1 -1
- package/dist/core/secrets.d.ts +57 -0
- package/dist/core/secrets.d.ts.map +1 -0
- package/dist/core/secrets.js +331 -0
- package/dist/core/structured-log.d.ts.map +1 -1
- package/dist/core/structured-log.js +9 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +4 -0
- package/dist/db/git-state-repo.d.ts +16 -0
- package/dist/db/git-state-repo.d.ts.map +1 -0
- package/dist/db/git-state-repo.js +38 -0
- package/dist/db/schema.d.ts +1 -1
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +23 -0
- package/dist/index.d.ts +68 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +589 -45
- package/dist/rpc.d.ts +623 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +219 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +67 -0
- package/dist/settings.d.ts +16 -0
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +29 -0
- package/dist/task-transfer.d.ts +30 -3
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +83 -6
- package/dist/templates.d.ts +1 -1
- package/dist/templates.d.ts.map +1 -1
- package/dist/workspaces.d.ts +8 -2
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +21 -4
- package/docs/ARCHITECTURE.md +14 -5
- package/docs/FEATURES.md +80 -1
- package/docs/README.ru.md +15 -5
- package/gui-experimental.cjs +9 -4
- package/package.json +8 -3
- package/src/core/audit.ts +291 -0
- package/src/core/dry-run.ts +188 -1
- package/src/core/file-watcher.ts +65 -10
- package/src/core/git-trigger.ts +367 -0
- package/src/core/glob.ts +226 -0
- package/src/core/ps-wrapper.ts +7 -0
- package/src/core/schedule-gate.ts +67 -33
- package/src/core/schedule-v2.ts +108 -3
- package/src/core/scheduler/types.ts +1 -1
- package/src/core/secrets.ts +385 -0
- package/src/core/structured-log.ts +9 -0
- package/src/core/wrappers/bash.ts +4 -0
- package/src/db/git-state-repo.ts +62 -0
- package/src/db/schema.ts +23 -0
- package/src/gui.tsx +548 -4
- package/src/index.ts +790 -47
- package/src/rpc.ts +230 -0
- package/src/server.ts +67 -0
- package/src/settings.ts +51 -0
- package/src/task-transfer.ts +124 -5
- package/src/templates.ts +1 -1
- package/src/workspaces.ts +22 -4
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { loadTaskDefinitions, type TaskDefinition } from "../task-transfer.js";
|
|
5
|
+
import { getGitState, setGitState, deleteGitState } from "../db/git-state-repo.js";
|
|
6
|
+
import { filterPaths } from "./glob.js";
|
|
7
|
+
import { getWorkspace } from "../workspaces.js";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Git-триггеры (Спринт 27).
|
|
11
|
+
*
|
|
12
|
+
* Задача с `triggerType: "git"` запускается, когда в её рабочей директории
|
|
13
|
+
* появился новый коммит, затронувший подходящие файлы. Состояние — последний
|
|
14
|
+
* обработанный `HEAD` — хранится в SQLite (`git_state`), поэтому перезапуск
|
|
15
|
+
* плагина не приводит к повторным запускам.
|
|
16
|
+
*
|
|
17
|
+
* Первый опрос только запоминает текущий `HEAD` (baseline) и ничего не запускает.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export const GIT_TRIGGER_DEFAULT_POLL_SECONDS = 60;
|
|
21
|
+
export const GIT_TRIGGER_MIN_POLL_SECONDS = 5;
|
|
22
|
+
export const GIT_COMMAND_TIMEOUT_MS = 10_000;
|
|
23
|
+
|
|
24
|
+
export interface GitProbe {
|
|
25
|
+
head: string;
|
|
26
|
+
branch: string | null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface GitTriggerTask {
|
|
30
|
+
name: string;
|
|
31
|
+
cwd: string;
|
|
32
|
+
/** Разрешённые ветки (glob). Пусто — любая ветка. */
|
|
33
|
+
branch?: string;
|
|
34
|
+
/** Пути/glob-маски, изменение которых запускает задачу. Пусто — любой файл. */
|
|
35
|
+
paths?: string[];
|
|
36
|
+
/** Исключения (glob): изменения только в этих путях игнорируются. */
|
|
37
|
+
ignore?: string[];
|
|
38
|
+
pollSeconds?: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export type GitCheckStatus =
|
|
42
|
+
| "no-repo"
|
|
43
|
+
| "baseline"
|
|
44
|
+
| "no-changes"
|
|
45
|
+
| "branch-mismatch"
|
|
46
|
+
| "ignored"
|
|
47
|
+
| "changed";
|
|
48
|
+
|
|
49
|
+
export interface GitCheckResult {
|
|
50
|
+
status: GitCheckStatus;
|
|
51
|
+
head?: string;
|
|
52
|
+
branch?: string | null;
|
|
53
|
+
from?: string | null;
|
|
54
|
+
files: string[];
|
|
55
|
+
matched: string[];
|
|
56
|
+
message: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export type GitTriggerHandler = (taskName: string, info: GitCheckResult & { cwd: string }) => void | Promise<void>;
|
|
60
|
+
|
|
61
|
+
export type GitRunner = (cwd: string, args: string[]) => Promise<string>;
|
|
62
|
+
|
|
63
|
+
const defaultRunner: GitRunner = (cwd, args) =>
|
|
64
|
+
new Promise((resolve, reject) => {
|
|
65
|
+
execFile(
|
|
66
|
+
"git",
|
|
67
|
+
["-C", cwd, ...args],
|
|
68
|
+
{ timeout: GIT_COMMAND_TIMEOUT_MS, windowsHide: true, maxBuffer: 4 * 1024 * 1024 },
|
|
69
|
+
(err, stdout) => {
|
|
70
|
+
if (err) {
|
|
71
|
+
reject(err);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
resolve(String(stdout ?? ""));
|
|
75
|
+
}
|
|
76
|
+
);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
/** true, если директория существует (иначе git всё равно ответит ошибкой). */
|
|
80
|
+
function directoryExists(dir: string): boolean {
|
|
81
|
+
try {
|
|
82
|
+
return fs.statSync(dir).isDirectory();
|
|
83
|
+
} catch {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Текущий HEAD и ветка; null, если это не git-репозиторий. */
|
|
89
|
+
export async function probeGit(cwd: string, run: GitRunner = defaultRunner): Promise<GitProbe | null> {
|
|
90
|
+
if (!cwd || !directoryExists(cwd)) return null;
|
|
91
|
+
try {
|
|
92
|
+
const head = (await run(cwd, ["rev-parse", "HEAD"])).trim();
|
|
93
|
+
if (!head) return null;
|
|
94
|
+
let branch: string | null = null;
|
|
95
|
+
try {
|
|
96
|
+
const raw = (await run(cwd, ["rev-parse", "--abbrev-ref", "HEAD"])).trim();
|
|
97
|
+
branch = raw && raw !== "HEAD" ? raw : null;
|
|
98
|
+
} catch {
|
|
99
|
+
branch = null;
|
|
100
|
+
}
|
|
101
|
+
return { head, branch };
|
|
102
|
+
} catch {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Файлы, изменённые между коммитами (или в самом коммите, если from пуст). */
|
|
108
|
+
export async function gitChangedFiles(
|
|
109
|
+
cwd: string,
|
|
110
|
+
from: string | null,
|
|
111
|
+
to: string,
|
|
112
|
+
run: GitRunner = defaultRunner
|
|
113
|
+
): Promise<string[]> {
|
|
114
|
+
const args = from
|
|
115
|
+
? ["diff", "--name-only", `${from}..${to}`]
|
|
116
|
+
: ["diff-tree", "--no-commit-id", "--name-only", "-r", to];
|
|
117
|
+
try {
|
|
118
|
+
const out = await run(cwd, args);
|
|
119
|
+
return out
|
|
120
|
+
.split(/\r?\n/)
|
|
121
|
+
.map((line) => line.trim())
|
|
122
|
+
.filter(Boolean);
|
|
123
|
+
} catch {
|
|
124
|
+
return [];
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function branchMatches(branch: string | null, pattern?: string): boolean {
|
|
129
|
+
if (!pattern || !pattern.trim()) return true;
|
|
130
|
+
if (!branch) return false;
|
|
131
|
+
const normalize = (value: string) =>
|
|
132
|
+
process.platform === "win32" ? value.toLowerCase() : value;
|
|
133
|
+
const target = normalize(branch);
|
|
134
|
+
const patterns = pattern
|
|
135
|
+
.split(",")
|
|
136
|
+
.map((item) => item.trim())
|
|
137
|
+
.filter(Boolean);
|
|
138
|
+
if (patterns.length === 0) return true;
|
|
139
|
+
return patterns.some((item) => {
|
|
140
|
+
const source = normalize(item)
|
|
141
|
+
.replace(/[.+^${}()|\\]/g, "\\$&")
|
|
142
|
+
.replace(/\*/g, ".*")
|
|
143
|
+
.replace(/\?/g, ".");
|
|
144
|
+
return new RegExp(`^${source}$`).test(target);
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Проверяет задачу без побочных эффектов (кроме baseline-записи).
|
|
150
|
+
* Используется и менеджером, и dry-run.
|
|
151
|
+
*/
|
|
152
|
+
export async function checkGitTrigger(
|
|
153
|
+
task: GitTriggerTask,
|
|
154
|
+
options: { run?: GitRunner; persist?: boolean } = {}
|
|
155
|
+
): Promise<GitCheckResult> {
|
|
156
|
+
const run = options.run ?? defaultRunner;
|
|
157
|
+
const persist = options.persist !== false;
|
|
158
|
+
const probe = await probeGit(task.cwd, run);
|
|
159
|
+
if (!probe) {
|
|
160
|
+
return {
|
|
161
|
+
status: "no-repo",
|
|
162
|
+
files: [],
|
|
163
|
+
matched: [],
|
|
164
|
+
message: `«${task.cwd}» не git-репозиторий — git-триггер не сработает.`,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const state = getGitState(task.name);
|
|
169
|
+
if (!state) {
|
|
170
|
+
if (persist) setGitState(task.name, probe.head, probe.branch);
|
|
171
|
+
return {
|
|
172
|
+
status: "baseline",
|
|
173
|
+
head: probe.head,
|
|
174
|
+
branch: probe.branch,
|
|
175
|
+
files: [],
|
|
176
|
+
matched: [],
|
|
177
|
+
message: `Запомнен текущий коммит ${probe.head.slice(0, 7)} — задача запустится на следующем изменении.`,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (!branchMatches(probe.branch, task.branch)) {
|
|
182
|
+
return {
|
|
183
|
+
status: "branch-mismatch",
|
|
184
|
+
head: probe.head,
|
|
185
|
+
branch: probe.branch,
|
|
186
|
+
from: state.commitSha,
|
|
187
|
+
files: [],
|
|
188
|
+
matched: [],
|
|
189
|
+
message: `Ветка ${probe.branch ?? "(detached)"} не подходит под фильтр «${task.branch}».`,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (probe.head === state.commitSha) {
|
|
194
|
+
return {
|
|
195
|
+
status: "no-changes",
|
|
196
|
+
head: probe.head,
|
|
197
|
+
branch: probe.branch,
|
|
198
|
+
from: state.commitSha,
|
|
199
|
+
files: [],
|
|
200
|
+
matched: [],
|
|
201
|
+
message: "Новых коммитов нет.",
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const files = await gitChangedFiles(task.cwd, state.commitSha, probe.head, run);
|
|
206
|
+
const matched = filterPaths(files, task.paths, task.ignore);
|
|
207
|
+
|
|
208
|
+
if (matched.length === 0) {
|
|
209
|
+
if (persist) setGitState(task.name, probe.head, probe.branch);
|
|
210
|
+
return {
|
|
211
|
+
status: files.length === 0 ? "no-changes" : "ignored",
|
|
212
|
+
head: probe.head,
|
|
213
|
+
branch: probe.branch,
|
|
214
|
+
from: state.commitSha,
|
|
215
|
+
files,
|
|
216
|
+
matched: [],
|
|
217
|
+
message:
|
|
218
|
+
files.length === 0
|
|
219
|
+
? "Новых коммитов нет."
|
|
220
|
+
: `Изменено файлов: ${files.length}, но ни один не подходит под фильтры.`,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
if (persist) setGitState(task.name, probe.head, probe.branch);
|
|
225
|
+
return {
|
|
226
|
+
status: "changed",
|
|
227
|
+
head: probe.head,
|
|
228
|
+
branch: probe.branch,
|
|
229
|
+
from: state.commitSha,
|
|
230
|
+
files,
|
|
231
|
+
matched,
|
|
232
|
+
message: `Новый коммит ${probe.head.slice(0, 7)}: изменено файлов ${matched.length} (${matched
|
|
233
|
+
.slice(0, 3)
|
|
234
|
+
.join(", ")}${matched.length > 3 ? ", …" : ""}).`,
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function cwdOf(def: TaskDefinition): string {
|
|
239
|
+
const workspacePath = def.workspaceId ? getWorkspace(def.workspaceId)?.path : undefined;
|
|
240
|
+
return workspacePath || def.workingDirectory || def.workdir || "";
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function pollSecondsOf(def: TaskDefinition): number {
|
|
244
|
+
const raw = Number(def.gitPollSeconds ?? GIT_TRIGGER_DEFAULT_POLL_SECONDS);
|
|
245
|
+
if (!Number.isFinite(raw) || raw <= 0) return GIT_TRIGGER_DEFAULT_POLL_SECONDS;
|
|
246
|
+
return Math.max(GIT_TRIGGER_MIN_POLL_SECONDS, Math.floor(raw));
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
interface ManagedGit {
|
|
250
|
+
def: TaskDefinition;
|
|
251
|
+
timer: NodeJS.Timeout;
|
|
252
|
+
busy: boolean;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export class GitTriggerManager {
|
|
256
|
+
private readonly tasks = new Map<string, ManagedGit>();
|
|
257
|
+
private readonly handler: GitTriggerHandler;
|
|
258
|
+
private readonly run?: GitRunner;
|
|
259
|
+
|
|
260
|
+
constructor(handler: GitTriggerHandler, options: { run?: GitRunner } = {}) {
|
|
261
|
+
this.handler = handler;
|
|
262
|
+
this.run = options.run;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
get size(): number {
|
|
266
|
+
return this.tasks.size;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** Перечитывает задачи и пересобирает таймеры. Возвращает число задач. */
|
|
270
|
+
async refresh(): Promise<number> {
|
|
271
|
+
const wanted = new Map<string, TaskDefinition>();
|
|
272
|
+
for (const def of await loadTaskDefinitions()) {
|
|
273
|
+
if (def.triggerType !== "git") continue;
|
|
274
|
+
if (!cwdOf(def)) continue;
|
|
275
|
+
wanted.set(def.name.toLowerCase(), def);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
for (const [key, managed] of [...this.tasks]) {
|
|
279
|
+
const next = wanted.get(key);
|
|
280
|
+
if (!next || pollSecondsOf(next) !== pollSecondsOf(managed.def)) {
|
|
281
|
+
clearInterval(managed.timer);
|
|
282
|
+
this.tasks.delete(key);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
for (const [key, def] of wanted) {
|
|
287
|
+
const existing = this.tasks.get(key);
|
|
288
|
+
if (existing) {
|
|
289
|
+
existing.def = def;
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
const timer = setInterval(() => void this.poll(key), pollSecondsOf(def) * 1000);
|
|
293
|
+
timer.unref?.();
|
|
294
|
+
this.tasks.set(key, { def, timer, busy: false });
|
|
295
|
+
// Первый опрос — сразу: он запоминает baseline, не запуская задачу.
|
|
296
|
+
void this.poll(key);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
return this.tasks.size;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Ручная проверка одной задачи (dry-run, тесты). */
|
|
303
|
+
async check(taskName: string): Promise<GitCheckResult | null> {
|
|
304
|
+
const managed = this.tasks.get(taskName.toLowerCase());
|
|
305
|
+
if (managed) {
|
|
306
|
+
return checkGitTrigger(this.taskSpec(managed.def), { run: this.run });
|
|
307
|
+
}
|
|
308
|
+
const def = (await loadTaskDefinitions()).find(
|
|
309
|
+
(d) => d.triggerType === "git" && d.name.toLowerCase() === taskName.toLowerCase()
|
|
310
|
+
);
|
|
311
|
+
if (!def) return null;
|
|
312
|
+
return checkGitTrigger(this.taskSpec(def), { run: this.run });
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
private taskSpec(def: TaskDefinition): GitTriggerTask {
|
|
316
|
+
return {
|
|
317
|
+
name: def.name,
|
|
318
|
+
cwd: cwdOf(def),
|
|
319
|
+
branch: def.gitBranch,
|
|
320
|
+
paths: def.gitPaths,
|
|
321
|
+
ignore: def.gitIgnore,
|
|
322
|
+
pollSeconds: pollSecondsOf(def),
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
private async poll(key: string): Promise<void> {
|
|
327
|
+
const managed = this.tasks.get(key);
|
|
328
|
+
if (!managed || managed.busy) return;
|
|
329
|
+
managed.busy = true;
|
|
330
|
+
try {
|
|
331
|
+
const result = await checkGitTrigger(this.taskSpec(managed.def), { run: this.run });
|
|
332
|
+
if (result.status === "changed") {
|
|
333
|
+
await this.handler(managed.def.name, { ...result, cwd: cwdOf(managed.def) });
|
|
334
|
+
}
|
|
335
|
+
} catch (err: any) {
|
|
336
|
+
console.error(
|
|
337
|
+
`[windows-scheduler] git-триггер «${managed.def.name}»: ${
|
|
338
|
+
err instanceof Error ? err.message : String(err)
|
|
339
|
+
}`
|
|
340
|
+
);
|
|
341
|
+
} finally {
|
|
342
|
+
managed.busy = false;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async stop(): Promise<void> {
|
|
347
|
+
for (const managed of this.tasks.values()) clearInterval(managed.timer);
|
|
348
|
+
this.tasks.clear();
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** Забывает состояние (при удалении/пересоздании задачи). */
|
|
352
|
+
forget(taskName: string): void {
|
|
353
|
+
deleteGitState(taskName);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Задачи с git-триггером (для dry-run и вида задач). */
|
|
358
|
+
export async function gitTriggerTasks(): Promise<{ name: string; cwd: string }[]> {
|
|
359
|
+
return (await loadTaskDefinitions())
|
|
360
|
+
.filter((def) => def.triggerType === "git" && cwdOf(def))
|
|
361
|
+
.map((def) => ({ name: def.name, cwd: cwdOf(def) }));
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** Нормализует путь рабочей директории (для сравнения в тестах). */
|
|
365
|
+
export function normalizeGitCwd(cwd: string): string {
|
|
366
|
+
return path.resolve(cwd);
|
|
367
|
+
}
|
package/src/core/glob.ts
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Glob-маски без внешних зависимостей (Спринт 27).
|
|
3
|
+
*
|
|
4
|
+
* Поддерживается подмножество, достаточное для фильтров файловых и git-триггеров:
|
|
5
|
+
* * — любые символы, кроме "/"
|
|
6
|
+
* ** — любые символы, включая "/" (в т.ч. ноль сегментов: `src/**\/x.ts`)
|
|
7
|
+
* ? — один символ, кроме "/"
|
|
8
|
+
* [abc] — класс символов, [a-z] — диапазон, [!abc] / [^abc] — отрицание
|
|
9
|
+
* {a,b} — альтернативы (в т.ч. вложенные)
|
|
10
|
+
* !pattern — отрицание маски (для ignore-списков, обрабатывается matchesAnyGlob)
|
|
11
|
+
*
|
|
12
|
+
* Пути нормализуются к POSIX-виду ("\" → "/"), ведущий "./" отбрасывается.
|
|
13
|
+
* На Windows сравнение регистронезависимое, на остальных платформах — точное.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const WINDOWS = process.platform === "win32";
|
|
17
|
+
|
|
18
|
+
/** Нормализует путь или маску: "/" как разделитель, без ведущего "./". */
|
|
19
|
+
export function normalizePath(value: unknown): string {
|
|
20
|
+
let text = String(value ?? "").trim().replace(/\\/g, "/");
|
|
21
|
+
if (!text) return "";
|
|
22
|
+
while (text.startsWith("./")) text = text.slice(2);
|
|
23
|
+
// Схлопываем повторные слэши, но не трогаем начало (UNC уже приведён к "/").
|
|
24
|
+
text = text.replace(/\/{2,}/g, "/");
|
|
25
|
+
return text;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Экранирует символ регулярного выражения. */
|
|
29
|
+
function escapeRe(ch: string): string {
|
|
30
|
+
return /[.+^$()|[\]\\]/.test(ch) ? `\\${ch}` : ch;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Преобразует glob-маску в регулярное выражение.
|
|
35
|
+
* Маска предполагается полной (от начала до конца строки).
|
|
36
|
+
*/
|
|
37
|
+
export function globToRegExp(pattern: unknown): RegExp {
|
|
38
|
+
const source = normalizePath(pattern);
|
|
39
|
+
let out = "^";
|
|
40
|
+
|
|
41
|
+
const compile = (text: string): string => {
|
|
42
|
+
let result = "";
|
|
43
|
+
let j = 0;
|
|
44
|
+
while (j < text.length) {
|
|
45
|
+
const ch = text[j];
|
|
46
|
+
if (ch === "*") {
|
|
47
|
+
if (text[j + 1] === "*") {
|
|
48
|
+
const isSegment = (j === 0 || text[j - 1] === "/") && text[j + 2] === "/";
|
|
49
|
+
if (isSegment) {
|
|
50
|
+
// "**/" — ноль или более сегментов пути.
|
|
51
|
+
result += "(?:[^/]+/)*";
|
|
52
|
+
j += 3;
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (j > 0 && text[j - 1] === "/") {
|
|
56
|
+
result += "(?:[^/]+/)*[^/]*";
|
|
57
|
+
} else {
|
|
58
|
+
result += ".*";
|
|
59
|
+
}
|
|
60
|
+
j += 2;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
result += "[^/]*";
|
|
64
|
+
j += 1;
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (ch === "?") {
|
|
68
|
+
result += "[^/]";
|
|
69
|
+
j += 1;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (ch === "[") {
|
|
73
|
+
const close = text.indexOf("]", j + 1);
|
|
74
|
+
if (close === -1) {
|
|
75
|
+
result += "\\[";
|
|
76
|
+
j += 1;
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
let body = text.slice(j + 1, close);
|
|
80
|
+
if (body.startsWith("!")) body = `^${body.slice(1)}`;
|
|
81
|
+
else if (body.startsWith("^")) body = `\\${body}`;
|
|
82
|
+
result += `[${body}]`;
|
|
83
|
+
j = close + 1;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
if (ch === "{") {
|
|
87
|
+
// Находим парную закрывающую скобку.
|
|
88
|
+
let depth = 0;
|
|
89
|
+
let end = -1;
|
|
90
|
+
for (let k = j; k < text.length; k++) {
|
|
91
|
+
if (text[k] === "{") depth++;
|
|
92
|
+
else if (text[k] === "}") {
|
|
93
|
+
depth--;
|
|
94
|
+
if (depth === 0) {
|
|
95
|
+
end = k;
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (end === -1) {
|
|
101
|
+
result += "\\{";
|
|
102
|
+
j += 1;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
const body = text.slice(j + 1, end);
|
|
106
|
+
const parts = splitAlternatives(body);
|
|
107
|
+
result += `(?:${parts.map((part) => compile(part)).join("|")})`;
|
|
108
|
+
j = end + 1;
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (ch === "}") {
|
|
112
|
+
result += "\\}";
|
|
113
|
+
j += 1;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
result += escapeRe(ch);
|
|
117
|
+
j += 1;
|
|
118
|
+
}
|
|
119
|
+
return result;
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
out += compile(source);
|
|
123
|
+
out += "$";
|
|
124
|
+
return new RegExp(out, WINDOWS ? "i" : "");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Разбивает "{a,b,c}" по запятым верхнего уровня. */
|
|
128
|
+
function splitAlternatives(body: string): string[] {
|
|
129
|
+
const parts: string[] = [];
|
|
130
|
+
let depth = 0;
|
|
131
|
+
let current = "";
|
|
132
|
+
for (const ch of body) {
|
|
133
|
+
if (ch === "{") depth++;
|
|
134
|
+
if (ch === "}") depth--;
|
|
135
|
+
if (ch === "," && depth === 0) {
|
|
136
|
+
parts.push(current);
|
|
137
|
+
current = "";
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
current += ch;
|
|
141
|
+
}
|
|
142
|
+
parts.push(current);
|
|
143
|
+
return parts;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** true, если путь матчится хотя бы одной маске. */
|
|
147
|
+
export function matchesGlob(path: unknown, pattern: unknown): boolean {
|
|
148
|
+
const candidate = normalizePath(path);
|
|
149
|
+
if (!candidate) return false;
|
|
150
|
+
const re = globToRegExp(pattern);
|
|
151
|
+
if (re.test(candidate)) return true;
|
|
152
|
+
// Маска каталога "src/**" должна матчить и сам "src".
|
|
153
|
+
const raw = normalizePath(pattern).replace(/\/$/, "");
|
|
154
|
+
if (raw.endsWith("/**")) {
|
|
155
|
+
return globToRegExp(raw.slice(0, -3)).test(candidate);
|
|
156
|
+
}
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Проверяет путь по списку масок с поддержкой отрицаний.
|
|
162
|
+
* `!pattern` исключает совпадение; порядок важен (последнее правило побеждает).
|
|
163
|
+
*/
|
|
164
|
+
export function matchesAnyGlob(path: unknown, patterns: unknown): boolean {
|
|
165
|
+
if (!Array.isArray(patterns)) return false;
|
|
166
|
+
let matched = false;
|
|
167
|
+
for (const pattern of patterns) {
|
|
168
|
+
const text = String(pattern ?? "").trim();
|
|
169
|
+
if (!text) continue;
|
|
170
|
+
if (text.startsWith("!")) {
|
|
171
|
+
if (matchesGlob(path, text.slice(1))) matched = false;
|
|
172
|
+
} else if (matchesGlob(path, text)) {
|
|
173
|
+
matched = true;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return matched;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** true, если путь не попал ни в одну маску из ignore-списка (или список пуст). */
|
|
180
|
+
export function isIgnored(path: unknown, ignore: unknown): boolean {
|
|
181
|
+
if (!Array.isArray(ignore) || ignore.length === 0) return false;
|
|
182
|
+
const candidate = normalizePath(path);
|
|
183
|
+
for (const pattern of ignore) {
|
|
184
|
+
const text = String(pattern ?? "").trim();
|
|
185
|
+
if (!text) continue;
|
|
186
|
+
if (text.startsWith("!")) continue;
|
|
187
|
+
if (matchesGlob(candidate, text)) return true;
|
|
188
|
+
}
|
|
189
|
+
return false;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Отбирает файлы по include-маскам с учётом ignore-списка.
|
|
194
|
+
* Пустой include-список означает «любой файл».
|
|
195
|
+
*/
|
|
196
|
+
export function filterPaths(
|
|
197
|
+
files: string[],
|
|
198
|
+
include?: string[] | null,
|
|
199
|
+
ignore?: string[] | null
|
|
200
|
+
): string[] {
|
|
201
|
+
const list = Array.isArray(files) ? files : [];
|
|
202
|
+
const includes = Array.isArray(include) ? include.filter(Boolean) : [];
|
|
203
|
+
return list.filter((file) => {
|
|
204
|
+
const path = normalizePath(file);
|
|
205
|
+
if (!path) return false;
|
|
206
|
+
if (isIgnored(path, ignore)) return false;
|
|
207
|
+
if (includes.length === 0) return true;
|
|
208
|
+
return matchesAnyGlob(path, includes);
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Относительный путь файла от каталога; null, если файл вне каталога. */
|
|
213
|
+
export function relativeTo(base: unknown, file: unknown): string | null {
|
|
214
|
+
const root = normalizePath(base).replace(/\/$/, "");
|
|
215
|
+
const target = normalizePath(file);
|
|
216
|
+
if (!root) return target;
|
|
217
|
+
if (target === root) return "";
|
|
218
|
+
const prefix = root.endsWith("/") ? root : `${root}/`;
|
|
219
|
+
if (WINDOWS) {
|
|
220
|
+
if (target.toLowerCase().startsWith(prefix.toLowerCase())) {
|
|
221
|
+
return target.slice(prefix.length);
|
|
222
|
+
}
|
|
223
|
+
return null;
|
|
224
|
+
}
|
|
225
|
+
return target.startsWith(prefix) ? target.slice(prefix.length) : null;
|
|
226
|
+
}
|
package/src/core/ps-wrapper.ts
CHANGED
|
@@ -643,6 +643,13 @@ export async function writeWrapperCmd(
|
|
|
643
643
|
if (scheduleGate.notAfter?.trim()) {
|
|
644
644
|
gateArgs.push(`--not-after ${scheduleGate.notAfter.trim()}`);
|
|
645
645
|
}
|
|
646
|
+
// Спринт 27: дни недели и политика окна.
|
|
647
|
+
if (Array.isArray(scheduleGate.days) && scheduleGate.days.length > 0) {
|
|
648
|
+
gateArgs.push(`--days ${scheduleGate.days.join(",")}`);
|
|
649
|
+
}
|
|
650
|
+
if (scheduleGate.windowPolicy) {
|
|
651
|
+
gateArgs.push(`--window-policy ${scheduleGate.windowPolicy}`);
|
|
652
|
+
}
|
|
646
653
|
if (scheduleGate.deferFile?.trim()) {
|
|
647
654
|
gateArgs.push(`--defer-file "${scheduleGate.deferFile.trim()}"`);
|
|
648
655
|
}
|