-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoDiscordAnsi.mjs
58 lines (52 loc) · 1.75 KB
/
toDiscordAnsi.mjs
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
import fs from 'fs';
import parseSolidity from './parseSolidity.mjs';
import { collectAllTokens, applyColors } from './highlighter.mjs';
import clipboard from 'clipboardy';
// Read Solidity code from a file
let inputFile = process.argv[2];
let code;
if (!inputFile) {
code = clipboard.readSync();
} else {
code = fs.readFileSync(inputFile, 'utf8');
}
/**
* Merge AST tokens and comments, then apply colors.
* @param {string} code - The original Solidity code.
* @returns {string} - The colored Solidity code with ANSI codes.
*/
function highlightSolidityCode(originalCode) {
let ast;
let surroundedCode = false;
let code = originalCode;
try {
const result = parseSolidity(originalCode);
ast = result.ast;
} catch (error) {
if (error.message.includes("Cannot read properties of null (reading 'getText')")) {
code = `contract Dummy {\n${originalCode}\n}`;
surroundedCode = true;
try {
ast = parseSolidity(code).ast;
}
catch(error) {
code = `contract Dummy { function dum() {\n${originalCode}\n}}`;
surroundedCode = true;
ast = parseSolidity(code).ast;
}
}
}
const astTokens = collectAllTokens(ast, code);
// Apply colors
let coloredCode = applyColors(code, astTokens);
if (surroundedCode) {
coloredCode = coloredCode.split('\n').slice(1, -1).join('\n');
}
return coloredCode;
}
let highlightedCode = highlightSolidityCode(code);
const discordCode = `\`\`\`ansi\n${highlightedCode}\n\`\`\``;
console.log(discordCode);
console.log('\x1b[92m[ Code copied to clipboard! ]');
// Copy the highlighted code to the clipboard
clipboard.writeSync(discordCode);