1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| import ChildProcess from "child_process"; import path from "path"; import fsPromises from "fs/promises"; import type { Plugin } from "vite"; import { promisify } from "util";
async function execGit(gitWorkTree: string | undefined, cmd: string) { const { exec } = ChildProcess; const execPromise = promisify(exec); const gitBaseCommand = gitWorkTree ? `git --git-dir=${path.join(gitWorkTree, ".git")} --work-tree=${gitWorkTree}` : "git"; try { const { stdout } = await execPromise(`${gitBaseCommand} ${cmd}`); return stdout.trim().replace(/[\s\r\n]+$/, ""); } catch (error) { console.error(error); return `Error executing git command`; } }
export default function vitePluginVersionFromGit(): Plugin { let config: any = {}; return { name: "vite-plugin-version-from-git", async config() { const branch = await execGit(undefined, "rev-parse --abbrev-ref HEAD"); const tag = await execGit(undefined, "describe --tags --abbrev=0"); const commitHash = await execGit(undefined, "rev-parse --short HEAD"); const commitMessage = await execGit(undefined, "log -1 --format=%s"); let commitDate = await execGit(undefined, "log -1 --pretty=%cI"); if (commitDate.includes("+")) { commitDate = commitDate .split("+")[0] .replaceAll("T", "") .replaceAll("-", "") .replaceAll(":", ""); } config = { GIT_BRANCH: branch, GIT_TAG: tag, GIT_COMMIT_HASH: commitHash, GIT_COMMIT_MESSAGE: commitMessage.replace(/[\s\r\n]+$/, ""), GIT_COMMIT_DATE: commitDate, define: { RELEASE_VERSION: `"${tag}-${commitHash}-${commitDate}"` } }; return config; }, async closeBundle() { const output = config.build?.outDir ?? "dist"; const distDir = path.resolve(output); const configPath = path.resolve(distDir, "platform-config.json"); try { if ( !(await fsPromises .access(distDir) .then(() => true) .catch(() => false)) ) { await fsPromises.mkdir(distDir, { recursive: true }); } let cfg: Record<string, any> = {}; if ( await fsPromises .access(configPath) .then(() => true) .catch(() => false) ) { const content = await fsPromises.readFile(configPath, "utf-8"); cfg = content ? JSON.parse(content) : {}; cfg.version = config.define.RELEASE_VERSION.replaceAll('"', ""); cfg.external = config.GIT_COMMIT_MESSAGE; await fsPromises.writeFile( configPath, JSON.stringify(cfg, null, 2), "utf-8" ); } } catch (error) { console.error(error); } } }; }
|