Made it work

This commit is contained in:
2024-12-27 13:45:55 +01:00
parent 8f4e00390a
commit 140961b482
2 changed files with 155 additions and 67 deletions

219
app.ts
View File

@@ -1,15 +1,21 @@
import * as core from "@actions/core";
import { spawn } from "child_process"; import { spawn } from "child_process";
import fs from "fs/promises"; import { ChildProcess, SpawnOptions } from "node:child_process";
import path from "path";
import {ChildProcess, SpawnOptions} from "node:child_process";
const myToken = core.getInput("branches");
// Ignored branches // Ignored branches
const IGNORED_BRANCHES = ["master", "main", "dev", "release"]; const IGNORED_BRANCHES = ["master", "main", "dev", "release"];
type BranchDependencies = Record<string, null | string>; const mainBranch = "main";
enum Action {
Rebase,
Reset
}
interface RebaseAction {
branch: string,
onBranch: string,
action: Action
}
/** /**
* Helper function to run a Git command and capture stdout and stderr. * Helper function to run a Git command and capture stdout and stderr.
@@ -44,63 +50,148 @@ const fetchBranches = async (): Promise<string[]> => {
.filter((branch) => !IGNORED_BRANCHES.includes(branch) && branch !== ""); .filter((branch) => !IGNORED_BRANCHES.includes(branch) && branch !== "");
} }
/**
* Detect dependencies between branches.
*/
const detectDependencies = async (branches: string[]): Promise<BranchDependencies> => {
console.log("Detecting dependencies...");
const dependencies: BranchDependencies = {};
// Get the full commit history for a branch
const getCommitsForBranch = async (branch: string): Promise<Set<string>> => {
const commits = await runGitCommand(["rev-list", branch]);
return new Set(commits.split("\n").filter(Boolean));
};
const removeIgnoredBranches = (branchesWithDependencies: Record<string, any>) => {
let withoutIgnoredBranches = {}
for (const [branch, value] of Object.entries(branchesWithDependencies)) {
if(!value.ignore) {
withoutIgnoredBranches[branch] = value;
}
}
return withoutIgnoredBranches;
}
// Build the dependency graph
const buildRebaseDependencyGraph = async (branches: string[]): Promise<any> => {
const commitHistories: Record<string, Set<string>> = {};
for (const branch of branches) { for (const branch of branches) {
dependencies[branch] = null; // Default: no dependency commitHistories[branch] = await getCommitsForBranch(branch);
}
for (const otherBranch of branches) { let finalBranches: Record<string, {
if (branch !== otherBranch) { rebaseBranch?: string
const base = await runGitCommand(["merge-base", `origin/${branch}`, `origin/${otherBranch}`]); differenceWithRebase?: number
const isAncestor = await runGitCommand(["merge-base", "--is-ancestor", base.trim(), `origin/${branch}`]).catch(() => false); equalBranches?: string[]
if (isAncestor) { ignore?: boolean
dependencies[branch] = otherBranch; }> = {};
break; for (const branchA of branches) {
for (const branchB of branches) {
if(branchA !== branchB) {
const infos = {
superset: commitHistories[branchA].isSupersetOf(commitHistories[branchB]),
difference: commitHistories[branchA].difference(commitHistories[branchB])
}
if (infos.superset) {
if(branchB === mainBranch) {
// SUPERSET OF MAIN BRANCH, MEANING ALREADY REBASED
finalBranches[branchA] = {
ignore: true
}
}
if (infos.difference.size === 0) {
const prevBranches: string[] = finalBranches[branchA]?.equalBranches ?? [];
finalBranches[branchA] = {
rebaseBranch: mainBranch,
...finalBranches[branchA],
equalBranches: [...prevBranches, branchB]
};
} else {
if (!finalBranches[branchA] || finalBranches[branchA].differenceWithRebase > infos.difference.size) {
if (branchA !== mainBranch) {
finalBranches[branchA] = {
...finalBranches[branchA],
rebaseBranch: branchB,
differenceWithRebase: infos.difference.size
};
}
}
}
} }
} }
} }
} }
return dependencies;
// Set rebase for branches with no dependencies
for (const branch of branches) {
if(branch !== mainBranch) {
finalBranches[branch] = finalBranches[branch] ?? {
rebaseBranch: mainBranch,
differenceWithRebase: 0
}
}
}
return removeIgnoredBranches(finalBranches);
};
const rebaseOrder = (branchesWithDependencies: any): RebaseAction[] => {
console.log("Order everything")
// First choose the right actions
let orderedActions: RebaseAction[] = []
for (const branch of Object.keys(branchesWithDependencies)) {
const alreadyRebasedEqualBranch = orderedActions.find(action => branchesWithDependencies[branch].equalBranches?.some(otherBranch => otherBranch === action.branch))
if(alreadyRebasedEqualBranch) {
orderedActions.push({
branch,
onBranch: alreadyRebasedEqualBranch.branch,
action: Action.Reset
})
} else {
orderedActions.push({
branch,
onBranch: branchesWithDependencies[branch].rebaseBranch,
action: Action.Rebase
});
}
}
// Then order by differenceWithRebase and then add resets
orderedActions = orderedActions.sort((a,b) => {
const diffA = branchesWithDependencies[a.branch].differenceWithRebase;
const diffB = branchesWithDependencies[b.branch].differenceWithRebase;
return diffA - diffB;
})
orderedActions = orderedActions.sort((a,b) => a.action - b.action)
return orderedActions;
} }
/** const rebaseBranch = async ({
* Perform a topological sort to determine the rebase order. branch,
*/ onBranch,
const determineRebaseOrder = (dependencies: BranchDependencies) => { action
console.log("Determining rebase order..."); }: RebaseAction) => {
const visited = new Set(); await runGitCommand([
const order = []; "checkout",
branch
const visit = (branch) => { ]);
if (visited.has(branch)) return; if(action === Action.Rebase) {
visited.add(branch); await runGitCommand([
if (dependencies[branch]) visit(dependencies[branch]); "rebase",
order.push(branch); onBranch
}; ]);
await runGitCommand([
Object.keys(dependencies).forEach((branch) => visit(branch)); "push",
return order; "--force-with-lease"
} ]);
} else {
/** await runGitCommand([
* Rebase a branch onto its base branch. "reset",
*/ "--hard",
const rebaseBranch = async (branch: string, baseBranch = "master"): Promise<void> => { onBranch
console.log(`Rebasing ${branch} onto ${baseBranch}...`); ]);
try { await runGitCommand([
await runGitCommand(["checkout", branch]); "push",
await runGitCommand(["fetch", "origin", baseBranch]); "--force-with-lease"
await runGitCommand(["rebase", `origin/${baseBranch}`]); ]);
console.log(`Rebase successful for ${branch}. Pushing...`);
await runGitCommand(["push", "--force-with-lease"]);
} catch (error) {
console.error(`Rebase failed for ${branch}: ${error.message}`);
await runGitCommand(["rebase", "--abort"]);
} }
} }
@@ -110,24 +201,20 @@ const rebaseBranch = async (branch: string, baseBranch = "master"): Promise<void
const main = async (): Promise<void> => { const main = async (): Promise<void> => {
try { try {
// Step 1: Fetch branches // Step 1: Fetch branches
const branches: string[] = await fetchBranches(); const branches: string[] = (await fetchBranches());
console.log(branches) branches.push(mainBranch)
await fs.writeFile(BRANCHES_FILE, branches.join("\n"), "utf-8");
console.log("Branches:", branches); console.log("Branches:", branches);
const dependencies = await buildRebaseDependencyGraph(branches);
// Step 2: Detect dependencies // Step 2: Detect dependencies
const dependencies = await detectDependencies(branches); console.log("Dependencies:", dependencies);
await fs.writeFile(DEPENDENCIES_FILE, JSON.stringify(dependencies, null, 2), "utf-8");
console.log("Dependencies:", dependencies);
// Step 3: Determine rebase order // Step 3: Determine rebase order
const order = determineRebaseOrder(dependencies); const order = rebaseOrder(dependencies);
console.log("Rebase order:", order); console.log("Rebase order:", order);
// Step 4: Rebase branches // Step 4: Rebase branches
for (const branch of order) { for (const rebaseAction of order) {
const baseBranch = dependencies[branch] || "master"; await rebaseBranch(rebaseAction);
await rebaseBranch(branch, baseBranch);
} }
} catch (error) { } catch (error) {
console.error("Error during workflow execution:", error.message); console.error("Error during workflow execution:", error.message);

View File

@@ -18,5 +18,6 @@
"esbuild": "^0.24.0", "esbuild": "^0.24.0",
"tsx": "^4.19.2", "tsx": "^4.19.2",
"typescript": "^5.7.2" "typescript": "^5.7.2"
} },
"packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
} }