async function protectBranch()

in packages/repocop/src/remediation/branch-protector/branch-protection.ts [71:112]


async function protectBranch(
	octokit: Octokit,
	config: Config,
	event: UpdateMessageEvent,
) {
	const [owner, repo] = event.fullName.split('/');

	if (!owner || !repo) {
		throw new Error(`Invalid repo name: ${event.fullName}`);
	}

	let defaultBranchName = undefined;
	try {
		defaultBranchName = await getDefaultBranchName(owner, repo, octokit);
	} catch (error) {
		throw new Error(`Could not find default branch for repo: ${repo}`);
	}

	const branchIsProtected = await isBranchProtected(
		octokit,
		owner,
		repo,
		defaultBranchName,
	);

	const stageIsProd = config.stage === 'PROD';

	if (stageIsProd && !branchIsProtected && config.branchProtectionEnabled) {
		await updateBranchProtection(octokit, owner, repo, defaultBranchName);
		for (const slug of event.teamNameSlugs) {
			await notify(event.fullName, config, slug);
		}
		console.log(`Notified teams ${event.teamNameSlugs.join(', ')}}`);
	} else {
		const reason =
			(branchIsProtected ? ' Branch is already protected.' : '') +
			(!stageIsProd ? ' Not running on PROD.' : '') +
			(!config.branchProtectionEnabled
				? ' Branch protection is disabled.'
				: '');
		console.log(`No action required for ${repo}. ${reason}`);
	}