Skip to content

Commit f4a18d3

Browse files
committed
Refactor lockfile discovery
1 parent f54ad0f commit f4a18d3

File tree

1 file changed

+11
-13
lines changed

1 file changed

+11
-13
lines changed

scfw/package_managers/npm.py

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -106,24 +106,19 @@ def is_install_command(command: list[str]) -> bool:
106106
}
107107
return any(alias in command for alias in install_aliases)
108108

109-
def read_lockfile() -> dict[str, Any]:
109+
def detect_lockfile() -> Optional[Path]:
110110
npm_prefix_command = self._normalize_command(["npm", "prefix"])
111111
npm_prefix = subprocess.run(npm_prefix_command, check=True, text=True, capture_output=True).stdout.strip()
112112
if not npm_prefix:
113113
_log.debug("'npm prefix' command returned empty output")
114-
return {}
114+
return None
115115

116-
package_lock_path = Path(npm_prefix) / "package-lock.json"
117-
if not package_lock_path.is_file():
116+
lockfile_path = Path(npm_prefix) / "package-lock.json"
117+
if not lockfile_path.is_file():
118118
_log.debug("No package-lock.json file found in current project root")
119-
return {}
120-
121-
with open(package_lock_path) as f:
122-
package_lock_file = json.load(f)
123-
if not isinstance(package_lock_file, dict):
124-
raise RuntimeError(f"Package lock file {package_lock_path} is malformed")
119+
return None
125120

126-
return package_lock_file
121+
return lockfile_path
127122

128123
def extract_target_handles(dry_run_log: list[str]) -> list[str]:
129124
target_handles = []
@@ -188,11 +183,14 @@ def match_to_placed_dependency(placed_dependencies: list[Package], target_name:
188183
install_targets = set()
189184
placed_dependencies = extract_placed_dependencies(dry_run_log)
190185

186+
# Read `package-lock.json`, if it exists
191187
lockfile = {}
192188
try:
193-
lockfile = read_lockfile()
189+
if (lockfile_path := detect_lockfile()):
190+
with open(lockfile_path) as f:
191+
lockfile = json.load(f)
194192
except Exception as e:
195-
_log.warning(f"Failed to read package-lock.json: {e}")
193+
_log.warning(f"Failed to read package lockfile: {e}")
196194

197195
while target_handles:
198196
target_handle = target_handles.pop()

0 commit comments

Comments
 (0)