Created
August 29, 2023 02:08
-
-
Save mskelton/d821d40559bc894965c25dd483a2e13b to your computer and use it in GitHub Desktop.
Set the packageManager key in package.json to the latest version of the given package manager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Ensure there is a manifest file | |
if [[ ! -f package.json ]]; then | |
echo "error: no manifest file found" | |
exit 1 | |
fi | |
# Get the repo name for the given package manager | |
if [[ $1 == 'npm' ]]; then | |
repo='npm/cli' | |
elif [[ $1 == 'yarn' ]]; then | |
repo='yarnpkg/berry' | |
elif [[ $1 == 'pnpm' ]]; then | |
repo='pnpm/pnpm' | |
else | |
echo "error: unknown package manager '$1'" | |
exit 1 | |
fi | |
# Get the latest version from GitHub | |
version=$( | |
curl -s https://api.github.com/repos/$repo/releases/latest | | |
grep '"name": "v' | | |
awk '{print $2}' | | |
tr -d v\", | |
) | |
# Set the packageManager key in the manifest | |
key="$1@$version" | |
jq ".packageManager = \"$key\"" package.json >/tmp/package.json | |
mv /tmp/package.json package.json |
This is the JS version of that script (did this cuz had problem with jq):
const { execSync } = require("child_process");
// Ensure there is a manifest file
if (!readFileSync("package.json")) {
console.error("error: no manifest file found");
process.exit(1);
}
const PACKAGE_MANAGER_NAME = process.argv[2];
const packageManagersRepo = {
npm: "npm/cli",
yarn: "yarnpkg/berry",
pnpm: "pnpm/pnpm",
};
const repo = packageManagersRepo[PACKAGE_MANAGER_NAME];
if (!repo) {
console.error(`error: unknown package manager '${PACKAGE_MANAGER_NAME}'`);
process.exit(1);
}
// Get the latest version from GitHub
const stdout = execSync(
`curl -s https://api.github.com/repos/${repo}/releases/latest`,
{ encoding: "utf-8" }
);
const version = JSON.parse(stdout).name.replace("v", "");
// Set the packageManager key in the manifest
const packageJson = JSON.parse(readFileSync("package.json"));
const key = `${PACKAGE_MANAGER_NAME}@${version}`;
packageJson.packageManager = key;
writeFileSync("package.json", JSON.stringify(packageJson, null, 2));```
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you buddy. Exactly what I wanted <3