Created
August 18, 2020 16:28
-
-
Save sjmeverett/deee09bff25b38ff9cf02b2d058bd7fc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const { promises: fs } = require('fs'); | |
| const path = require('path'); | |
| main(process.argv.slice(2)).catch(console.error); | |
| async function main(argv) { | |
| if (argv.length !== 3) { | |
| printUsage(); | |
| process.exit(1); | |
| } | |
| switch (argv[0]) { | |
| case 'export': | |
| await exportEnv(argv[1], argv[2]); | |
| break; | |
| case 'import': | |
| await importEnv(argv[1], argv[2]); | |
| break; | |
| default: | |
| printUsage(); | |
| process.exit(1); | |
| } | |
| } | |
| function printUsage() { | |
| console.log('Usage: dotenv <import|export> <input dir> <output dir>'); | |
| } | |
| async function exportEnv(inputDir, outputDir) { | |
| const dirs = await getDirs(inputDir); | |
| await fs.mkdir(outputDir, { recursive: true }); | |
| for (const dir of dirs) { | |
| try { | |
| await fs.copyFile( | |
| path.join(inputDir, dir, '.env'), | |
| path.join(outputDir, dir + '.env'), | |
| ); | |
| } catch (err) { | |
| console.error(err.message); | |
| } | |
| } | |
| } | |
| async function importEnv(inputDir, outputDir) { | |
| const envs = await getDotEnvs(inputDir); | |
| for (const env of envs) { | |
| try { | |
| await fs.copyFile( | |
| path.join(inputDir, env), | |
| path.join(outputDir, path.basename(env, '.env'), '.env'), | |
| ); | |
| } catch (err) { | |
| console.error(err.message); | |
| } | |
| } | |
| } | |
| async function getDotEnvs(dir) { | |
| const files = await fs.readdir(dir, { withFileTypes: true }); | |
| return files | |
| .filter((file) => file.isFile() && file.name.endsWith('.env')) | |
| .map((file) => file.name); | |
| } | |
| async function getDirs(dir) { | |
| const files = await fs.readdir(dir, { withFileTypes: true }); | |
| return files.filter((file) => file.isDirectory()).map((file) => file.name); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment