Skip to content

Commit

Permalink
add git info mark in website footer
Browse files Browse the repository at this point in the history
  • Loading branch information
Fallen-Breath committed Sep 18, 2024
1 parent a5c3e96 commit c1743ab
Show file tree
Hide file tree
Showing 4 changed files with 125 additions and 14 deletions.
9 changes: 9 additions & 0 deletions .github/workflows/image.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,15 @@ jobs:
type=ref,event=pr
type=semver,pattern={{version}}
- name: Store Git Info
run: |
cat > git-info.json <<EOF
{
"branch": "$(git rev-parse --abbrev-ref HEAD)",
"commitHash": "$(git rev-parse HEAD)"
}
EOF
- name: Build and push
uses: docker/build-push-action@v6
with:
Expand Down
14 changes: 0 additions & 14 deletions package-lock.json

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

10 changes: 10 additions & 0 deletions src/components/layout/footer.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { NaLink } from "@/components/na-link";
import { siteConfig } from "@/site/config";
import { getGitInfo } from "@/utils/git-info";
import { clsx } from "clsx";
import React from "react";

export async function Footer() {
const year = new Date().getFullYear()
const gitInfo = await getGitInfo()
const gitBranchUrl = gitInfo && `${siteConfig.links.githubWebsite}/tree/${gitInfo.branch}`
const gitCommitUrl = gitInfo && `${siteConfig.links.githubWebsite}/tree/${gitInfo.commitHash}`
return (
<footer className={clsx(
"max-w-screen-xl w-full",
Expand All @@ -18,6 +22,12 @@ export async function Footer() {
<div className="flex gap-5">
<NaLink href={siteConfig.links.githubMcdr} hoverColor>MCDReforged</NaLink>
<NaLink href={siteConfig.links.githubWebsite} hoverColor>Website source</NaLink>
{gitInfo &&
<p>
<NaLink href={gitBranchUrl!}>{gitBranchUrl}</NaLink>
<span>@</span>
<NaLink href={gitCommitUrl!}>{gitInfo.commitHash.slice(0, 8)}</NaLink>
</p>}
</div>
</div>
</footer>
Expand Down
106 changes: 106 additions & 0 deletions src/utils/git-info.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { ExecOptions } from "child_process";
import fs from "fs/promises"
import { exec } from "node:child_process"
import { promisify } from "node:util"

interface GitInfo {
branch: string
commitHash: string
}

let cachedGitInfo: GitInfo | undefined | null = null

export async function getGitInfo(): Promise<GitInfo | undefined> {
if (cachedGitInfo === null) {
cachedGitInfo = await getGitInfoImpl()
}
return cachedGitInfo
}

async function tryGetGitInfoFromCommand(): Promise<GitInfo | undefined> {
try {
const execAsync = promisify(exec)

const execOptions: ExecOptions = { timeout: 1500 }
const [branchResult, commitHashResult] = await Promise.all([
execAsync('git rev-parse --abbrev-ref HEAD', execOptions),
execAsync('git rev-parse HEAD', execOptions)
])

const branch = branchResult.stdout.trim()
const commitHash = commitHashResult.stdout.trim()
if (branch && commitHash) {
return { branch, commitHash }
}
} catch {
return undefined
}
}

async function checkFileExists(filePath: string): Promise<boolean> {
try {
const st = await fs.stat(filePath)
return st.isFile()
} catch {
return false
}
}

async function getGitInfoFromFile(): Promise<GitInfo | undefined> {
const filePath = 'git-info.json'
try {
if (await checkFileExists(filePath)) {
const data = await fs.readFile(filePath, 'utf8')
const gitInfo: GitInfo = JSON.parse(data)
if (gitInfo.branch && gitInfo.commitHash) {
return gitInfo
}
}
} catch (error) {
console.error('Failed to read or parse git-info.json:', error)
}
return undefined
}

function getEnvVar(...keys: string[]): string | undefined {
for (const key of keys) {
if (process.env[key]) {
return process.env[key]
}
}
}

function gitRefToBranch(gitRef: string): string {
const mappings = [
{prefix: 'refs/heads/', append: ''},
{prefix: 'refs/tags/', append: ''},
{prefix: 'refs/pull/', append: 'pr-'},
]

for (const {prefix, append} of mappings) {
if (gitRef.startsWith(prefix)) {
return append + gitRef.substring(prefix.length)
}
}
return gitRef
}

async function getGitInfoImpl(): Promise<GitInfo | undefined> {
if (process.env.NODE_ENV === 'development') {
return (await tryGetGitInfoFromCommand()) || {
branch: 'test',
commitHash: 'abc',
}
}

const gitInfoFromFile = await getGitInfoFromFile()
if (gitInfoFromFile) {
return gitInfoFromFile
}

const gitRef = getEnvVar('GIT_REF', 'GITHUB_REF')
const commitHash = getEnvVar('GIT_COMMIT_HASH', 'GITHUB_SHA', 'VERCEL_GIT_COMMIT_SHA')
const branch = gitRef ? gitRefToBranch(gitRef) : getEnvVar('VERCEL_GIT_COMMIT_REF')

return (branch && commitHash) ? {branch, commitHash} : undefined
}

0 comments on commit c1743ab

Please sign in to comment.