Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
NullVoxPopuli committed Dec 11, 2023
1 parent 5ef044f commit 761ed2f
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
1 change: 1 addition & 0 deletions __tests__/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ describe('main tests', () => {
${' 14.1.0 '} | ${'14.1.0'}
${'{"volta": {"node": ">=14.0.0 <=17.0.0"}}'}| ${'>=14.0.0 <=17.0.0'}
${'{"engines": {"node": "17.0.0"}}'} | ${'17.0.0'}
${'{}'} | ${null}
`.it('parses "$contents"', ({contents, expected}) => {
expect(util.parseNodeVersionFile(contents)).toBe(expected);
});
Expand Down
12 changes: 11 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,17 @@ function resolveVersionInput(): string {
);
}

version = parseNodeVersionFile(fs.readFileSync(versionFilePath, 'utf8'));
const parsedVersion = parseNodeVersionFile(
fs.readFileSync(versionFilePath, 'utf8')
);

if (parsedVersion) {
version = parsedVersion;
} else {
core.warning(
`Could not determine node version from ${versionFilePath}. Falling back`
);
}

core.info(`Resolved ${versionFileInput} as ${version}`);
}
Expand Down
24 changes: 21 additions & 3 deletions src/util.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,31 @@
import * as core from '@actions/core';
import * as exec from '@actions/exec';

export function parseNodeVersionFile(contents: string): string {
export function parseNodeVersionFile(contents: string): string | null {
let nodeVersion: string | undefined;

// Try parsing the file as an NPM `package.json` file.
try {
nodeVersion = JSON.parse(contents).volta?.node;
if (!nodeVersion) nodeVersion = JSON.parse(contents).engines?.node;
const manifest = JSON.parse(contents);

// JSON can parse numbers, but that's handled later
if (typeof manifest === 'object') {
nodeVersion = manifest.volta?.node;
if (!nodeVersion) nodeVersion = manifest.engines?.node;

// if contents are an object, we parsed JSON
// this can happen if node-version-file is a package.json
// yet contains no volta.node or engines.node
//
// if node-version file is _not_ json, control flow
// will not have reached these lines.
//
// And because we've reached here, we know the contents
// *are* JSON, so no further string parsing makes sense.
if (!nodeVersion) {
return null;
}
}
} catch {
core.info('Node version file is not JSON file');
}
Expand Down

0 comments on commit 761ed2f

Please sign in to comment.