Skip to content

🎥 Make videos programmatically with React

11.9 KB
Raw Blame
import {
	chmodSync,
	copyFileSync,
	cpSync,
	readFileSync,
	readdirSync,
	writeFileSync,
} from 'node:fs';
import {tmpdir} from 'node:os';
import path from 'path';
import {$} from 'bun';
import {CreateVideoInternals} from 'create-video';

type MinimalTemplate = {
	shortName: string;
	org: string;
	repoName: string;
	defaultBranch: string;
	templateInMonorepo: string;
};

const folders = CreateVideoInternals.FEATURED_TEMPLATES.filter(
	(t) => t.templateInMonorepo !== null,
);

const skillsTemplate: MinimalTemplate = {
	defaultBranch: 'main',
	templateInMonorepo: 'skills',
	org: 'remotion-dev',
	repoName: 'skills',
	shortName: 'Skills',
};

const templates = [skillsTemplate, ...folders];

const publish = async (template: MinimalTemplate) => {
	const folder = path.join(
		__dirname,
		'..',
		'..',
		'..',
		template.templateInMonorepo as string,
	);

	const tmpDir = tmpdir();
	const workingDir = path.join(tmpDir, `template-${Math.random()}`);

	await $`git add .`.cwd(folder);
	const files = await $`git ls-files`.cwd(folder).quiet();
	const filesInTemplate = files.stdout
		.toString('utf-8')
		.trim()
		.split('\n')
		.filter(Boolean);

	await $`git clone [email protected]:${template.org}/${template.repoName}.git ${workingDir} --depth 1`;

	const defaultBranch = await $`git branch --show-current`
		.cwd(workingDir)
		.text();
	const existingFilesInRepo = await $`git ls-files`.cwd(workingDir).quiet();
	for (const file of existingFilesInRepo.stdout
		.toString('utf-8')
		.trim()
		.split('\n')) {
		if (file === '') continue;
		await $`rm ${file}`.cwd(workingDir).quiet();
	}

	for (const file of filesInTemplate) {
		const src = path.join(folder, file);
		const dst = path.join(workingDir, file);
		cpSync(src, dst, {dereference: true, recursive: true});

		if (file === 'package.json') {
			const dstFile = await Bun.file(dst).text();
			const currentVersion = dstFile.replaceAll('workspace:*', '^4.0.0');
			await Bun.write(dst, currentVersion);
		}
	}

	if (template.templateInMonorepo === 'skills') {
		const prepareEmbeddedSkillsScript = path.join(
			__dirname,
			'..',
			'..',
			'..',
			'skills',
			'scripts',
			'prepare-embedded-skills.ts',
		);
		await $`bun ${prepareEmbeddedSkillsScript} ${path.join(workingDir, 'skills')}`;
	}

	await $`git add .`.cwd(workingDir).nothrow();
	const hasChanges = await $`git status --porcelain`.cwd(workingDir).text();
	if (!hasChanges) {
		console.log(`No changes in ${template.shortName}`);
		return;
	}

	await $`git commit -m "Update template"`.cwd(workingDir);
	await $`git push origin ${defaultBranch.trim()}`.cwd(workingDir);
};

type AgentPluginPublishTarget = {
	commitMessage: string;
	filesToCopy: string[];
	manifestPaths: string[];
	name: string;
	readme?: string;
	repoName: string;
	skillsDir: string;
};

const publishBuiltAgentPlugin = async ({
	commitMessage,
	filesToCopy,
	manifestPaths,
	name,
	readme,
	repoName,
	skillsDir,
}: AgentPluginPublishTarget) => {
	const agentPluginDir = path.join(__dirname, '..', '..', '..', 'agent-plugin');

	const tmpDir = tmpdir();
	const workingDir = path.join(tmpDir, `${repoName}-${Math.random()}`);

	await $`git clone [email protected]:remotion-dev/${repoName}.git ${workingDir} --depth 1`;

	const defaultBranch = await $`git branch --show-current`
		.cwd(workingDir)
		.text();
	const existingFilesInRepo = await $`git ls-files`.cwd(workingDir).quiet();
	for (const file of existingFilesInRepo.stdout
		.toString('utf-8')
		.trim()
		.split('\n')) {
		if (file === '') continue;
		await $`rm ${file}`.cwd(workingDir).quiet();
	}

	for (const entry of filesToCopy) {
		const src =
			entry === 'skills' ? skillsDir : path.join(agentPluginDir, entry);
		const dst = path.join(workingDir, entry);
		cpSync(src, dst, {recursive: true});
	}
	if (readme) {
		cpSync(
			path.join(agentPluginDir, readme),
			path.join(workingDir, 'README.md'),
		);
	}

	const packageJson = JSON.parse(
		readFileSync(path.join(agentPluginDir, 'package.json'), 'utf-8'),
	);
	for (const manifestPath of manifestPaths) {
		const pluginJsonPath = path.join(workingDir, manifestPath);
		const pluginJson = JSON.parse(readFileSync(pluginJsonPath, 'utf-8'));
		writeFileSync(
			pluginJsonPath,
			`${JSON.stringify({...pluginJson, version: packageJson.version}, null, '\t')}\n`,
		);
	}

	await $`git add .`.cwd(workingDir).nothrow();
	const hasChanges = await $`git status --porcelain`.cwd(workingDir).text();
	if (!hasChanges) {
		console.log(`No changes in ${name}`);
		return;
	}

	await $`git commit -m ${commitMessage}`.cwd(workingDir);
	const versionTag = `v${packageJson.version}`;
	await $`git tag ${versionTag}`.cwd(workingDir);
	await $`git push --atomic origin ${defaultBranch.trim()} ${versionTag}`.cwd(
		workingDir,
	);
};

