Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(env): load new env variable on update #1368

Merged
merged 8 commits into from
Oct 6, 2022
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/bundler/src/index-html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export const indexHtml = ({
baseDir,
editorName,
inputProps,
envVariables,
staticHash,
remotionRoot,
previewServerCommand,
Expand All @@ -12,6 +13,7 @@ export const indexHtml = ({
baseDir: string;
editorName: string | null;
inputProps: object | null;
envVariables?: Record<string, string>;
remotionRoot: string;
previewServerCommand: string | null;
}) =>
Expand Down Expand Up @@ -49,6 +51,14 @@ export const indexHtml = ({
`
: ''
}
${
envVariables
? `<script> window.process = {
env: ${JSON.stringify(envVariables)}
};</script>
`
: ''
}

<div id="container"></div>
<div id="menuportal-0"></div>
Expand Down
6 changes: 5 additions & 1 deletion packages/cli/src/event-source-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,8 @@ export type EventSourceEvent =
}
| {
type: 'init';
};
}
| {
type: 'new-env-variables';
newEnvVariables: Record<string, string>;
};
2 changes: 1 addition & 1 deletion packages/cli/src/event-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const openEventSource = () => {

source.addEventListener('message', (event) => {
const newEvent = JSON.parse(event.data) as EventSourceEvent;
if (newEvent.type === 'new-input-props') {
if (newEvent.type === 'new-input-props' || newEvent.type === 'new-env-variables') {
window.location.reload();
}
});
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/get-cli-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ export const getCliOptions = async (options: {
shouldOutputImageSequence,
codec,
inputProps: getInputProps(() => undefined),
envVariables: await getEnvironmentVariables(),
envVariables: await getEnvironmentVariables(() => undefined),
quality: ConfigInternals.getQuality(),
browser: await getAndValidateBrowser(browserExecutable),
crf,
Expand Down
28 changes: 22 additions & 6 deletions packages/cli/src/get-env.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import dotenv from 'dotenv';
import fs from 'fs';
import path from 'path';
import {chalk} from './chalk';
import {ConfigInternals} from './config';
import {findRemotionRoot} from './find-closest-package-json';
import {Log} from './log';
Expand All @@ -22,10 +23,23 @@ function getProcessEnv(): Record<string, string> {

const getEnvForEnvFile = async (
processEnv: ReturnType<typeof getProcessEnv>,
envFile: string
envFile: string,
onUpdate: (newProps: Record<string, string>) => void
) => {
try {
const envFileData = await fs.promises.readFile(envFile);
fs.watchFile(envFile, {interval: 100}, async () => {
try {
const file = await fs.promises.readFile(envFile, 'utf-8');
onUpdate({
...processEnv,
...dotenv.parse(file),
});
Log.info(chalk.blueBright(`Updated env file ${envFile}`));
} catch (err) {
Log.error(`${envFile} update fails with error ${err}`);
}
});
return {
...processEnv,
...dotenv.parse(envFileData),
Expand All @@ -37,7 +51,9 @@ const getEnvForEnvFile = async (
}
};

export const getEnvironmentVariables = (): Promise<Record<string, string>> => {
export const getEnvironmentVariables = (
onUpdate: (newProps: Record<string, string>) => void
): Promise<Record<string, string>> => {
const processEnv = getProcessEnv();

if (parsedCli['env-file']) {
Expand All @@ -49,7 +65,7 @@ export const getEnvironmentVariables = (): Promise<Record<string, string>> => {
process.exit(1);
}

return getEnvForEnvFile(processEnv, envFile);
return getEnvForEnvFile(processEnv, envFile, onUpdate);
}

const remotionRoot = findRemotionRoot();
Expand All @@ -59,20 +75,20 @@ export const getEnvironmentVariables = (): Promise<Record<string, string>> => {
const envFile = path.resolve(remotionRoot, configFileSetting);
if (!fs.existsSync(envFile)) {
Log.error(
'You specifed a custom .env file using `Config.Rendering.setDotEnvLocation()` in the config file but it could not be found'
'You specified a custom .env file using `Config.Rendering.setDotEnvLocation()` in the config file but it could not be found'
);
Log.error('We looked for the file at:', envFile);
Log.error('Check that your path is correct and try again.');
process.exit(1);
}

return getEnvForEnvFile(processEnv, envFile);
return getEnvForEnvFile(processEnv, envFile, onUpdate);
}

const defaultEnvFile = path.resolve(remotionRoot, '.env');
if (!fs.existsSync(defaultEnvFile)) {
return Promise.resolve(processEnv);
}

return getEnvForEnvFile(processEnv, defaultEnvFile);
return getEnvForEnvFile(processEnv, defaultEnvFile, onUpdate);
};
6 changes: 6 additions & 0 deletions packages/cli/src/preview-server/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,13 @@ const handleFallback = async ({
hash,
response,
getCurrentInputProps,
getEnvVariables,
}: {
remotionRoot: string;
hash: string;
response: ServerResponse;
getCurrentInputProps: () => object;
getEnvVariables: () => Record<string, string>;
}) => {
const [edit] = await editorGuess;
const displayName = getDisplayNameForEditor(edit ? edit.command : null);
Expand All @@ -58,6 +60,7 @@ const handleFallback = async ({
staticHash: hash,
baseDir: '/',
editorName: displayName,
envVariables: getEnvVariables(),
inputProps: getCurrentInputProps(),
remotionRoot,
previewServerCommand:
Expand Down Expand Up @@ -184,6 +187,7 @@ export const handleRoutes = ({
response,
liveEventsServer,
getCurrentInputProps,
getEnvVariables,
remotionRoot,
userPassedPublicDir,
}: {
Expand All @@ -193,6 +197,7 @@ export const handleRoutes = ({
response: ServerResponse;
liveEventsServer: LiveEventsServer;
getCurrentInputProps: () => object;
getEnvVariables: () => Record<string, string>;
remotionRoot: string;
userPassedPublicDir: string | null;
}) => {
Expand Down Expand Up @@ -243,5 +248,6 @@ export const handleRoutes = ({
hash,
response,
getCurrentInputProps,
getEnvVariables,
});
};
5 changes: 3 additions & 2 deletions packages/cli/src/preview-server/start-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const startServer = async (
options: {
webpackOverride: WebpackOverrideFn;
getCurrentInputProps: () => object;
envVariables?: Record<string, string>;
getEnvVariables: () => Record<string, string>;
port: number | null;
maxTimelineTracks?: number;
remotionRoot: string;
Expand All @@ -43,7 +43,7 @@ export const startServer = async (
environment: 'development',
webpackOverride:
options?.webpackOverride ?? ConfigInternals.getWebpackOverrideFn(),
envVariables: options?.envVariables ?? {},
envVariables: options?.getEnvVariables() ?? {},
maxTimelineTracks: options?.maxTimelineTracks ?? 15,
entryPoints: [
require.resolve('./hot-middleware/client'),
Expand Down Expand Up @@ -84,6 +84,7 @@ export const startServer = async (
response,
liveEventsServer,
getCurrentInputProps: options.getCurrentInputProps,
getEnvVariables: options.getEnvVariables,
remotionRoot: options.remotionRoot,
userPassedPublicDir: options.userPassedPublicDir,
});
Expand Down
12 changes: 10 additions & 2 deletions packages/cli/src/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,22 @@ export const previewCommand = async (remotionRoot: string) => {
});
});
});
const envVariables = await getEnvironmentVariables();
let envVariables = await getEnvironmentVariables((newEnvVariables) => {
waitForLiveEventsListener().then((listener) => {
envVariables = newEnvVariables;
listener.sendEventToClient({
type: 'new-env-variables',
newEnvVariables,
});
});
});

const {port, liveEventsServer} = await startServer(
path.resolve(__dirname, 'previewEntry.js'),
fullPath,
{
getCurrentInputProps: () => inputProps,
envVariables,
getEnvVariables: () => envVariables,
port: desiredPort,
maxTimelineTracks: ConfigInternals.getMaxTimelineTracks(),
remotionRoot,
Expand Down