File size: 2,103 Bytes
2ec5eb1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import { spawn } from 'child_process';
import { execSync } from 'child_process';
import fs from 'fs';

const CHECK_INTERVAL = 60000; // Check every 60 seconds
let devProcess = null;

function log(msg) {
    console.log(`[Auto-Update Dev] ${new Date().toLocaleTimeString()} - ${msg}`);
}

function startDevServer() {
    if (devProcess) {
        log("Stopping current dev server...");
        devProcess.kill();
    }

    log("Starting dev server (npm run dev)...");
    devProcess = spawn('npm', ['run', 'dev'], { 
        stdio: 'inherit',
        shell: true 
    });

    devProcess.on('close', (code) => {
        if (code !== 0 && code !== null) {
            log(`Dev server exited with code ${code}. Restarting in 5s...`);
            setTimeout(startDevServer, 5000);
        }
    });
}

async function checkUpdates() {
    try {
        log("Checking for git updates...");
        execSync('git remote update');
        const status = execSync('git status -uno').toString();

        if (status.includes('Your branch is behind')) {
            log("πŸš€ New updates detected! Pulling changes...");
            
            // Get current package.json hash to see if we need npm install
            const pkgHashBefore = fs.readFileSync('package.json', 'utf8');
            
            execSync('git pull');
            log("βœ… Pull successful.");

            const pkgHashAfter = fs.readFileSync('package.json', 'utf8');
            if (pkgHashBefore !== pkgHashAfter) {
                log("πŸ“¦ package.json changed. Running npm install...");
                execSync('npm install', { stdio: 'inherit' });
            }

            log("πŸ”„ Restarting dev server to apply changes...");
            startDevServer();
        } else {
            log("🟒 Up to date.");
        }
    } catch (err) {
        log(`❌ Error during update check: ${err.message}`);
    }
}

// 1. Initial Start
startDevServer();

// 2. Set up polling loop
setInterval(checkUpdates, CHECK_INTERVAL);

log("Self-updating dev server is active.");
log("It will poll git every 60s and restart on changes.");