Skip to content

Commit 83ca13e

Browse files
feat(file): support lines arg to limit content (#46)
1 parent dbd2a39 commit 83ca13e

File tree

3 files changed

+23
-4
lines changed

3 files changed

+23
-4
lines changed

src/generators/file.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,27 @@ export const file = defineGenerator({
1313
contents = contents.trim();
1414
}
1515

16+
if (args.lines) {
17+
const groups = /^(?<startLine>\d+)?:(?<endLine>\d+)?$/.exec(
18+
"args.lines",
19+
)?.groups;
20+
21+
if (!groups) {
22+
throw new Error("invalid lines format");
23+
}
24+
25+
const lines = contents.split("\n");
26+
27+
const startLine = Number(groups.startLine) || 1;
28+
const endLine = Number(groups.endLine) || lines.length;
29+
30+
if (startLine < 1) {
31+
throw new Error("first line's index can not be smaller than 1");
32+
}
33+
34+
contents = lines.slice(startLine - 1, endLine).join("\n");
35+
}
36+
1637
if (args.code) {
1738
contents = md.codeBlock(
1839
contents,

test/fixture/INPUT.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737

3838
## `file`
3939

40-
<!-- automd:file src="./TEST.md" -->
40+
<!-- automd:file src="./TEST.md" lines=1:5 -->
4141
<!-- /automd -->
4242

4343
## `contributors`

test/fixture/OUTPUT.md

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -190,16 +190,14 @@ Why waste time solving problems when someone else has already done it for you? S
190190

191191
## `file`
192192

193-
<!-- automd:file src="./TEST.md" -->
193+
<!-- automd:file src="./TEST.md" lines=1:5 -->
194194

195195
## The Lazy Coder's Guide to Programming
196196

197197
Programming can be hard. But fear not! With the power of copy-paste, you can conquer any coding challenge without breaking a sweat. Just remember: if it works once, it'll work a thousand times. Who needs original code anyway?
198198

199199
When your code doesn't work, don't blame yourself. It's clearly the compiler's fault for not understanding your genius. Remember, the more error messages you get, the closer you are to becoming a programming master.
200200

201-
Why waste time solving problems when someone else has already done it for you? Stack Overflow is your best friend, your mentor, and your savior. Just make sure to upvote the answers that save your bacon.
202-
203201
<!-- /automd -->
204202

205203
## `contributors`

0 commit comments

Comments
 (0)