import simpleGit, { SimpleGit } from "simple-git"; import fs from "fs"; import path from "path"; import os from "os"; import { SyncConfig } from "./ConfigTypes"; import axios from "axios"; export function getRepoLocalPath(config: SyncConfig): string { // Logic to determine repoLocalPath return ( config.centralRepo.localPath || path.join( os.homedir(), ".code-sync", "central-repos", path.basename(config.centralRepo.url) ) ); } export async function cloneOrUpdateRepo(config: SyncConfig): Promise { const git: SimpleGit = simpleGit(); // Determine the local path for the central repo const repoLocalPath = getRepoLocalPath(config); try { if (!fs.existsSync(repoLocalPath)) { // Clone if the repo does not exist locally await git.clone(config.centralRepo.url, repoLocalPath); console.log(`Repository cloned to ${repoLocalPath}`); } else { await git.cwd(repoLocalPath).checkout(config.centralRepo.branch); // Pull updates if the repo exists await git.cwd(repoLocalPath).pull(); console.log(`Repository updated at ${repoLocalPath}`); } // NEW: Checkout to a specific version if specified if (config.options.defaultVersion) { await git.cwd(repoLocalPath).checkout(config.options.defaultVersion); console.log(`Checked out to version '${config.options.defaultVersion}'`); } else if (config.centralRepo.branch) { await git.cwd(repoLocalPath).checkout(config.centralRepo.branch); console.log(`Checked out to branch '${config.centralRepo.branch}'`); } } catch (error: any) { console.error( "Error in cloning/updating the repository:", error.response.data.errors ); throw error; // Rethrow the error for further handling if necessary } } async function createNewBranchInCentralRepo( centralRepoPath: string, branchName: string ): Promise { const git: SimpleGit = simpleGit(centralRepoPath); try { await git.checkout(["-b", branchName]); } catch (error) { console.error("Error creating new branch in central repository:", error); throw error; } } function copyUpdatedFilesToCentralRepo( config: SyncConfig, centralRepoPath: string, updatedFiles: string[], configFilePath: string ) { updatedFiles.forEach((fileRelativePath) => { const clientFilePath = path.join( path.dirname(configFilePath), fileRelativePath ); const centralRepoFilePath = path.join(centralRepoPath, fileRelativePath); // Check if the client file path is a directory or a file if (fs.lstatSync(clientFilePath).isDirectory()) { // Handle directory (you might need to implement a recursive copy function) recursiveCopyDirectory(clientFilePath, centralRepoFilePath); } else { // Handle file const centralRepoDir = path.dirname(centralRepoFilePath); if (!fs.existsSync(centralRepoDir)) { fs.mkdirSync(centralRepoDir, { recursive: true }); } fs.copyFileSync(clientFilePath, centralRepoFilePath); } }); } function recursiveCopyDirectory(sourceDir: string, targetDir: string) { if (!fs.existsSync(targetDir)) { fs.mkdirSync(targetDir, { recursive: true }); } const files = fs.readdirSync(sourceDir); files.forEach((file) => { const sourceFile = path.join(sourceDir, file); const targetFile = path.join(targetDir, file); if (fs.lstatSync(sourceFile).isDirectory()) { recursiveCopyDirectory(sourceFile, targetFile); } else { fs.copyFileSync(sourceFile, targetFile); } }); } async function commitAndPushChanges( centralRepoPath: string, branchName: string ): Promise { const git: SimpleGit = simpleGit(centralRepoPath); try { await git.add("./*"); await git.commit("Updated files from client repo"); await git.push("origin", branchName); } catch (error) { console.error( "Error committing and pushing changes to central repository:", error ); throw error; } } async function createPullRequest( repo: string, base: string, head: string, title: string, body: string, token: string ) { const url = `https://api.github.com/repos/${repo}/pulls`; console.log("PR Body", { title, head, base, body, }); try { const response = await axios.post( url, { title, head, base, body, }, { headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github.v3+json", }, } ); console.log(`Pull request created: ${response.data.html_url}`); } catch (error: any) { console.error("Error creating pull request:", error.response.data); throw { message: "Failed creating PR", }; } } export async function updateCentralRepository( config: SyncConfig, configFilePath: string ) { const clientRepoPath = path.dirname(configFilePath); const centralRepoPath = getRepoLocalPath(config); // Assuming getRepoLocalPath returns the local path of the central repo // Step 1: Detect updated files let updatedFiles: any = []; // Assume this is filled with paths of updated files for (const item of config.syncItems) { const clientFilePath = path.join(clientRepoPath, item.destinationPath); const centralRepoFilePath = path.join(centralRepoPath, item.sourcePath); // Check if the client file is more recent than the central repo file if ( fs.existsSync(clientFilePath) && (!fs.existsSync(centralRepoFilePath) || fs.statSync(clientFilePath).mtime > fs.statSync(centralRepoFilePath).mtime) ) { updatedFiles.push(item.destinationPath); } } // Assuming GitHub repo details and token are part of config const githubToken = config.githubToken; const githubRepo = config.githubRepo; // 'username/repo' const baseBranch = config.centralRepo.branch; const headBranch = `update-${new Date().getTime()}`; // Step 2: Create a new branch in the central repository await createNewBranchInCentralRepo(centralRepoPath, headBranch); // Step 3: Copy the updated files from the client repo to the new branch in the central repo copyUpdatedFilesToCentralRepo( config, centralRepoPath, updatedFiles, configFilePath ); // Step 4: Commit and push these changes to the central repo await commitAndPushChanges(centralRepoPath, headBranch); const prTitle = "Updates from client repository"; const prBody = "This PR includes recent updates from the client repository."; // Step 5: Create a pull request await createPullRequest( githubRepo, baseBranch, headBranch, prTitle, prBody, githubToken ); }