Skip to content

Commit bbabec2

Browse files
committed
fix: Use JSON to parse npm pack output.
1 parent 99fa9ba commit bbabec2

2 files changed

Lines changed: 39 additions & 4 deletions

File tree

pre_commit/languages/node.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import contextlib
44
import functools
5+
import json
56
import os
67
import sys
78
from collections.abc import Generator
@@ -98,8 +99,28 @@ def install_environment(
9899
)
99100
lang_base.setup_cmd(prefix, local_install_cmd)
100101

101-
_, pkg, _ = cmd_output('npm', 'pack', cwd=prefix.prefix_dir)
102-
pkg = prefix.path(pkg.strip())
102+
_, pkg, _ = cmd_output(
103+
'npm', 'pack', '--json', '--ignore-scripts', cwd=prefix.prefix_dir,
104+
)
105+
try:
106+
pkg_json = json.loads(pkg)
107+
except json.JSONDecodeError as e:
108+
raise ValueError('Failed to parse npm pack output as JSON.') from e
109+
110+
if not pkg_json:
111+
raise ValueError('JSON array from npm pack is empty.')
112+
113+
if not isinstance(pkg_json, list):
114+
raise ValueError('Expected npm pack output to be a JSON array.')
115+
116+
filename = pkg_json[0].get('filename')
117+
if filename is None:
118+
raise KeyError(
119+
"Key 'filename' not found in the first element "
120+
'of the JSON array.',
121+
)
122+
123+
pkg = prefix.path(filename)
103124

104125
install = ('npm', 'install', '-g', pkg, *additional_dependencies)
105126
lang_base.setup_cmd(prefix, install)

tests/languages/node_test.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,8 @@ def test_installs_without_links_outside_env(tmpdir):
113113
assert cmd_output('foo')[1] == 'success!\n'
114114

115115

116-
def _make_hello_world(tmp_path):
117-
package_json = '''\
116+
def _make_hello_world(tmp_path, package_json=None):
117+
package_json = package_json or '''\
118118
{"name": "t", "version": "0.0.1", "bin": {"node-hello": "./bin/main.js"}}
119119
'''
120120
tmp_path.joinpath('package.json').write_text(package_json)
@@ -132,6 +132,20 @@ def test_node_hook_system(tmp_path):
132132
assert ret == (0, b'Hello World\n')
133133

134134

135+
def test_node_with_prepare_script(tmp_path):
136+
package_json = '''
137+
{
138+
"name": "t",
139+
"version": "0.0.1",
140+
"bin": {"node-hello": "./bin/main.js"},
141+
"scripts": {"prepare": "echo prepare"}
142+
}
143+
'''
144+
_make_hello_world(tmp_path, package_json)
145+
ret = run_language(tmp_path, node, 'node-hello')
146+
assert ret == (0, b'Hello World\n')
147+
148+
135149
def test_node_with_user_config_set(tmp_path):
136150
cfg = tmp_path.joinpath('cfg')
137151
cfg.write_text('cache=/dne\n')

0 commit comments

Comments
 (0)