git precommit hooks

This commit is contained in:
cpu
2025-05-09 16:57:06 +02:00
parent c656af0009
commit ba26edf8be
6 changed files with 122 additions and 15 deletions

1
.githooks/pre-commit Symbolic link
View File

@@ -0,0 +1 @@
../scripts/git-hooks/pre-commit.cjs

View File

@@ -177,7 +177,30 @@ curl https://nexus-timer.virtonline.eu
Or open it in your browser: Or open it in your browser:
[https://nexus-timer.virtonline.eu](https://nexus-timer.virtonline.eu) [https://nexus-timer.virtonline.eu](https://nexus-timer.virtonline.eu)
### Update the app ## Developer Setup
### Clone the repository
```bash
git clone https://gitea.virtonline.eu/2HoursProject/nexus-timer.git
cd nexus-timer
```
### Git Pre-Commit Hook
This project uses a Git pre-commit hook to automatically updates the build timestamp placeholder in `src/views/InfoView.vue` and increments the `CACHE_VERSION` in `public/service-worker.js` (it is the indicator for the installed PWA that the new version is available). This ensures that each commit intended for a build/deployment reflects the correct information.
**Setup Steps:**
1. **Ensure Node.js is installed.** The hook script is written in Node.js.
2. **Configure Git to use the local hooks directory:**
After cloning the repository, run the following command in your terminal from the project root to tell Git to use the hooks located in the `.githooks` directory:
```bash
git config core.hooksPath .githooks
```
This step needs to be done once per local clone of the repository.
3. **Ensure the hook script is executable:**
The script `scripts/git-hooks/pre-commit.js` is the source, and it's copied/symlinked to `.githooks/pre-commit`. If you manually copy or if permissions are lost, ensure the hook in `.githooks` is executable:
```bash
chmod +x .githooks/pre-commit
```
(The main script in `scripts/git-hooks/` should also be executable if you plan to run it manually for testing: `chmod +x scripts/git-hooks/pre-commit.js`)
### Modify the app
Make code changes... Make code changes...
Run the live update server locally Run the live update server locally
@@ -188,11 +211,6 @@ npm run dev
Open it in your browser: Open it in your browser:
[http://localhost:8080/](http://localhost:8080/) [http://localhost:8080/](http://localhost:8080/)
When done, do not forget to update the `CACHE_VERSION` in the `service-worker.js`. It is the indicator for the PWA that the new version is available.
```bash
ver=$(grep -oP "CACHE_VERSION = 'nexus-timer-cache-v\K[0-9]+" public/service-worker.js)
sed -i "s/nexus-timer-cache-v$ver/nexus-timer-cache-v$((ver+1))/" public/service-worker.js
```
Stage changes, commit and push Stage changes, commit and push
```bash ```bash
git add . git add .

View File

@@ -1,7 +1,7 @@
{ {
"name": "Nexus Timer - Multiplayer Turn Timer", "name": "Nexus Timer - Multiplayer Turn Timer",
"short_name": "NexusTimer", "short_name": "NexusTimer",
"description": "Dynamic multiplayer timer for games, workshops, or sequential turns. Focuses on current & next player.", // Add a description "description": "Dynamic multiplayer timer for games, workshops, or sequential turns. Focuses on current & next player.",
"start_url": "/", "start_url": "/",
"scope": "/", "scope": "/",
"display": "standalone", "display": "standalone",
@@ -9,8 +9,6 @@
"background_color": "#1f2937", "background_color": "#1f2937",
"theme_color": "#3b82f6", "theme_color": "#3b82f6",
"orientation": "portrait", "orientation": "portrait",
"version": "0.0.1",
"version_name": "0.0.1",
"lang": "en-US", "lang": "en-US",
"icons": [ "icons": [
{ {

View File

@@ -1,4 +1,4 @@
const CACHE_VERSION = 'nexus-timer-cache-v6'; const CACHE_VERSION = 'nexus-timer-cache-v7';
const APP_SHELL_URLS = [ const APP_SHELL_URLS = [
// '/', // Let NetworkFirst handle '/' // '/', // Let NetworkFirst handle '/'
'/manifest.json', '/manifest.json',

View File

@@ -0,0 +1,71 @@
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const projectRoot = path.resolve(__dirname, '../..'); // Adjust if script is deeper
const infoViewFile = path.join(projectRoot, 'src/views/InfoView.vue');
const serviceWorkerFile = path.join(projectRoot, 'public/service-worker.js');
console.log('Running pre-commit hook...');
// --- 1. Update Build Time in InfoView.vue ---
try {
let infoViewContent = fs.readFileSync(infoViewFile, 'utf8');
const buildTimePlaceholder = '__BUILD_TIME__';
// Using a more robust regex to find the placeholder within the ref assignment
const buildTimeRegex = /const buildTime = ref\s*\(\s*["']__BUILD_TIME__["']\s*\);/;
if (infoViewContent.includes(buildTimePlaceholder)) { // Check if placeholder exists
const now = new Date();
const timestamp = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
// Replace the placeholder string within the ref() call
infoViewContent = infoViewContent.replace(
`ref("${buildTimePlaceholder}")`,
`ref("${timestamp}")`
);
// Or, if your placeholder is part of a more complex line:
// infoViewContent = infoViewContent.replace(
// buildTimeRegex,
// `const buildTime = ref("${timestamp}");`
// );
fs.writeFileSync(infoViewFile, infoViewContent, 'utf8');
console.log(`Updated build time in ${path.basename(infoViewFile)} to: ${timestamp}`);
execSync(`git add "${infoViewFile}"`, { stdio: 'inherit' });
} else {
console.log(`Placeholder ${buildTimePlaceholder} not found in ${path.basename(infoViewFile)}. Skipping build time update.`);
}
} catch (error) {
console.error(`Error updating build time in ${infoViewFile}:`, error);
process.exit(1); // Exit with error
}
// --- 2. Increment Service Worker Cache Version ---
try {
let swContent = fs.readFileSync(serviceWorkerFile, 'utf8');
const cacheVersionRegex = /const CACHE_VERSION = ['"](nexus-timer-cache-v)(\d+)['"];/;
const match = swContent.match(cacheVersionRegex);
if (match && match[1] && match[2]) {
const prefix = match[1];
const currentVersion = parseInt(match[2], 10);
const newVersion = currentVersion + 1;
const newCacheVersionLine = `const CACHE_VERSION = '${prefix}${newVersion}';`;
swContent = swContent.replace(cacheVersionRegex, newCacheVersionLine);
fs.writeFileSync(serviceWorkerFile, swContent, 'utf8');
console.log(`Updated Service Worker cache version in ${path.basename(serviceWorkerFile)} to: v${newVersion}`);
execSync(`git add "${serviceWorkerFile}"`, { stdio: 'inherit' });
} else {
console.warn(`Could not find or parse CACHE_VERSION in ${path.basename(serviceWorkerFile)}. Skipping version increment.`);
}
} catch (error) {
console.error(`Error updating Service Worker cache version in ${serviceWorkerFile}:`, error);
process.exit(1); // Exit with error
}
console.log('Pre-commit hook finished successfully.');
process.exit(0); // Exit successfully

View File

@@ -1,7 +1,11 @@
<template> <template>
<div class="flex-grow flex flex-col p-4 md:p-6 lg:p-8 items-center dark:bg-gray-800 text-gray-700 dark:text-gray-200"> <div class="flex-grow flex flex-col p-4 md:p-6 lg:p-8 items-center dark:bg-gray-800 text-gray-700 dark:text-gray-200">
<header class="w-full max-w-2xl mb-6 text-center"> <header class="w-full max-w-2xl mb-2 text-center"> <!-- Reduced mb for tighter spacing -->
<h1 class="text-3xl font-bold text-blue-600 dark:text-blue-400 mb-4">About Nexus Timer</h1> <h1 class="text-3xl font-bold text-blue-600 dark:text-blue-400 mb-1">About Nexus Timer</h1>
<!-- Build Time Information -->
<p class="text-xs text-gray-500 dark:text-gray-400 mb-4">
Build: <span class="font-mono">{{ buildTime }}</span>
</p>
</header> </header>
<main class="w-full max-w-2xl bg-white dark:bg-gray-700 p-6 rounded-lg shadow-md prose dark:prose-invert"> <main class="w-full max-w-2xl bg-white dark:bg-gray-700 p-6 rounded-lg shadow-md prose dark:prose-invert">
@@ -22,6 +26,7 @@
<li>Audio feedback for timer events.</li> <li>Audio feedback for timer events.</li>
<li>Light/Dark theme options.</li> <li>Light/Dark theme options.</li>
<li>Persistent storage of game state.</li> <li>Persistent storage of game state.</li>
<li>Screen Wake Lock to keep screen on during active gameplay.</li> <!-- Added Wake Lock to features -->
</ul> </ul>
<h2 class="text-xl font-semibold mt-6 mb-2">Source Code</h2> <h2 class="text-xl font-semibold mt-6 mb-2">Source Code</h2>
@@ -42,14 +47,24 @@
</template> </template>
<script setup> <script setup>
import { ref } from 'vue'; // Import ref
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import { useStore } from 'vuex'; import { useStore } from 'vuex';
const router = useRouter(); const router = useRouter();
const store = useStore(); // Get store instance const store = useStore();
// --- Build Time Placeholder ---
// This value will be replaced by your Git pre-commit hook.
// The hook should search for the string "__BUILD_TIME__" (including quotes if you prefer)
// and replace it with the actual build timestamp.
// For display, we'll use a ref.
const buildTime = ref("2025-05-09 16:57:06");
// If your hook replaces the entire line `const buildTime = ref("__BUILD_TIME__");`
// with `const buildTime = ref("YYYY-MM-DD HH:MM:SS");`, that's also fine.
// Or, if it replaces only the string content: `const buildTime = ref("Actual Build Time");`
const goBack = () => { const goBack = () => {
// Check if there are players to decide between game and setup
if (store.getters.players && store.getters.players.length >= 2) { if (store.getters.players && store.getters.players.length >= 2) {
router.push({ name: 'Game' }); router.push({ name: 'Game' });
} else { } else {
@@ -57,3 +72,7 @@ const goBack = () => {
} }
}; };
</script> </script>
<style scoped>
/* Tailwind's typography plugin 'prose' handles most styling */
</style>