const publishAgentPlugins = async () => {
	const agentPluginDir = path.join(__dirname, '..', '..', '..', 'agent-plugin');
	const cursorSkillsDir = path.join(
		tmpdir(),
		`cursor-plugin-skills-${Math.random()}`,
	);

	await Promise.all([
		$`bun build.mts`.cwd(agentPluginDir),
		$`bun build.mts --client=cursor --output=${cursorSkillsDir}`.cwd(
			agentPluginDir,
		),
	]);

	await Promise.all([
		publishBuiltAgentPlugin({
			commitMessage: 'Update Agent Plugin',
			filesToCopy: ['LICENSE', 'plugin.json', 'skills'],
			manifestPaths: ['plugin.json'],
			name: 'agent-plugin',
			readme: 'README.cursor.md',
			repoName: 'agent-plugin',
			skillsDir: cursorSkillsDir,
		}),
		publishBuiltAgentPlugin({
			commitMessage: 'Update Codex plugin',
			filesToCopy: [
				'.codex-plugin',
				'assets',
				'LICENSE',
				'skills',
				'README.md',
			],
			manifestPaths: ['.codex-plugin/plugin.json'],
			name: 'codex-plugin',
			repoName: 'codex-plugin',
			skillsDir: path.join(agentPluginDir, 'skills'),
		}),
		publishBuiltAgentPlugin({
			commitMessage: 'Update Cursor plugin',
			filesToCopy: ['LICENSE', 'plugin.json', 'skills'],
			manifestPaths: ['plugin.json'],
			name: 'cursor-plugin',
			readme: 'README.cursor.md',
			repoName: 'cursor-plugin',
			skillsDir: cursorSkillsDir,
		}),
	]);
};

const publishCanvasCapture = async () => {
	const monorepoDir = path.join(__dirname, '..', '..', '..', '..');
	const packageDir = path.join(
		monorepoDir,
		'packages',
		'canvas-capture-extension',
	);
	const workingDir = path.join(tmpdir(), `canvas-capture-${Math.random()}`);

	await $`bun run make`.cwd(packageDir);
	await $`git clone [email protected]:remotion-dev/canvas-capture.git ${workingDir} --depth 1`;

	const defaultBranch = await $`git branch --show-current`
		.cwd(workingDir)
		.text();
	const existingFilesInRepo = await $`git ls-files`.cwd(workingDir).quiet();
	for (const file of existingFilesInRepo.stdout
		.toString('utf-8')
		.trim()
		.split('\n')) {
		if (file === '') continue;
		await $`rm ${file}`.cwd(workingDir).quiet();
	}

	const distDir = path.join(packageDir, 'dist');
	for (const entry of readdirSync(distDir)) {
		cpSync(path.join(distDir, entry), path.join(workingDir, entry), {
			recursive: true,
		});
	}
	copyFileSync(
		path.join(packageDir, 'README.public.md'),
		path.join(workingDir, 'README.md'),
	);
	const installBrowserPath = path.join(workingDir, 'install-browser.sh');
	copyFileSync(
		path.join(packageDir, 'scripts', 'install-browser.sh'),
		installBrowserPath,
	);
	chmodSync(installBrowserPath, 0o755);
	copyFileSync(
		path.join(monorepoDir, 'LICENSE.md'),
		path.join(workingDir, 'LICENSE.md'),
	);

	await $`git add .`.cwd(workingDir).nothrow();
	const hasChanges = await $`git status --porcelain`.cwd(workingDir).text();
	if (!hasChanges) {
		console.log('No changes in Canvas Capture');
		return;
	}

	const packageJson = JSON.parse(
		readFileSync(path.join(packageDir, 'package.json'), 'utf-8'),
	);
	await $`git commit -m "Update Canvas Capture"`.cwd(workingDir);
	const versionTag = `v${packageJson.version}`;
	await $`git tag ${versionTag}`.cwd(workingDir);
	await $`git push --atomic origin ${defaultBranch.trim()} ${versionTag}`.cwd(
		workingDir,
	);
};

