Skip to content

Commit

Permalink
Merge pull request #95 from zakhenry/jci-aws/non-zero-exit-with-verify
Browse files Browse the repository at this point in the history
  • Loading branch information
zakhenry authored Sep 7, 2022
2 parents b0a0156 + e47aeea commit cb8cacc
Show file tree
Hide file tree
Showing 9 changed files with 90 additions and 138 deletions.
53 changes: 35 additions & 18 deletions src/embedme.lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ enum CommentFamily {
DOUBLE_HYPHENS,
}

type Replacement = {
text: string;
error: boolean;
};

const languageMap: Record<CommentFamily, SupportedFileType[]> = {
[CommentFamily.NONE]: [SupportedFileType.JSON],
[CommentFamily.C]: [
Expand Down Expand Up @@ -193,7 +198,7 @@ function getReplacement(
startLineNumber: number,
ignoreNext: boolean,
commentEmbedOverrideFilepath?: string,
): string {
): Replacement {
/**
* Re-declare the log class, prefixing each snippet with the file and line number
* Note that we couldn't have derived the line count in the parent regex matcher, as we don't yet know how long the
Expand All @@ -212,7 +217,7 @@ function getReplacement(

if (ignoreNext) {
log({ returnSnippet: substr }, chalk => chalk.blue(`"Ignore next" comment detected, skipping code block...`));
return substr;
return { text: substr, error: false };
}

let commentedFilename: string | null;
Expand All @@ -221,14 +226,14 @@ function getReplacement(
} else {
if (!codeExtension) {
log({ returnSnippet: substr }, chalk => chalk.blue(`No code extension detected, skipping code block...`));
return substr;
return { text: substr, error: false };
}

if (!firstLine) {
log({ returnSnippet: substr }, chalk =>
chalk.blue(`Code block is empty & no preceding embedme comment, skipping...`),
);
return substr;
return { text: substr, error: false };
}

const supportedFileTypes: SupportedFileType[] = Object.values(SupportedFileType).filter(x => typeof x === 'string');
Expand All @@ -241,7 +246,7 @@ function getReplacement(
)}, skipping code block`,
),
);
return substr;
return { text: substr, error: false };
}

const languageFamily: CommentFamily | null = lookupLanguageCommentFamily(codeExtension);
Expand All @@ -254,7 +259,7 @@ function getReplacement(
)} marked as supported, but comment family could not be determined. Please report this issue.`,
),
);
return substr;
return { text: substr, error: false };
}

commentedFilename = filetypeCommentReaders[languageFamily](firstLine);
Expand All @@ -264,14 +269,14 @@ function getReplacement(
log({ returnSnippet: substr }, chalk =>
chalk.gray(`No comment detected in first line for block with extension ${codeExtension}`),
);
return substr;
return { text: substr, error: false };
}

const matches = commentedFilename.match(/\s?(\S+?)((#L(\d+)-L(\d+))|$)/m);

if (!matches) {
log({ returnSnippet: substr }, chalk => chalk.gray(`No file found in embed line`));
return substr;
return { text: substr, error: false };
}

const [, filename, , lineNumbering, startLine, endLine] = matches;
Expand All @@ -283,7 +288,7 @@ function getReplacement(
)}, Expecting Github formatting e.g. #L10-L20`,
),
);
return substr;
return { text: substr, error: false };
}

const relativePath = options.sourceRoot
Expand All @@ -298,7 +303,7 @@ function getReplacement(
)} in comment in first line, but file does not exist at ${chalk.underline(relativePath)}!`,
),
);
return substr;
return { text: substr, error: true };
}

const file = readFileSync(relativePath, 'utf8');
Expand Down Expand Up @@ -338,7 +343,7 @@ function getReplacement(
)} contains a code fence. Refusing to embed as that would break the document`,
),
);
return substr;
return { text: substr, error: false };
}

let replacement =
Expand All @@ -355,12 +360,12 @@ function getReplacement(

if (replacement === substr) {
log({ returnSnippet: substr }, chalk => chalk.gray(`No changes required, already up to date`));
return substr;
return { text: substr, error: false };
}

if (replacement.slice(0, -3).trimRight() === substr.slice(0, -3).trimRight()) {
log({ returnSnippet: substr }, chalk => chalk.gray(`Changes are trailing whitespace only, ignoring`));
return substr;
return { text: substr, error: false };
}

const chalkColour = options.verify ? 'yellow' : 'green';
Expand All @@ -373,7 +378,7 @@ function getReplacement(
),
);

return replacement;
return { text: replacement, error: false };
}

function getLineNumber(text: string, index: number, lineEnding: string): number {
Expand All @@ -386,7 +391,11 @@ function detectLineEnding(sourceText: string): string {
return rexp.test(sourceText) ? '\r\n' : '\n';
}

export function embedme(sourceText: string, inputFilePath: string, options: EmbedmeOptions): string {
export function embedme(
sourceText: string,
inputFilePath: string,
options: EmbedmeOptions,
): { outText: string; error: boolean } {
const log = logBuilder(options);

log(chalk => chalk.magenta(` Analysing ${chalk.underline(relative(process.cwd(), inputFilePath))}...`));
Expand All @@ -406,6 +415,7 @@ export function embedme(sourceText: string, inputFilePath: string, options: Embe
let previousEnd = 0;

let result: RegExpExecArray | null;
let replacementError = false;
while ((result = codeFenceFinder.exec(sourceText)) !== null) {
const [codeFence, leadingSpaces] = result;
const start = sourceText.substring(previousEnd, result.index);
Expand All @@ -432,7 +442,7 @@ export function embedme(sourceText: string, inputFilePath: string, options: Embe

const commentInsertion = start.match(/<!--\s*?embedme[ ]+?(\S+?)\s*?-->/);

const replacement = getReplacement(
const { text, error } = getReplacement(
inputFilePath,
options,
log,
Expand All @@ -446,9 +456,16 @@ export function embedme(sourceText: string, inputFilePath: string, options: Embe
commentInsertion ? commentInsertion[1] : undefined,
);

docPartials.push(start, replacement);
if (error) {
replacementError = true;
}

docPartials.push(start, text);
previousEnd = codeFenceFinder.lastIndex;
}

return [...docPartials].join('') + sourceText.substring(previousEnd);
return {
outText: [...docPartials].join('') + sourceText.substring(previousEnd),
error: replacementError,
};
}
6 changes: 4 additions & 2 deletions src/embedme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,11 @@ sourceFiles.forEach((source, i) => {

const sourceText = readFileSync(source, 'utf-8');

const outText = embedme(sourceText, resolvedPath, options);
const { outText, error } = embedme(sourceText, resolvedPath, options);

if (options.verify) {
if (error) {
process.exit(1);
} else if (options.verify) {
if (sourceText !== outText) {
errorLog(chalk => chalk.red(`Diff detected, exiting 1`));
process.exit(1);
Expand Down
27 changes: 27 additions & 0 deletions test/fixtures/fixture-error.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Missing File

```txt
// file-does-not-exist.txt
```

### Also bad file format

```ts
// also-not-a-file
```

### Contains Codefence

```md
<!-- contains-codefence.md -->
```

### Contains Codefence, but not the embedded lines

```md
<!-- contains-codefence.md#L1-L3 -->

# This markdown document

## Contains a codefence
```
28 changes: 0 additions & 28 deletions test/fixtures/fixture-in-place.md
Original file line number Diff line number Diff line change
Expand Up @@ -519,34 +519,6 @@ Ignored block
// Not a file
```

### Also bad file format

```ts
// also-not-a-file
```

### Missing file

```txt
// this-file-does-not-exist.txt
```

### Contains Codefence

```md
<!-- contains-codefence.md -->
```

### Contains Codefence, but not the embedded lines

```md
<!-- contains-codefence.md#L1-L3 -->

# This markdown document

## Contains a codefence
```

### malformed line numbering

```ts
Expand Down
28 changes: 0 additions & 28 deletions test/fixtures/fixture-source.md
Original file line number Diff line number Diff line change
Expand Up @@ -287,34 +287,6 @@ Ignored block
// Not a file
```

### Also bad file format

```ts
// also-not-a-file
```

### Missing file

```txt
// this-file-does-not-exist.txt
```

### Contains Codefence

```md
<!-- contains-codefence.md -->
```

### Contains Codefence, but not the embedded lines

```md
<!-- contains-codefence.md#L1-L3 -->

# This markdown document

## Contains a codefence
```

### malformed line numbering

```ts
Expand Down
28 changes: 0 additions & 28 deletions test/fixtures/fixture.md
Original file line number Diff line number Diff line change
Expand Up @@ -519,34 +519,6 @@ Ignored block
// Not a file
```

### Also bad file format

```ts
// also-not-a-file
```

### Missing file

```txt
// this-file-does-not-exist.txt
```

### Contains Codefence

```md
<!-- contains-codefence.md -->
```

### Contains Codefence, but not the embedded lines

```md
<!-- contains-codefence.md#L1-L3 -->

# This markdown document

## Contains a codefence
```

### malformed line numbering

```ts
Expand Down
49 changes: 15 additions & 34 deletions test/snapshots/test.ts.md
Original file line number Diff line number Diff line change
Expand Up @@ -529,34 +529,6 @@ Generated by [AVA](https://ava.li).
// Not a file␊
```␊
### Also bad file format␊
```ts␊
// also-not-a-file␊
```␊
### Missing file␊
```txt␊
// this-file-does-not-exist.txt␊
```␊
### Contains Codefence␊
```md␊
<!-- contains-codefence.md -->␊
```␊
### Contains Codefence, but not the embedded lines␊
```md␊
<!-- contains-codefence.md#L1-L3 -->␊
# This markdown document␊
## Contains a codefence␊
```␊
### malformed line numbering␊
```ts␊
Expand Down Expand Up @@ -621,15 +593,24 @@ Generated by [AVA](https://ava.li).
test/fixtures/fixture-in-place.md#L506-L508 Unsupported file extension [binary], supported extensions are txt, ts, js, re, scss, rust, java, cpp, c, html, xml, md, yaml, json, json5, py, bash, sh, go, objectivec, php, cs, swift, rb, kotlin, scala, cr, puml, mermaid, cmake, proto, sql, hs, ino, jsx, tsx, skipping code block␊
test/fixtures/fixture-in-place.md#L512-L514 No code extension detected, skipping code block...␊
test/fixtures/fixture-in-place.md#L518-L520 No comment detected in first line for block with extension ts␊
test/fixtures/fixture-in-place.md#L524-L526 Found filename also-not-a-file in comment in first line, but file does not exist at ${cwd}/test/fixtures/also-not-a-file!␊
test/fixtures/fixture-in-place.md#L530-L532 Found filename this-file-does-not-exist.txt in comment in first line, but file does not exist at ${cwd}/test/fixtures/this-file-does-not-exist.txt!␊
test/fixtures/fixture-in-place.md#L536-L538 Found filename contains-codefence.md in comment in first line, but file does not exist at ${cwd}/test/fixtures/contains-codefence.md!␊
test/fixtures/fixture-in-place.md#L542-L548 Found filename contains-codefence.md in comment in first line, but file does not exist at ${cwd}/test/fixtures/contains-codefence.md!␊
test/fixtures/fixture-in-place.md#L552-L554 Incorrectly formatted line numbering string snippets/sample.ts#L1-2, Expecting Github formatting e.g. #L10-L20␊
test/fixtures/fixture-in-place.md#L558-L560 Code block is empty & no preceding embedme comment, skipping...␊
test/fixtures/fixture-in-place.md#L524-L526 Incorrectly formatted line numbering string snippets/sample.ts#L1-2, Expecting Github formatting e.g. #L10-L20␊
test/fixtures/fixture-in-place.md#L530-L532 Code block is empty & no preceding embedme comment, skipping...␊
Writing test/fixtures/fixture-in-place.md with embedded changes.␊
`

> stderr does not match
''

## it exits with code 1 in error conditions

> stdout does not match
`Verifying...␊
Skipped 0 files ignored in '.gitignore'␊
Analysing test/fixtures/fixture-error.md...␊
test/fixtures/fixture-error.md#L3-L5 Found filename file-does-not-exist.txt in comment in first line, but file does not exist at ${cwd}/test/fixtures/file-does-not-exist.txt!␊
test/fixtures/fixture-error.md#L9-L11 Found filename also-not-a-file in comment in first line, but file does not exist at ${cwd}/test/fixtures/also-not-a-file!␊
test/fixtures/fixture-error.md#L15-L17 Found filename contains-codefence.md in comment in first line, but file does not exist at ${cwd}/test/fixtures/contains-codefence.md!␊
test/fixtures/fixture-error.md#L21-L27 Found filename contains-codefence.md in comment in first line, but file does not exist at ${cwd}/test/fixtures/contains-codefence.md!␊
`
Binary file modified test/snapshots/test.ts.snap
Binary file not shown.
Loading

0 comments on commit cb8cacc

Please sign in to comment.