import simpleGit from 'simple-git'; import fs from 'fs'; import path from 'path'; // Format git URL with token if present function getAuthUrl(repoUrl, token) { if (!token) return repoUrl; try { const url = new URL(repoUrl); url.username = token; return url.toString(); } catch (e) { // If not a valid URL format, try basic string replace if (repoUrl.startsWith('https://')) { return `https://${token}@${repoUrl.substring(8)}`; } return repoUrl; } } // Clone repo export async function cloneRepo(repoUrl, destDir, branch = 'main', token = '') { fs.mkdirSync(destDir, { recursive: true }); const git = simpleGit(destDir); const authUrl = getAuthUrl(repoUrl, token); try { await git.clone(authUrl, '.', ['--branch', branch]); } catch (e) { // If it fails (e.g. because branch main doesn't exist yet on empty repo) try { console.log('Cloning failed or repo is empty. Initializing empty local repository...'); await git.init(); await git.addRemote('origin', authUrl); // Configure user details if not set try { await git.addConfig('user.name', 'MC Hoster Bot', false, 'local'); await git.addConfig('user.email', 'bot@mchoster.local', false, 'local'); } catch (configErr) {} // Create a dummy file to establish the branch fs.writeFileSync(path.join(destDir, '.gitignore'), '# Minecraft Server Data\nservers.json\n'); await git.add('.'); await git.commit('Initial commit'); await git.push('origin', 'main', ['-u']); } catch (innerErr) { console.error('Failed to initialize empty repository:', innerErr); throw e; // throw the original error if fallback also fails } } return true; } // Pull repo updates export async function pullRepo(destDir) { const git = simpleGit(destDir); const status = await git.status(); // If there are uncommitted changes, stash them first or commit them const result = await git.pull(); return result; } // Commit and Push repo updates export async function pushRepo(destDir, commitMessage = 'Auto-backup from MC Hoster Panel') { const git = simpleGit(destDir); // Configure user details if not set try { await git.addConfig('user.name', 'MC Hoster Bot', false, 'local'); await git.addConfig('user.email', 'bot@mchoster.local', false, 'local'); } catch (e) { console.error('Failed to configure git user info locally:', e); } await git.add('.'); const status = await git.status(); if (status.staged.length > 0 || status.not_added.length > 0 || status.modified.length > 0) { await git.commit(commitMessage); await git.push(); return true; } return false; }