Procházet zdrojové kódy

chore: load .env automatically

Gerald před 2 roky
rodič
revize
f60960ae80

+ 2 - 1
.github/workflows/release.yml

@@ -37,7 +37,8 @@ jobs:
           # Create source zip
           git archive @ --format=zip > $TEMP_DIR/$SOURCE_ZIP
           # Include .env to ensure the output is reproducible
-          export | grep SYNC_ > .env && zip -u $TEMP_DIR/$SOURCE_ZIP .env && rm .env
+          export | grep SYNC_ | sed -e 's/^declare -x //' > .env \
+            && zip -u $TEMP_DIR/$SOURCE_ZIP .env && rm .env
 
           # Build for release, also upload to GitHub assets
           yarn build

+ 1 - 0
.gitignore

@@ -6,3 +6,4 @@ node_modules/
 /tmp/
 /dist-assets/
 .eslintcache
+.env

+ 0 - 1
scripts/amo-upload.mjs

@@ -40,7 +40,6 @@ async function main() {
       : join(process.env.ASSETS_DIR, process.env.ASSET_ZIP),
     sourceFile: join(process.env.TEMP_DIR, process.env.SOURCE_ZIP),
     approvalNotes: `\
-source .env
 yarn && yarn build
 `,
     output: tempFile,

+ 49 - 0
scripts/config-helper.js

@@ -0,0 +1,49 @@
+const fs = require('fs');
+
+class ConfigLoader {
+  data = {};
+
+  add(values) {
+    Object.assign(this.data, values);
+    return this;
+  }
+
+  env() {
+    return this.add(process.env);
+  }
+
+  envFile(filepath = '.env') {
+    let content = '';
+    try {
+      content = fs.readFileSync(filepath, 'utf8');
+    } catch {
+      // ignore error
+    }
+    const values = content
+      .split('\n')
+      .map((line) => line.trim())
+      .filter((line) => line && !line.startsWith('#'))
+      .map((line) => {
+        const i = line.indexOf('=');
+        if (i < 0) return [];
+        const key = line.split(0, i).trim();
+        let value = line.split(i + 1).trim();
+        // Note: escaped characters are not supported
+        if (/^(['"]).*\1$/.test(value)) value = value.slice(1, -1);
+        return [key, value];
+      })
+      .reduce((prev, [key, value]) => {
+        if (key) prev[key] = value;
+        return prev;
+      }, {});
+    return this.add(values);
+  }
+
+  get(key, def) {
+    return this.data[key] ?? def;
+  }
+}
+
+exports.ConfigLoader = ConfigLoader;
+
+exports.configLoader = new ConfigLoader();

+ 26 - 14
scripts/webpack.conf.js

@@ -8,6 +8,7 @@ const { addWrapperWithGlobals, getCodeMirrorThemes } = require('./webpack-util')
 const ProtectWebpackBootstrapPlugin = require('./webpack-protect-bootstrap-plugin');
 const projectConfig = require('./plaid.conf');
 const { getVersion } = require('./version-helper');
+const { configLoader } = require('./config-helper');
 const mergedConfig = shallowMerge(defaultOptions, projectConfig);
 
 // Avoiding collisions with globals of a content-mode userscript
@@ -54,26 +55,37 @@ const MIN_OPTS_MAIN = isProd && deepmerge.all([{}, MIN_OPTS, {
   },
 }]);
 
+configLoader
+  // Default values
+  .add({
+    DEBUG: false,
+  })
+  // Load from `./.env`
+  .envFile()
+  // Load from `process.env`
+  .env()
+  // Override values
+  .add({
+    VM_VER,
+  });
+
 const pickEnvs = (items) => {
-  return Object.assign({}, ...items.map(x => ({
-    [`process.env.${x.key}`]: JSON.stringify(
-      'val' in x ? x.val
-        : process.env[x.key] ?? x.def,
-    ),
+  return Object.assign({}, ...items.map(key => ({
+    [`process.env.${key}`]: JSON.stringify(configLoader.get(key)),
   })));
 };
 
 const defsObj = {
   ...pickEnvs([
-    { key: 'DEBUG', def: false },
-    { key: 'VM_VER', val: VM_VER },
-    { key: 'SYNC_GOOGLE_CLIENT_ID' },
-    { key: 'SYNC_GOOGLE_CLIENT_SECRET' },
-    { key: 'SYNC_GOOGLE_DESKTOP_ID' },
-    { key: 'SYNC_GOOGLE_DESKTOP_SECRET' },
-    { key: 'SYNC_ONEDRIVE_CLIENT_ID' },
-    { key: 'SYNC_ONEDRIVE_CLIENT_SECRET' },
-    { key: 'SYNC_DROPBOX_CLIENT_ID' },
+    'DEBUG',
+    'VM_VER',
+    'SYNC_GOOGLE_CLIENT_ID',
+    'SYNC_GOOGLE_CLIENT_SECRET',
+    'SYNC_GOOGLE_DESKTOP_ID',
+    'SYNC_GOOGLE_DESKTOP_SECRET',
+    'SYNC_ONEDRIVE_CLIENT_ID',
+    'SYNC_ONEDRIVE_CLIENT_SECRET',
+    'SYNC_DROPBOX_CLIENT_ID',
   ]),
   'process.env.INIT_FUNC_NAME': JSON.stringify(INIT_FUNC_NAME),
   'process.env.CODEMIRROR_THEMES': JSON.stringify(getCodeMirrorThemes()),