Skip to content

Commit

Permalink
Add PORT env var to be used (#952)
Browse files Browse the repository at this point in the history
* Add PORT env var to be used

* Format

* Create few-carpets-sing.md

* Update few-carpets-sing.md
  • Loading branch information
stramel authored and FredKSchott committed Aug 11, 2021
1 parent fcc56a8 commit 939b9d0
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/few-carpets-sing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"astro": patch
---

Allow dev server port to be set by `PORT` environment variable
44 changes: 37 additions & 7 deletions packages/astro/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,44 @@ interface CLIState {
};
}

type TypeOf = 'string' | 'boolean' | 'number';
// Validates property types of object
const validateOptions = (opts: Record<string, any>, specs: Record<string, TypeOf | [(v: any) => unknown, TypeOf]>) =>
Object.entries(specs).reduce<Record<string, any>>((options, [k, spec]) => {
const v = opts[k];

if (typeof spec === 'string' && typeof v === spec) {
options[k] = v;
} else if (Array.isArray(spec)) {
const [coercion, test] = spec;
const result = coercion(v);
if (typeof result === test) {
options[k] = result;
}
}

return options;
}, {});

/** Determine which action the user requested */
function resolveArgs(flags: Arguments): CLIState {
const options: CLIState['options'] = {
projectRoot: typeof flags.projectRoot === 'string' ? flags.projectRoot : undefined,
site: typeof flags.site === 'string' ? flags.site : undefined,
sitemap: typeof flags.sitemap === 'boolean' ? flags.sitemap : undefined,
port: typeof flags.port === 'number' ? flags.port : undefined,
config: typeof flags.config === 'string' ? flags.config : undefined,
const { PORT } = process.env;

// Merge options (Flags take priority)
const options = {
...validateOptions(
{ port: PORT },
{
port: [parseInt, 'number'],
}
),
...validateOptions(flags, {
projectRoot: 'string',
site: 'string',
sitemap: 'boolean',
port: 'number',
config: 'string',
}),
};

if (flags.version) {
Expand Down Expand Up @@ -101,7 +131,7 @@ function mergeCLIFlags(astroConfig: AstroConfig, flags: CLIState['options']) {
}

/** Handle `astro run` command */
async function runCommand(rawRoot: string, cmd: (a: AstroConfig, options: any) => Promise<void>, options: CLIState['options']) {
async function runCommand(rawRoot: string, cmd: (a: AstroConfig, opts: any) => Promise<void>, options: CLIState['options']) {
try {
const projectRoot = options.projectRoot || rawRoot;
const astroConfig = await loadConfig(projectRoot, options.config);
Expand Down

0 comments on commit 939b9d0

Please sign in to comment.