From 4de93ef3e23210f2052a2a2ff9ebf14a6399fdf7 Mon Sep 17 00:00:00 2001 From: Olivers Vitins Date: Sun, 17 Dec 2023 18:11:47 +0200 Subject: [PATCH] feat(commands): check for updates upon commit creation (#13) --- src/index.ts | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index 1f69fd9..4c512e6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,12 +10,14 @@ import { select, text, } from "@clack/prompts"; -import fs, { fdatasync } from "fs"; +import fs from "fs"; import path from "path"; import { CommitStack, Config } from "./types"; import simpleGit from "simple-git"; import { Command } from "commander"; import semver from "semver"; +import { execSync } from "child_process"; +import { tmpdir } from "os"; const GetConfig = async () => { if (fs.existsSync(path.join(process.cwd(), ".rczrc"))) { @@ -40,6 +42,38 @@ const GetConfig = async () => { return null; } }; + +const CheckForUpdates = async () => { + const updateText = + "You are running on an outdated version of Resultium Commitizen, in order to update run\n\nnpm install -g @resultium/rcz@latest"; + + const cachedVersion = fs.existsSync(path.join(tmpdir(), "rcz-server-version")) + ? (await fs.promises.readFile(path.join(tmpdir(), "rcz-server-version"))) + .toString() + .trim() + : null; + const localVersion = execSync("rcz --version").toString().trim(); + + // even if cached once in a while it should get newest data + if ((cachedVersion && Math.random() < 0.1) || cachedVersion === null) { + const isOnline = (await fetch("https://icanhazip.com")).status === 200; + if (!isOnline) return; + + const serverVersion = execSync("npm show @resultium/rcz version") + .toString() + .trim(); + + fs.promises.writeFile( + path.join(tmpdir(), "rcz-server-version"), + serverVersion + ); + + if (semver.gt(serverVersion, localVersion)) note(updateText); + } else if (cachedVersion) { + if (semver.gt(cachedVersion, localVersion)) note(updateText); + } +}; + const program = new Command(); program @@ -54,6 +88,8 @@ program .option("-S, --sign", "sign the commit") .option("--amend", "amend commit message to the last commit") .action(async (options) => { + await CheckForUpdates(); + const config = await GetConfig(); const sign = config?.autoSignCommits || options.sign ? true : false;