const publishClaudeCodePlugin = async () => {
	const claudeCodePluginDir = path.join(
		__dirname,
		'..',
		'..',
		'..',
		'claude-code-plugin',
	);

	// Run the build step to assemble skills
	await $`bun build.mts`.cwd(claudeCodePluginDir);

	const tmpDir = tmpdir();
	const workingDir = path.join(tmpDir, `claude-code-plugin-${Math.random()}`);

	await $`git clone [email protected]:remotion-dev/claude-code-plugin.git ${workingDir} --depth 1`;

	const defaultBranch = await $`git branch --show-current`
		.cwd(workingDir)
		.text();
	const existingFilesInRepo = await $`git ls-files`.cwd(workingDir).quiet();
	for (const file of existingFilesInRepo.stdout
		.toString('utf-8')
		.trim()
		.split('\n')) {
		if (file === '') continue;
		await $`rm ${file}`.cwd(workingDir).quiet();
	}

	const filesToCopy = ['.claude-plugin', 'skills', 'README.md'];
	for (const entry of filesToCopy) {
		const src = path.join(claudeCodePluginDir, entry);
		const dst = path.join(workingDir, entry);
		cpSync(src, dst, {recursive: true});
	}

	const packageJson = JSON.parse(
		readFileSync(path.join(claudeCodePluginDir, 'package.json'), 'utf-8'),
	);
	const pluginJsonPath = path.join(workingDir, '.claude-plugin', 'plugin.json');
	const pluginJson = JSON.parse(readFileSync(pluginJsonPath, 'utf-8'));
	writeFileSync(
		pluginJsonPath,
		`${JSON.stringify({...pluginJson, version: packageJson.version}, null, '\t')}\n`,
	);

	await $`git add .`.cwd(workingDir).nothrow();
	const hasChanges = await $`git status --porcelain`.cwd(workingDir).text();
	if (!hasChanges) {
		console.log('No changes in claude-code-plugin');
		return;
	}

	await $`git commit -m "Update Claude Code plugin"`.cwd(workingDir);
	await $`git push origin ${defaultBranch.trim()}`.cwd(workingDir);
};

const publishKimiCodePlugin = async () => {
	const kimiCodePluginDir = path.join(
		__dirname,
		'..',
		'..',
		'..',
		'kimi-code-plugin',
	);

	// Run the build step to assemble skills
	await $`bun build.mts`.cwd(kimiCodePluginDir);

	const tmpDir = tmpdir();
	const workingDir = path.join(tmpDir, `kimi-code-plugin-${Math.random()}`);

	await $`git clone [email protected]:remotion-dev/kimi-code-plugin.git ${workingDir} --depth 1`;

	const defaultBranch = await $`git branch --show-current`
		.cwd(workingDir)
		.text();
	const existingFilesInRepo = await $`git ls-files`.cwd(workingDir).quiet();
	for (const file of existingFilesInRepo.stdout
		.toString('utf-8')
		.trim()
		.split('\n')) {
		if (file === '') continue;
		await $`rm ${file}`.cwd(workingDir).quiet();
	}

	const filesToCopy = ['.kimi-plugin', 'skills', 'README.md'];
	for (const entry of filesToCopy) {
		const src = path.join(kimiCodePluginDir, entry);
		const dst = path.join(workingDir, entry);
		cpSync(src, dst, {recursive: true});
	}

	const packageJson = JSON.parse(
		readFileSync(path.join(kimiCodePluginDir, 'package.json'), 'utf-8'),
	);
	const pluginJsonPath = path.join(workingDir, '.kimi-plugin', 'plugin.json');
	const pluginJson = JSON.parse(readFileSync(pluginJsonPath, 'utf-8'));
	writeFileSync(
		pluginJsonPath,
		`${JSON.stringify({...pluginJson, version: packageJson.version}, null, '\t')}\n`,
	);

	await $`git add .`.cwd(workingDir).nothrow();
	const hasChanges = await $`git status --porcelain`.cwd(workingDir).text();
	if (!hasChanges) {
		console.log('No changes in kimi-code-plugin');
		return;
	}

	await $`git commit -m "Update Kimi Code plugin"`.cwd(workingDir);
	await $`git push origin ${defaultBranch.trim()}`.cwd(workingDir);
};

const CONCURRENCY = 1;

const results: PromiseSettledResult<void>[] = [];

for (let i = 0; i < templates.length; i += CONCURRENCY) {
	const batch = templates.slice(i, i + CONCURRENCY);
	const batchResults = await Promise.allSettled(
		batch.map((template) => publish(template)),
	);
	results.push(...batchResults);
}

results.push(
	...(await Promise.allSettled([
		publishAgentPlugins(),
		publishCanvasCapture(),
		publishClaudeCodePlugin(),
		publishKimiCodePlugin(),
	])),
);

const failures = results.filter(
	(r): r is PromiseRejectedResult => r.status === 'rejected',
);

if (failures.length > 0) {
	console.error(`${failures.length} template(s) failed to publish:`);
	for (const failure of failures) {
		console.error(failure.reason);
	}

	process.exit(1);
}