-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathchatgptextractcodeblock
More file actions
executable file
·67 lines (55 loc) · 2.14 KB
/
chatgptextractcodeblock
File metadata and controls
executable file
·67 lines (55 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env node
const fs = require('fs');
function printHelp() {
console.log(`Usage: chatgptExtractCodeblock [options]
Description:
Extracts and prints the contents of a code block delimited by triple backticks from stdin.
The code block can be inline or multiline.
Options:
-n, --invert Print everything except the code block.
--help Show this help message and exit.
`);
process.exit(0);
}
function processArgs() {
const args = process.argv.slice(2);
const options = {invert: false};
for (let i = 0; i < args.length; i++) {
if (args[i] === '--help' || args[i] === '-h') {
printHelp();
} else if (args[i] === '-n' || args[i] === '--invert') {
options.invert = true;
} else {
printHelp();
}
}
return options;
}
function extractCodeBlock(fileContent, invert) {
// split the fileContent at triple backticks as multline regex
const regex = /```[a-z]*\n?/gm;
const parts = fileContent.split(regex);
if (parts.length < 3 ) {
console.error('Error: ', parts.length, ' parts - no code block found in\n', fileContent);
process.exit(1);
} else if (parts.length > 3) {
console.error('Error: Multiple code blocks found in\n', fileContent);
process.exit(1);
}
if (invert) {
const result = parts[0] + parts[2];
console.log(result);
} else {
console.log(parts[1]);
}
}
function main() {
const options = processArgs();
const fileContent = fs.readFileSync(0, 'utf8');
extractCodeBlock(fileContent, options.invert);
}
main();
/**
* Requirements for ChatGPT, but I gave up and fixed that myself:
* The script is called chatgptExtractCodeblock. It looks for a codeblock delimited with three backticks ``` - one before the codeblock, one after the codeblock, and prints the contents of that codeblock to stdout. The codeblock can be on one line, including the delimiters, or multiline. If the argument -n is given, it prints everything except that codeblock. If there is no codeblock, it returns with exit code 0 and no output, but an error message to stderr.
*/