Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Make the end file name optional #312

Merged
merged 1 commit into from
Jul 3, 2024
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
66 changes: 38 additions & 28 deletions src/FileInjector/FileInjector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,19 @@ import { is } from 'unist-util-is';
import { remove } from 'unist-util-remove';
import { visit } from 'unist-util-visit';
import { fileURLToPath } from 'url';
import { VFile } from 'vfile';
import type { VFile } from 'vfile';

import type { BufferEncoding, FileSystemAdapter, PathLike } from '../FileSystemAdapter/FileSystemAdapter.js';
import { fileType } from '../util/fileType.mjs';
import { type InjectInfo, parseHash } from '../util/hash.js';
import { isDefined } from '../util/isDefined.js';
import { dirToUrl, parseRelativeUrl, pathToUrl, relativePath, type RelURL } from '../util/url_helper.js';
import { toError, toString } from './utils.js';
import { type FileData, isVFileEx, type VFileEx } from './VFileEx.js';
import { type FileData, isVFileEx, VFileEx } from './VFileEx.js';

type Node = Root | RootContent;

const injectDirectiveRegExp = /^[ \t]*<!---?\s*@@inject(?<type>|-start|-end|-code):\s*(?<file>.*?)-?-->$/;
const injectDirectiveRegExp = /^[ \t]*<!--+\s*@@inject(?<type>|-start|-end|-code)[:\s]\s*(?<file>.*?)-+->$/;

const directiveRegExp = /^[ \t]*<!---?\s*@@inject(\b|-)/;

