const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
// --- CONFIGURATION ---
// IMPORTANT: Replace this with the actual GitHub repository URL.
const TARGET_REPO_URL = "https://github.com/example/target-repo";
const TARGET_BRANCH = "main"; // Change if needed
// ---------------------
/**
* Finds all deleted files in a Git repository's history.
* param {string} repoUrl - The URL of the GitHub repository.
* param {string} branchName - The branch to inspect (e.g., 'main').
* @returns {string[]} An array of file paths that were deleted.
*/
function findDeletedFiles(repoUrl, branchName) {
// Create a unique temporary directory for the clone
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'git-scan-'));
const deletedFiles = new Set();
console.log(`1. Cloning repository: ${repoUrl} into ${tempDir}...`);
try {
// Step 1: Clone the repository
// We clone to the temporary directory. The output is buffered but not printed.
execSync(`git clone ${repoUrl} ${tempDir} --branch ${branchName} --depth 1`, { stdio: 'pipe' });
// Fetch full history required to see all deletions
execSync('git fetch --unshallow', { cwd: tempDir, stdio: 'pipe' });
// Step 2: Use git log to check the history status for all files
console.log("2. Analyzing commit history for deleted files ('D' status)...");
// The command: git log --pretty=format: --name-status
const logOutput = execSync('git log --pretty=format: --name-status', {
cwd: tempDir
}).toString();
// Step 3: Parse the output to find files marked 'D' (Deleted)
const lines = logOutput.split('\n');
for (const line of lines) {
const trimmedLine = line.trim();
if (trimmedLine.startsWith('D\t')) {
// Line format is 'D\tpath/to/deleted/file'
const filePath = trimmedLine.substring(2).trim();
deletedFiles.add(filePath);
}
}
console.log("3. Analysis complete.");
} catch (error) {
console.error(`\n❌ ERROR: Could not execute Git command or clone repository. Check URL/Branch/Permissions.`);
console.error(`Details: ${error.message.trim()}`);
return null;
} finally {
// Cleanup: Remove the temporary directory
if (fs.existsSync(tempDir)) {
fs.rmSync(tempDir, { recursive: true, force: true });
console.log(`4. Cleaned up temporary directory: ${tempDir}`);
}
}
return Array.from(deletedFiles);
}
// --- EXECUTION ---
// We need the 'os' module for the temp directory path.
const os = require('os');
if (TARGET_REPO_URL === "https://github.com/example/target-repo") {
console.log("Please configure the TARGET_REPO_URL variable with the actual GitHub repository URL.");
} else {
const results = findDeletedFiles(TARGET_REPO_URL, TARGET_BRANCH);
if (results && results.length > 0) {
console.log(`\n✅ Found ${results.length} deleted file paths in the history of ${TARGET_REPO_URL}:\n`);
results.forEach(path => console.log(` - ${path}`));
} else if (results) {
console.log("\n✅ No deleted files were identified in the history.");
}
}