Skip to content

Commit 761ed2f

Browse files
committed
Fix #864
1 parent 5ef044f commit 761ed2f

File tree

3 files changed

+33
-4
lines changed

3 files changed

+33
-4
lines changed

__tests__/main.test.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ describe('main tests', () => {
101101
${' 14.1.0 '} | ${'14.1.0'}
102102
${'{"volta": {"node": ">=14.0.0 <=17.0.0"}}'}| ${'>=14.0.0 <=17.0.0'}
103103
${'{"engines": {"node": "17.0.0"}}'} | ${'17.0.0'}
104+
${'{}'} | ${null}
104105
`.it('parses "$contents"', ({contents, expected}) => {
105106
expect(util.parseNodeVersionFile(contents)).toBe(expected);
106107
});

src/main.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,17 @@ function resolveVersionInput(): string {
105105
);
106106
}
107107

108-
version = parseNodeVersionFile(fs.readFileSync(versionFilePath, 'utf8'));
108+
const parsedVersion = parseNodeVersionFile(
109+
fs.readFileSync(versionFilePath, 'utf8')
110+
);
111+
112+
if (parsedVersion) {
113+
version = parsedVersion;
114+
} else {
115+
core.warning(
116+
`Could not determine node version from ${versionFilePath}. Falling back`
117+
);
118+
}
109119

110120
core.info(`Resolved ${versionFileInput} as ${version}`);
111121
}

src/util.ts

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,31 @@
11
import * as core from '@actions/core';
22
import * as exec from '@actions/exec';
33

4-
export function parseNodeVersionFile(contents: string): string {
4+
export function parseNodeVersionFile(contents: string): string | null {
55
let nodeVersion: string | undefined;
66

77
// Try parsing the file as an NPM `package.json` file.
88
try {
9-
nodeVersion = JSON.parse(contents).volta?.node;
10-
if (!nodeVersion) nodeVersion = JSON.parse(contents).engines?.node;
9+
const manifest = JSON.parse(contents);
10+
11+
// JSON can parse numbers, but that's handled later
12+
if (typeof manifest === 'object') {
13+
nodeVersion = manifest.volta?.node;
14+
if (!nodeVersion) nodeVersion = manifest.engines?.node;
15+
16+
// if contents are an object, we parsed JSON
17+
// this can happen if node-version-file is a package.json
18+
// yet contains no volta.node or engines.node
19+
//
20+
// if node-version file is _not_ json, control flow
21+
// will not have reached these lines.
22+
//
23+
// And because we've reached here, we know the contents
24+
// *are* JSON, so no further string parsing makes sense.
25+
if (!nodeVersion) {
26+
return null;
27+
}
28+
}
1129
} catch {
1230
core.info('Node version file is not JSON file');
1331
}

0 commit comments

Comments
 (0)