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
10 changes: 7 additions & 3 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@
"dependencies": {
"ajv": "^8.20.0",
"ajv-formats": "^3.0.1",
"chokidar": "^5.0.0",
"chokidar": "^6.0.0",
"commander": "^15.0.0",
"fast-glob": "^3.3.3",
"gray-matter": "^4.0.3",
Expand Down
151 changes: 98 additions & 53 deletions src/commands/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,9 @@ function ofKind<K extends ValidationIssue['kind']>(result: ValidationResult, kin
return result.issues.filter((issue): issue is Extract<ValidationIssue, { kind: K }> => issue.kind === kind);
}

export async function validate(
context: SpaceContext,
options: { json?: boolean } & ValidateSpaceOptions = {},
): Promise<number> {
type ValidateCommandOptions = { json?: boolean } & ValidateSpaceOptions;

export async function validate(context: SpaceContext, options: ValidateCommandOptions = {}): Promise<number> {
const result = await validateSpace(context, options);
const errorCount = result.issues.filter((issue) => issue.severity === 'error').length;

Expand Down Expand Up @@ -192,7 +191,90 @@ export async function validate(
return errorCount === 0 ? 0 : 1;
}

export async function watchValidate(context: SpaceContext): Promise<never> {
interface WatchSessionDeps {
read?: typeof readSpace;
refresh?: typeof refreshReadResult;
runValidate?: typeof validate;
reloadContext?: (spaceName: string) => SpaceContext;
onBeforeRevalidate?: (filePath: string, action: string) => void;
}

/**
* Serialized state machine for `watchValidate`: holds the latest `SpaceContext` and
* `ReadSpaceResult`, forwards CLI validate options on every run, and queues change events
* so concurrent filesystem events (e.g. rename = unlink + add) cannot race on `refreshReadResult`.
*/
export function createWatchSession(
context: SpaceContext,
options: ValidateCommandOptions = {},
deps: WatchSessionDeps = {},
) {
const read = deps.read ?? readSpace;
const refresh = deps.refresh ?? refreshReadResult;
const runValidate = deps.runValidate ?? validate;
const reloadContext = deps.reloadContext ?? ((name) => createSpaceContext(name, loadConfig()));
const onBeforeRevalidate = deps.onBeforeRevalidate;

let exitCode = 0;
let currentContext = context;
let currentReadResult: ReadSpaceResult | undefined;
const resolvedSpacePath = resolve(context.space.path);

const innerValidate = async (changedSpaceFile?: string) => {
try {
if (changedSpaceFile && currentReadResult) {
currentReadResult = await refresh(currentContext, currentReadResult, [changedSpaceFile]);
} else {
currentReadResult = await read(currentContext);
}
exitCode = await runValidate(currentContext, { ...options, readResult: currentReadResult });
} catch (error) {
console.error(`❌ Error during validation: ${error instanceof Error ? error.message : String(error)}`);
exitCode = 2;
}
};

let queue = Promise.resolve();
const enqueue = (task: () => Promise<void>): Promise<void> => {
queue = queue.then(task, task);
return queue;
};

const runInitial = () => enqueue(() => innerValidate());

const handleChange = (filePath: string, action: string) =>
enqueue(async () => {
onBeforeRevalidate?.(filePath, action);
const absFile = resolve(filePath);
const relToSpace = relative(resolvedSpacePath, absFile);
const isInSpace = relToSpace !== '' && !relToSpace.startsWith('..') && !isAbsolute(relToSpace);
if (isInSpace) {
await innerValidate(relToSpace.replace(/\\/g, '/'));
} else if (absFile === resolvedSpacePath) {
// Single-file space (space_on_a_page): re-read without reloading config/schema.
await innerValidate();
} else {
// Config or schema changed: rebuild context and do a full read.
try {
currentContext = reloadContext(context.space.name);
} catch (error) {
console.error(`❌ Error reloading config/schema: ${error instanceof Error ? error.message : String(error)}`);
exitCode = 2;
return;
}
currentReadResult = undefined;
await innerValidate();
}
});

return {
runInitial,
handleChange,
getExitCode: () => exitCode,
};
}

export async function watchValidate(context: SpaceContext, options: ValidateCommandOptions = {}): Promise<never> {
const spacePath = context.space.path;
const schemaPath = context.resolvedSchemaPath;
const configFiles = Array.from(getConfigSourceFiles());
Expand All @@ -216,25 +298,13 @@ export async function watchValidate(context: SpaceContext): Promise<never> {

process.stdout.write('\x1b[s');

let exitCode = 0;
let currentContext = context;
let currentReadResult: ReadSpaceResult | undefined;
const resolvedSpacePath = resolve(spacePath);

const innerValidate = async (changedSpaceFile?: string) => {
try {
if (changedSpaceFile && currentReadResult) {
currentReadResult = await refreshReadResult(currentContext, currentReadResult, [changedSpaceFile]);
} else {
currentReadResult = await readSpace(currentContext);
}
exitCode = await validate(currentContext, { readResult: currentReadResult });
} catch (error) {
console.error(`❌ Error during validation: ${error instanceof Error ? error.message : String(error)}`);
exitCode = 2;
}
};
await innerValidate();
const session = createWatchSession(context, options, {
onBeforeRevalidate: (filePath, action) => {
process.stdout.write('\x1b[u\x1b[0J');
console.log(`🔄 ${filePath} ${action}, re-validating...\n`);
},
});
await session.runInitial();

const watchPaths = [...configFiles, ...schemaDirs, spacePath];

Expand All @@ -246,34 +316,9 @@ export async function watchValidate(context: SpaceContext): Promise<never> {
},
});

const handleFileChange = async (filePath: string, action: string) => {
process.stdout.write('\x1b[u\x1b[0J');
console.log(`🔄 ${filePath} ${action}, re-validating...\n`);
const absFile = resolve(filePath);
const relToSpace = relative(resolvedSpacePath, absFile);
const isInSpace = relToSpace !== '' && !relToSpace.startsWith('..') && !isAbsolute(relToSpace);
if (isInSpace) {
await innerValidate(relToSpace.replace(/\\/g, '/'));
} else if (absFile === resolvedSpacePath) {
// Single-file space (space_on_a_page): re-read without reloading config/schema.
await innerValidate();
} else {
// Config or schema changed: rebuild context and do a full read.
try {
currentContext = createSpaceContext(context.space.name, loadConfig());
} catch (error) {
console.error(`❌ Error reloading config/schema: ${error instanceof Error ? error.message : String(error)}`);
exitCode = 2;
return;
}
currentReadResult = undefined;
await innerValidate();
}
};

watcher.on('add', (path) => handleFileChange(path, 'added'));
watcher.on('change', (path) => handleFileChange(path, 'changed'));
watcher.on('unlink', (path) => handleFileChange(path, 'removed'));
watcher.on('add', (path) => void session.handleChange(path, 'added'));
watcher.on('change', (path) => void session.handleChange(path, 'changed'));
watcher.on('unlink', (path) => void session.handleChange(path, 'removed'));
watcher.on('error', (error) => {
console.error(`Watcher error: ${error}`);
});
Expand All @@ -282,7 +327,7 @@ export async function watchValidate(context: SpaceContext): Promise<never> {
process.on('SIGINT', () => {
console.log('\n\n👋 Stopping watch mode...');
watcher.close();
process.exit(exitCode);
process.exit(session.getExitCode());
});
process.on('uncaughtException', reject);
});
Expand Down
11 changes: 6 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,14 +118,15 @@ addValidationOptions(
),
).action(async (spaceName, options) => {
const context = buildSpaceContext(spaceName);
const validateOptions = {
...commonValidateCliOptions(options),
depth: options.depth,
};
if (options.watch) {
await watchValidate(context);
await watchValidate(context, validateOptions);
} else {
// exitCode rather than process.exit(): exiting straight away can cut off large piped output
process.exitCode = await validate(context, {
...commonValidateCliOptions(options),
depth: options.depth,
});
process.exitCode = await validate(context, validateOptions);
}
});

Expand Down
1 change: 1 addition & 0 deletions src/plugins/markdown/read-space.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ export async function readSpaceDirectory(
const abs = resolve(directory, file);
const rel = relative(directory, abs);
if (rel.startsWith('..') || isAbsolute(rel)) return false;
if (rel.split(/[\\/]/).some((segment) => segment.startsWith('.'))) return false;
return existsSync(abs) && statSync(abs).isFile();
})
: await fg('**/*.md', { cwd: directory, followSymbolicLinks: true });
Expand Down
5 changes: 4 additions & 1 deletion src/plugins/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ export type PluginContext = SpaceContext & {
persistConfig?: (updates: Record<string, string>) => void;
/** Validate the whole space and return every issue found, of every severity. */
validate?: (
options?: Pick<ValidateSpaceOptions, 'includeGated' | 'ruleFilter' | 'semantic' | 'depth'>,
options?: Pick<
ValidateSpaceOptions,
'includeGated' | 'ruleFilter' | 'semantic' | 'depth' | 'cacheMode' | 'cacheDir'
>,
) => Promise<ValidationIssue[]>;
/** The graph being rendered, in the space graph format. */
exportGraph?: () => SpaceGraphData;
Expand Down
21 changes: 21 additions & 0 deletions tests/read/refresh-read-result.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,4 +330,25 @@ describe('refreshReadResult', () => {
expect(refreshed.nodes).toHaveLength(2);
await expectMatchesFullRead(context, refreshed);
});

test('ignores dot-prefixed paths during partial refresh to match full read', async () => {
const { spaceDir, context } = makeTempSpace({
'vision.md': '---\ntype: vision\ntitle: Our Vision\nstatus: active\n---\n',
});
const initial = await readSpace(context);

for (const rel of ['.obsidian/note.md', '.trash/old.md', 'sub/.hidden.md']) {
const full = join(spaceDir, rel);
mkdirSync(join(full, '..'), { recursive: true });
writeFileSync(full, '---\ntype: vision\ntitle: Hidden\nstatus: active\n---\n', 'utf-8');
}

const refreshed = await refreshReadResult(context, initial, [
'.obsidian/note.md',
'.trash/old.md',
'sub/.hidden.md',
]);
expect(refreshed.nodes.map((n) => String(n.id))).toEqual(['vision.md']);
await expectMatchesFullRead(context, refreshed);
});
});
Loading