|
| 1 | +import { execSync } from 'child_process'; |
| 2 | +import { existsSync, mkdirSync, readdirSync, renameSync, rmSync } from 'fs'; |
| 3 | +import { tmpdir } from 'os'; |
| 4 | +import { join } from 'path'; |
| 5 | + |
| 6 | +const REPO_URL = 'https://github.com/nrwl/nx-ai-agents-config'; |
| 7 | +const CACHE_DIR = join(tmpdir(), 'nx-ai-agents-config'); |
| 8 | + |
| 9 | +/** |
| 10 | + * Get the latest commit hash from the remote repository. |
| 11 | + * Uses `git ls-remote` to fetch the HEAD commit hash without cloning. |
| 12 | + */ |
| 13 | +function getLatestCommitHash(): string { |
| 14 | + try { |
| 15 | + const output = execSync(`git ls-remote ${REPO_URL} HEAD`, { |
| 16 | + encoding: 'utf-8', |
| 17 | + stdio: ['pipe', 'pipe', 'pipe'], |
| 18 | + timeout: 30000, // 30 second timeout |
| 19 | + }); |
| 20 | + const hash = output.split('\t')[0]; |
| 21 | + if (!hash || hash.length < 10) { |
| 22 | + throw new Error('Invalid commit hash received'); |
| 23 | + } |
| 24 | + // Return first 10 characters of the commit hash |
| 25 | + return hash.substring(0, 10); |
| 26 | + } catch (error) { |
| 27 | + throw new Error( |
| 28 | + `Failed to fetch latest commit hash from ${REPO_URL}. Please check your network connection.` |
| 29 | + ); |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * Clone the repository to the specified path using shallow clone. |
| 35 | + */ |
| 36 | +function cloneRepo(targetPath: string): void { |
| 37 | + try { |
| 38 | + // Ensure parent directory exists |
| 39 | + mkdirSync(CACHE_DIR, { recursive: true }); |
| 40 | + |
| 41 | + // Use a temporary path first to avoid race conditions |
| 42 | + const tempPath = `${targetPath}.tmp.${process.pid}`; |
| 43 | + |
| 44 | + // Clean up any leftover temp directory |
| 45 | + if (existsSync(tempPath)) { |
| 46 | + rmSync(tempPath, { recursive: true, force: true }); |
| 47 | + } |
| 48 | + |
| 49 | + execSync(`git clone --depth 1 ${REPO_URL} "${tempPath}"`, { |
| 50 | + encoding: 'utf-8', |
| 51 | + stdio: ['pipe', 'pipe', 'pipe'], |
| 52 | + timeout: 120000, // 2 minute timeout for clone |
| 53 | + }); |
| 54 | + |
| 55 | + // Remove .git directory after clone |
| 56 | + const gitDir = join(tempPath, '.git'); |
| 57 | + if (existsSync(gitDir)) { |
| 58 | + rmSync(gitDir, { recursive: true, force: true }); |
| 59 | + } |
| 60 | + |
| 61 | + // Atomically move temp directory to final location |
| 62 | + // If targetPath already exists (race condition), just clean up temp |
| 63 | + if (existsSync(targetPath)) { |
| 64 | + rmSync(tempPath, { recursive: true, force: true }); |
| 65 | + } else { |
| 66 | + // Rename is atomic on the same filesystem |
| 67 | + try { |
| 68 | + renameSync(tempPath, targetPath); |
| 69 | + } catch { |
| 70 | + // Rename failed - check if another process won the race |
| 71 | + if (existsSync(targetPath)) { |
| 72 | + // Another process created it, clean up our temp |
| 73 | + rmSync(tempPath, { recursive: true, force: true }); |
| 74 | + } else { |
| 75 | + // targetPath still doesn't exist - retry once |
| 76 | + try { |
| 77 | + renameSync(tempPath, targetPath); |
| 78 | + } catch (retryError) { |
| 79 | + // Clean up and fail |
| 80 | + rmSync(tempPath, { recursive: true, force: true }); |
| 81 | + throw new Error( |
| 82 | + `Failed to move cloned repository to cache location: ${(retryError as Error).message}` |
| 83 | + ); |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + } catch (error) { |
| 89 | + // Re-throw if it's already our error (from rename failure) |
| 90 | + if (error instanceof Error && error.message.startsWith('Failed to move')) { |
| 91 | + throw error; |
| 92 | + } |
| 93 | + throw new Error( |
| 94 | + `Failed to clone ${REPO_URL}. Please check your network connection.` |
| 95 | + ); |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +/** |
| 100 | + * Clean up old cached versions, keeping only the current one. |
| 101 | + */ |
| 102 | +function cleanupOldCaches(currentCommitHash: string): void { |
| 103 | + if (!existsSync(CACHE_DIR)) { |
| 104 | + return; |
| 105 | + } |
| 106 | + |
| 107 | + try { |
| 108 | + const entries = readdirSync(CACHE_DIR, { withFileTypes: true }); |
| 109 | + for (const entry of entries) { |
| 110 | + if (entry.isDirectory() && entry.name !== currentCommitHash) { |
| 111 | + const oldCachePath = join(CACHE_DIR, entry.name); |
| 112 | + rmSync(oldCachePath, { recursive: true, force: true }); |
| 113 | + } |
| 114 | + } |
| 115 | + } catch { |
| 116 | + // Ignore cleanup errors - not critical |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +/** |
| 121 | + * Get the path to the cached nx-ai-agents-config repository. |
| 122 | + * Uses a commit-hash based caching strategy: |
| 123 | + * 1. Fetches the latest commit hash from the remote repository |
| 124 | + * 2. Checks if a cached version exists for that hash |
| 125 | + * 3. If not, clones the repository and cleans up old caches |
| 126 | + * |
| 127 | + * @returns The path to the cached repository |
| 128 | + * @throws Error if unable to fetch or clone the repository |
| 129 | + */ |
| 130 | +export function getAiConfigRepoPath(): string { |
| 131 | + // 1. Get latest commit hash (first 10 chars) |
| 132 | + const commitHash = getLatestCommitHash(); |
| 133 | + |
| 134 | + // 2. Check if cached version exists |
| 135 | + const cachedPath = join(CACHE_DIR, commitHash); |
| 136 | + if (existsSync(cachedPath)) { |
| 137 | + return cachedPath; |
| 138 | + } |
| 139 | + |
| 140 | + // 3. Clone fresh |
| 141 | + cloneRepo(cachedPath); |
| 142 | + |
| 143 | + // 4. Clean up old cached versions |
| 144 | + cleanupOldCaches(commitHash); |
| 145 | + |
| 146 | + return cachedPath; |
| 147 | +} |
0 commit comments