aboutsummaryrefslogtreecommitdiff
path: root/src/codegen/helpers.ts
diff options
context:
space:
mode:
authorGravatar dave caruso <me@paperdave.net> 2023-10-17 19:42:37 -0700
committerGravatar dave caruso <me@paperdave.net> 2023-10-17 19:42:37 -0700
commitcb5c4c71c866362dce24eff79251fed6add53e9f (patch)
tree5635cf21140ff2eac14539316f7c6d6704925bd3 /src/codegen/helpers.ts
parentbf12268274faac1a38d33007be7a48af9e570761 (diff)
downloadbun-cb5c4c71c866362dce24eff79251fed6add53e9f.tar.gz
bun-cb5c4c71c866362dce24eff79251fed6add53e9f.tar.zst
bun-cb5c4c71c866362dce24eff79251fed6add53e9f.zip
Diffstat (limited to 'src/codegen/helpers.ts')
-rw-r--r--src/codegen/helpers.ts64
1 files changed, 64 insertions, 0 deletions
diff --git a/src/codegen/helpers.ts b/src/codegen/helpers.ts
new file mode 100644
index 000000000..d259a526e
--- /dev/null
+++ b/src/codegen/helpers.ts
@@ -0,0 +1,64 @@
+import fs from "fs";
+import path from "path";
+import { isAscii } from "buffer";
+
+export function fmtCPPString(str: string) {
+ return (
+ '"' +
+ str
+ .replace(/\\/g, "\\\\")
+ .replace(/"/g, '\\"')
+ .replace(/\n/g, "\\n")
+ .replace(/\r/g, "\\r")
+ .replace(/\t/g, "\\t")
+ .replace(/\?/g, "\\?") + // https://stackoverflow.com/questions/1234582
+ '"'
+ );
+}
+
+export function cap(str: string) {
+ return str[0].toUpperCase() + str.slice(1);
+}
+
+export function low(str: string) {
+ if (str.startsWith("JS")) {
+ return "js" + str.slice(2);
+ }
+
+ return str[0].toLowerCase() + str.slice(1);
+}
+
+export function readdirRecursive(root: string): string[] {
+ const files = fs.readdirSync(root, { withFileTypes: true });
+ return files.flatMap(file => {
+ const fullPath = path.join(root, file.name);
+ return file.isDirectory() ? readdirRecursive(fullPath) : fullPath;
+ });
+}
+
+export function resolveSyncOrNull(specifier: string, from: string) {
+ try {
+ return Bun.resolveSync(specifier, from);
+ } catch {
+ return null;
+ }
+}
+
+export function checkAscii(str: string) {
+ if (!isAscii(Buffer.from(str))) {
+ throw new Error(`non-ascii character in string "${str}". this will not be a valid ASCIILiteral`);
+ }
+
+ return str;
+}
+
+export function writeIfNotChanged(file: string, contents: string) {
+ if (fs.existsSync(file)) {
+ const oldContents = fs.readFileSync(file, "utf8");
+ if (oldContents === contents) {
+ return;
+ }
+ }
+
+ fs.writeFileSync(file, contents);
+}