Skip to content

feat: package update checker w/ banner #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,17 @@ const main = defineCommand({
name: "hello",
version: "1.0.0",
description: "My Awesome CLI App",
updateChecker: {
registryName: "helloWorld",
msg: `Update available! {current} → {latest}.\n\nRun "npm install -g {cmd}" to update`,
box: {
padding: 1,
margin: 1,
align: "center",
borderColor: "yellow",
borderStyle: "round",
}
}
},
args: {
name: {
Expand Down
10 changes: 9 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,27 @@
"release": "pnpm test && changelogen --release --push && npm publish",
"test": "pnpm lint && vitest run --coverage"
},
"dependencies": {
"boxen": "^7.0.2"
},
"devDependencies": {
"@types/node": "^18.15.11",
"@types/semver": "^7.3.13",
"@vitest/coverage-c8": "^0.29.8",
"changelogen": "^0.5.2",
"colorette": "^2.0.19",
"defu": "^6.1.2",
"eslint": "^8.37.0",
"eslint-config-unjs": "^0.1.0",
"jiti": "^1.18.2",
"ofetch": "^1.0.1",
"pkg-types": "^1.0.2",
"prettier": "^2.8.7",
"scule": "^1.0.0",
"semver": "^7.3.8",
"typescript": "^5.0.3",
"unbuild": "^1.2.0",
"vitest": "^0.29.8"
},
"packageManager": "[email protected]"
}
}
83 changes: 71 additions & 12 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

42 changes: 42 additions & 0 deletions src/_registry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { ofetch } from "ofetch";
import { readPackageJSON } from "pkg-types";
import semver from "semver";

interface ReturnPkgVersion {
latest?: string;
current?: string;
}

const REGISTRY_URL = "https://registry.npmjs.org";

// Check the latest version of a package
export async function checkPkgVersion(name: string): Promise<ReturnPkgVersion> {
const latest = await ofetch(`${REGISTRY_URL}/${name}`, { retry: 3 })
.then((reg) => {
const {
"dist-tags": { latest },
} = reg;
return latest;
})
.catch(() => undefined);

const current = await readPackageJSON()
.then((pkg) => pkg.version)
.catch(() => undefined);

return {
latest,
current,
};
}

// Check if the current version is outdated
export function isPkgOutdated(pkgVer: ReturnPkgVersion): boolean {
const { latest, current } = pkgVer;

if (!latest || !current) {
return false;
}

return semver.lt(current, latest);
}
48 changes: 46 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import { bgRed } from "colorette";
import boxen from "boxen";
import defu from "defu";
import { bgRed, red, bold, green, magenta } from "colorette";
import { readPackageJSON } from "pkg-types";
import type { CommandDef } from "./types";
import { resolveSubCommand, runCommand } from "./command";
import { CLIError } from "./_utils";
import { CLIError, resolveValue } from "./_utils";
import { showUsage } from "./usage";
import { checkPkgVersion, isPkgOutdated } from "./_registry";

export interface RunMainOptions {
rawArgs?: string[];
Expand All @@ -11,6 +15,46 @@ export interface RunMainOptions {
export async function runMain(cmd: CommandDef, opts: RunMainOptions = {}) {
const rawArgs = opts.rawArgs || process.argv.slice(2);
try {
const cmdMeta = defu(await resolveValue(cmd.meta || {}), {
updateChecker: {
registryName: undefined,
msg: `Update available! ${red(bold("{current}"))} → ${bold(
green("{latest}")
)}.\n\nRun "${bold(magenta("npm install -g {cmd}"))}" to update.`,
box: {
padding: 1,
textAlignment: "center",
borderStyle: "round",
borderColor: "yellowBright",
},
},
});

// Check for updates
const pkgName = await readPackageJSON()
.then((r) => r.name)
.catch(() => undefined);
const updateOpts = cmdMeta.updateChecker;
const registryName =
typeof updateOpts === "object"
? updateOpts?.registryName || pkgName
: false;

if (registryName && updateOpts) {
const version = await checkPkgVersion(registryName);
const isOutdated = isPkgOutdated(version);

if (isOutdated && version.current && version.latest) {
const msg = updateOpts.msg
.replace(/{cmd}/g, registryName)
.replace(/{current}/g, version.current)
.replace(/{latest}/g, version.latest);

console.log(boxen(msg, updateOpts.box as any) + "\n");
}
}
// End of update check

if (rawArgs.includes("--help") || rawArgs.includes("-h")) {
await showUsage(...(await resolveSubCommand(cmd, rawArgs)));
process.exit(0);
Expand Down
Loading