Expand Down Expand Up @@ -158,6 +158,8 @@ export interface ProcessFileResult {
file: VFileEx;
/** had injection errors? */
hasErrors: boolean;
/** had injection warnings? */
hasMessages: boolean;
/** file was written */
written: boolean;
/**
Expand Down Expand Up @@ -207,6 +209,7 @@ async function processFileInjections(
file,
injectionsFound: false,
hasErrors: false,
hasMessages: false,
written: false,
hasChanged: false,
skipped: false,
Expand All @@ -225,12 +228,14 @@ async function processFileInjections(
}
return processFileResult;
}
const hasErrors = result.messages.length > 0;
const hasErrors = result.messages.filter((m) => m.fatal).length > 0;
const hasMessages = result.messages.filter((m) => !m.fatal).length > 0;
const resultAsString = extractContent(result);
const resultContent = fixContentLineEndings(resultAsString, lineEnding, hasEofNewLine(content));
const hasChanged = content !== resultContent;
processFileResult.hasChanged = hasChanged;
processFileResult.hasErrors = hasErrors;
processFileResult.hasMessages = hasMessages;
const stale = hasChanged || !!options.outputDir;
if (stale) {
if ((!hasErrors || options.writeOnError) && !options.dryRun) {
Expand Down Expand Up @@ -329,7 +334,7 @@ async function processFileInjections(
const dFile = directive.file;
const directiveFileUrl = dFile.toUrl(fileUrl);
options.verbose && stderr.write(`\n ${gray(dFile.href)}`);
const root = await readAndParseCodeFile(directiveFileUrl);
const root = await readAndParseCodeFile(directiveFileUrl, directive);
return injectContent(directive, root);
}

Expand Down Expand Up @@ -357,7 +362,7 @@ async function processFileInjections(
parent.children.splice(index, 1, start, ...root.children, end);
}

async function readAndParseCodeFile(fileName: URL): Promise<ParseResult> {
async function readAndParseCodeFile(fileName: URL, directive: DirectiveNode): Promise<ParseResult> {
const info = parseHash(fileName);
const lang = info.lang;
const lines = info.lines;
Expand All @@ -371,7 +376,7 @@ async function processFileInjections(
};
} catch (e) {
const err = toError(e);
file.message(err.message);
file.error(err.message, directive.node.position);
return { root: errorToComment(err), info };
}
}
Expand Down Expand Up @@ -560,7 +565,7 @@ interface DirectivePair {
type DirectiveType = 'start' | 'end' | 'code';
interface Directive {
type: DirectiveType;
file: RelURL;
file: RelURL | undefined;
}

interface DirectiveNode extends Partial<Directive> {
Expand All @@ -577,11 +582,11 @@ const startTypes: Record<DirectiveType, boolean> = {
function findInjectionPairs(nodes: DirectiveNode[], vfile: VFileEx): DirectivePair[] {
function validate(n: DirectiveNode): n is Required<DirectiveNode> {
if (!n.type) {
vfile.message('Unable to parse @@inject directive.', n.node.position);
vfile.error('Unable to parse @@inject directive.', n.node.position);
return false;
}
if (!n.file?.href) {
vfile.message('Missing injection filename.', n.node.position);
if (!n.file?.href && n.type !== 'end') {
vfile.error('Missing injection filename.', n.node.position);
return false;
}
return true;
Expand All @@ -591,28 +596,32 @@ function findInjectionPairs(nodes: DirectiveNode[], vfile: VFileEx): DirectivePa

const pairs: DirectivePair[] = [];
let last: DirectiveNode | undefined = undefined;
for (const n of dnp.reverse()) {

for (const n of dnp) {
if (startTypes[n.type]) {
if (last?.file && !refersToTheSameFile(last.file, n.file)) {
vfile.message(`Unmatched @@inject-end "${last.file}" matching with "${n.file}"`, last.node.position);
pairs.push({ end: last });
if (last) {
pairs.push({ start: last });
}
pairs.push({ start: n, end: last });
last = undefined;
last = n;
continue;
}
if (last) {
vfile.message(`Unmatched @@inject-end "${last.file || ''}"`, last.node.position);
if (!last) {
vfile.error(`Unmatched @@inject-end${n.file ? ` "${n.file}"` : ''}`, n.node.position);
pairs.push({ end: last });
continue;
}
last = n;
if (!refersToTheSameFile(last.file, n.file)) {
vfile.info(`@@inject-end${n.file ? ` "${n.file}"` : ''} matching with "${last.file}"`, n.node.position);
}
pairs.push({ start: last, end: n });
last = undefined;
}

if (last) {
vfile.message(`Unmatched @@inject-end "${last.file || ''}"`, last.node.position);
pairs.push({ end: last });
pairs.push({ start: last });
}

return pairs.reverse();
return pairs;
}

function parseDirectiveNode(node: Html): Directive | undefined {
Expand All @@ -623,9 +632,10 @@ function parseDirective(html: string): Directive | undefined {
const m = html.match(injectDirectiveRegExp);
if (!m || !m.groups) return undefined;

const file = parseRelativeUrl(m.groups['file']);
const filePath = m.groups['file'].trim();
const file = (filePath && parseRelativeUrl(filePath)) || undefined;
const isEnd = m.groups['type'] === '-end';
const isCode = (!isEnd && !file.pathname.toLowerCase().endsWith('.md')) || m.groups['type'] === '-code';
const isCode = (!isEnd && !file?.pathname.toLowerCase().endsWith('.md')) || m.groups['type'] === '-code';

const d: Directive = {
type: isEnd ? 'end' : isCode ? 'code' : 'start',
Expand Down Expand Up @@ -656,7 +666,7 @@ async function readFile(fs: FileSystemAdapter, path: URL, encoding: BufferEncodi
fileUrl: path,
};
// use path.pathname because Vfile blows up if it isn't a file: url.
const file = new VFile({ path: path.pathname, value, data });
const file = new VFileEx(value, data);
assert(isVFileEx(file));
return file;
}
Expand Down Expand Up @@ -718,8 +728,8 @@ function extractLines(content: string, lines: [number, number] | undefined): str
return cLines.slice(lines[0] - 1, lines[1]).join('\n');
}

function refersToTheSameFile(a: RelURL | URL, b: RelURL | URL): boolean {
return a.pathname === b.pathname && a.search === b.search;
function refersToTheSameFile(a: RelURL | URL | undefined, b: RelURL | URL | undefined): boolean {
return a === b || (a && !b) || a?.pathname === b?.pathname;
}

function initParser() {
Expand Down
22 changes: 19 additions & 3 deletions src/FileInjector/VFileEx.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,34 @@
import { type Data as VFileData, VFile } from 'vfile';
import type { Data as VFileData, MessageOptions as VFileMessageOptions } from 'vfile';
import { VFile } from 'vfile';

import type { BufferEncoding } from '../FileSystemAdapter/FileSystemAdapter.js';

export type MessageOptions = VFileMessageOptions['place'];

export interface FileData extends VFileData {
encoding: BufferEncoding;
fileUrl: URL;
cwdUrl?: URL;
hasInjections?: boolean;
}

export interface VFileEx extends VFile {
export class VFileEx extends VFile {
readonly fileUrl: URL;
data: FileData;

constructor(value: string, data: FileData) {
super({ path: data.fileUrl.pathname, value, data });
this.fileUrl = data.fileUrl;
this.data = data;
}

error(reason: string, place?: MessageOptions): ReturnType<VFile['message']> {
const msg = this.message(reason, place);
msg.fatal = true;
return msg;
}
}

export function isVFileEx(file: VFile | VFileEx): file is VFileEx {
return !!file.data.fileUrl;
return file instanceof VFileEx;
}
3 changes: 2 additions & 1 deletion src/app.mts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { promises as fs } from 'node:fs';
import { fileURLToPath } from 'node:url';

import chalk from 'chalk';
import { Command, Option as CommanderOption, program as defaultCommand } from 'commander';
import * as path from 'path';

Expand Down Expand Up @@ -63,7 +64,7 @@ export async function app(program = defaultCommand): Promise<Command> {
const option = fixOptions(optionsCli);
const result = await processGlobs(files, option);
const showSummary = (!optionsCli.silent && !!result.numberOfFiles) || optionsCli.summary === true;
showSummary && console.error(formatSummary(result));
showSummary && console.error(chalk.white(formatSummary(result)));
if (!result.numberOfFiles && optionsCli.mustFindFiles) {
program.error('No Markdown files found.');
}
Expand Down
8 changes: 4 additions & 4 deletions src/processor/process.mts
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ export async function processGlobs(globs: string[], options: Options): Promise<R
result.numberOfFilesWritten += r.written ? 1 : 0;
result.numberOfFilesUpdated += r.hasChanged ? 1 : 0;
result.numberOfFilesSkipped += r.skipped ? 1 : 0;
if (r.hasErrors) {
result.errorCount += 1;
result.filesWithErrors.push(file);
if (r.hasErrors || r.hasMessages) {
result.errorCount += r.hasErrors ? 1 : 0;
r.hasErrors && result.filesWithErrors.push(file);
console.error(reportFileErrors(r.file));
if (options.stopOnErrors ?? true) break;
if (r.hasErrors && (options.stopOnErrors ?? true)) break;
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/processor/reportFileErrors.mts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { VFile } from 'vfile';
import { reporter } from 'vfile-reporter';

export function reportFileErrors(file: VFile): string {
const hasErrors = file.messages.length > 0;
const hasMessages = file.messages.length > 0;

return (hasErrors && reporter(file)) || '';
return (hasMessages && reporter(file)) || '';
}
Loading