Philipp Schrader | 272e07b | 2024-03-29 17:26:02 -0700 | [diff] [blame] | 1 | """Acts as a dummy `npm` binary for the `create-foxglove-extension` binary. |
| 2 | |
| 3 | The `create-foxglove-extension` binary uses `npm` to manipulate the |
| 4 | `package.json` file instead of doing so directly. Since we don't have access to |
| 5 | the real `npm` binary here we just emulate the limited functionality we need. |
| 6 | """ |
| 7 | |
| 8 | import argparse |
| 9 | import json |
| 10 | import sys |
| 11 | from pathlib import Path |
| 12 | |
| 13 | |
| 14 | def main(argv: list[str]): |
| 15 | """Runs the main logic.""" |
| 16 | parser = argparse.ArgumentParser() |
| 17 | parser.add_argument("command") |
| 18 | parser.add_argument("--save-exact", action="store_true") |
| 19 | parser.add_argument("--save-dev", action="store_true") |
| 20 | args, packages = parser.parse_known_args(argv[1:]) |
| 21 | |
| 22 | # Validate the input arguments. |
| 23 | if args.command != "install": |
| 24 | raise ValueError("Don't know how to simulate anything other " |
| 25 | f"than 'install'. Got '{args.command}'.") |
| 26 | |
| 27 | for package in packages: |
| 28 | if "@^" not in package: |
| 29 | raise ValueError(f"Got unexpected package: {package}") |
| 30 | |
| 31 | # Append the specified packages to the dependencies list. |
| 32 | package_version_pairs = list( |
| 33 | package.rsplit("@", maxsplit=1) for package in packages) |
| 34 | package_json_file = Path.cwd() / "package.json" |
| 35 | package_json = json.loads(package_json_file.read_text()) |
Austin Schuh | ea5f0a7 | 2024-09-02 15:02:36 -0700 | [diff] [blame^] | 36 | package_json.setdefault("dependencies", {}).update({ |
| 37 | package: version |
| 38 | for package, version in package_version_pairs |
| 39 | }) |
Philipp Schrader | 272e07b | 2024-03-29 17:26:02 -0700 | [diff] [blame] | 40 | |
| 41 | package_json_file.write_text( |
| 42 | json.dumps(package_json, sort_keys=True, indent=4)) |
| 43 | |
| 44 | |
| 45 | if __name__ == "__main__": |
| 46 | sys.exit(main(sys.argv)) |