UNPKG

@baseplate-dev/create-project

Version:

CLI starter kit for creating a new Baseplate project

75 lines (61 loc) 2.03 kB
/* * Generates .npmrc from a .npmrc.template file using a .env file if present * * This allows us to use .env files to store secrets and use them in .npmrc * since it is not natively supported by pnpm. */ const fs = require('node:fs'); const path = require('node:path'); module.exports = function generateNpmRc(dirname) { const templatePath = path.join(dirname, '.template.npmrc'); const npmrcPath = path.join(dirname, '.npmrc'); const envPath = path.join(dirname, '.env'); if (!fs.existsSync(templatePath)) { return; } // read .env file if present const envVars = { ...process.env }; if (fs.existsSync(envPath)) { const env = fs.readFileSync(envPath, 'utf8'); const lines = env .split('\n') .filter((line) => line && !line.startsWith('#')); for (const line of lines) { const [key, ...values] = line.split('='); if (values.length > 0) { envVars[key] = values.join('='); } } } const template = fs.readFileSync(templatePath, 'utf8'); // replace all ${VARIABLE} with process.env.VARIABLE const npmrc = template .replaceAll(/\${([A-Z_]+)}/g, (_, key) => { if (!envVars[key]) { throw new Error(`Missing environment variable ${key}`); } return envVars[key]; }) .replaceAll(/\${([A-Z_:a-z\-]+)}/g, (_, key) => envVars[key] ? envVars[key] : key, ); const npmrcContents = ` # This file has been auto-generated from .npmrc.template # Do not edit this file directly # Edit .npmrc.template instead and run \`pnpm install\` to regenerate this file ${npmrc}`.trimStart(); if (fs.existsSync(npmrcPath)) { const existingNpmrc = fs.readFileSync(npmrcPath, 'utf8'); if (existingNpmrc === npmrcContents) { return; } } fs.writeFileSync(npmrcPath, npmrcContents); if (!process.argv.includes('--silent')) { console.log(` Generated .npmrc file from .template.npmrc! Please run your command again so it can use the latest .npmrc. `); process.exit(1); } };