🎥 Make videos programmatically with React
`@remotion/studio`: Add GitHub.com to "Open in..." menu (#10364)
Jonny Burger1a60a2916da5
diff --git a/packages/cli/src/get-github-repository.ts b/packages/cli/src/get-github-repository.tsindex dcb6459772..869762eea8 100644--- a/packages/cli/src/get-github-repository.ts+++ b/packages/cli/src/get-github-repository.ts@@ -1,5 +1,5 @@-import {execSync} from 'child_process';-import {existsSync, readFileSync} from 'fs';+import {execFileSync} from 'child_process';+import {existsSync, readFileSync, statSync} from 'fs';import path from 'path';import {BundlerInternals} from '@remotion/bundler';import type {LogLevel} from '@remotion/renderer';@@ -39,16 +39,37 @@ const getGitRemotes = (lines: string[]) => {});};+const getGitRoot = (remotionRoot: string) => {+ return BundlerInternals.findClosestFolderWithItem(remotionRoot, '.git');+};+export const getGitConfig = (remotionRoot: string) => {- const gitFolder = BundlerInternals.findClosestFolderWithItem(- remotionRoot,- '.git',- );- if (!gitFolder) {+ const gitRoot = getGitRoot(remotionRoot);+ if (!gitRoot) {return null;}- const gitConfig = path.join(gitFolder, '.git', 'config');+ const dotGit = path.join(gitRoot, '.git');+ let gitDirectory = dotGit;+ if (!statSync(dotGit).isDirectory()) {+ const match = readFileSync(dotGit, 'utf-8')+ .trim()+ .match(/^gitdir:\s*(.+)$/);+ if (!match?.[1]) {+ return null;+ }++ gitDirectory = path.resolve(gitRoot, match[1]);+ const commonDirectoryFile = path.join(gitDirectory, 'commondir');+ if (existsSync(commonDirectoryFile)) {+ gitDirectory = path.resolve(+ gitDirectory,+ readFileSync(commonDirectoryFile, 'utf-8').trim(),+ );+ }+ }++ const gitConfig = path.join(gitDirectory, 'config');if (!existsSync(gitConfig)) {return null;}@@ -98,14 +119,29 @@ export const normalizeGitRemoteUrl = (url: string): ParsedGitRemote | null => {return null;};-export const getGifRef = (logLevel: LogLevel): string | null => {+export const getGifRef = (+ logLevel: LogLevel,+ remotionRoot = process.cwd(),+): string | null => {try {- const ret = execSync('git rev-parse --abbrev-ref HEAD', {+ const branch = execFileSync(+ 'git',+ ['-C', remotionRoot, 'rev-parse', '--abbrev-ref', 'HEAD'],+ {+ stdio: ['ignore', 'pipe', 'ignore'],+ },+ )+ .toString('utf-8')+ .trim();+ if (branch !== 'HEAD') {+ return branch;+ }++ return execFileSync('git', ['-C', remotionRoot, 'rev-parse', 'HEAD'], {stdio: ['ignore', 'pipe', 'ignore'],}).toString('utf-8').trim();- return ret;} catch (err) {Log.verbose({logLevel, indent: false}, 'Could not get git ref', err);return null;@@ -126,9 +162,8 @@ const getFromEnvVariables = (remotionRoot: string): GitSource | null => {VERCEL_GIT_PROVIDER === 'github') {let relativeFromGitRoot = '';- const gitConfig = getGitConfig(remotionRoot);- if (gitConfig) {- const gitRoot = path.dirname(path.dirname(gitConfig));+ const gitRoot = getGitRoot(remotionRoot);+ if (gitRoot) {relativeFromGitRoot = path.relative(gitRoot, remotionRoot);}@@ -162,7 +197,7 @@ export const getGitSource = ({return fromEnv;}- const ref = getGifRef(logLevel);+ const ref = getGifRef(logLevel, remotionRoot);if (!ref) {return null;}@@ -182,7 +217,11 @@ export const getGitSource = ({return null;}- const gitRoot = path.dirname(path.dirname(gitConfig));+ const gitRoot = getGitRoot(remotionRoot);+ if (!gitRoot) {+ return null;+ }+const relativeFromGitRoot = path.relative(gitRoot, remotionRoot);return {diff --git a/packages/cli/src/test/get-github-repo.test.ts b/packages/cli/src/test/get-github-repo.test.tsindex dcfd0dd904..5f6eb54ec6 100644--- a/packages/cli/src/test/get-github-repo.test.ts+++ b/packages/cli/src/test/get-github-repo.test.ts@@ -1,4 +1,7 @@import {expect, test} from 'bun:test';+import {execFileSync} from 'node:child_process';+import {mkdirSync, mkdtempSync, rmSync, writeFileSync} from 'node:fs';+import {tmpdir} from 'node:os';import path from 'node:path';import {getGifRef,@@ -62,6 +65,81 @@ test('Should get Git Source', () => {expect(git?.relativeFromGitRoot).toBe(`packages${path.sep}cli`);});+test('Should get Git Source from a linked worktree', () => {+ const temporaryDirectory = mkdtempSync(+ path.join(tmpdir(), 'remotion-git-source-'),+ );+ const mainCheckout = path.join(temporaryDirectory, 'main');+ const linkedWorktree = path.join(temporaryDirectory, 'linked');++ try {+ mkdirSync(mainCheckout);+ execFileSync('git', ['-C', mainCheckout, 'init'], {stdio: 'ignore'});+ writeFileSync(path.join(mainCheckout, 'README.md'), 'Remotion');+ execFileSync('git', ['-C', mainCheckout, 'add', 'README.md'], {+ stdio: 'ignore',+ });+ execFileSync(+ 'git',+ [+ '-C',+ mainCheckout,+ '-c',+ 'user.name=Remotion Test',+ '-c',+ '[email protected]',+ 'commit',+ '-m',+ 'Initial commit',+ ],+ {stdio: 'ignore'},+ );+ execFileSync(+ 'git',+ [+ '-C',+ mainCheckout,+ 'remote',+ 'add',+ 'origin',+ 'https://github.com/remotion-dev/remotion.git',+ ],+ {stdio: 'ignore'},+ );+ execFileSync(+ 'git',+ ['-C', mainCheckout, 'worktree', 'add', '--detach', linkedWorktree],+ {stdio: 'ignore'},+ );+ const remotionRoot = path.join(linkedWorktree, 'packages', 'example');+ mkdirSync(remotionRoot, {recursive: true});+ const commit = execFileSync('git', [+ '-C',+ linkedWorktree,+ 'rev-parse',+ 'HEAD',+ ])+ .toString('utf-8')+ .trim();++ expect(+ getGitSource({+ remotionRoot,+ disableGitSource: false,+ logLevel: 'info',+ }),+ ).toEqual({+ name: 'remotion',+ org: 'remotion-dev',+ ref: commit,+ relativeFromGitRoot: path.join('packages', 'example'),+ type: 'github',+ });+ } finally {+ rmSync(temporaryDirectory, {force: true, recursive: true});+ }+});+test('Should recognize VERCEL', () => {process.env.VERCEL_GIT_COMMIT_SHA = '123';process.env.VERCEL_GIT_PROVIDER = 'github';diff --git a/packages/example/e2e/studio.test.mts b/packages/example/e2e/studio.test.mtsindex 87594b7431..d608823d10 100644--- a/packages/example/e2e/studio.test.mts+++ b/packages/example/e2e/studio.test.mts@@ -987,6 +987,28 @@ test.describe('visual mode', () => {await expect(page.getByRole('button', {name: 'Cursor', exact: true}),).toHaveCount(2);+ const gitHubButton = page.getByRole('button', {+ name: 'GitHub.com',+ exact: true,+ });+ await expect(gitHubButton).toBeVisible();+ await expect(gitHubButton.locator('[data-github-icon]')).toBeVisible();+ await page.evaluate(() => {+ document.body.dataset.openedUrl = '';+ window.open = (url) => {+ document.body.dataset.openedUrl = String(url);+ return null;+ };+ });+ await gitHubButton.click();+ await expect+ .poll(() => page.evaluate(() => document.body.dataset.openedUrl ?? ''))+ .toMatch(+ /^https:\/\/github\.com\/remotion-dev\/remotion\/blob\/.+\/packages\/example\/src\/BarChart\.tsx#L\d+$/,+ );++ await timelineGridline.click({button: 'right'});+ await page.getByRole('button', {name: 'Open in...', exact: true}).click();await page.getByRole('button', {name: 'Change default apps...', exact: true}).click();diff --git a/packages/studio/src/components/InspectorOpenInEditor.tsx b/packages/studio/src/components/InspectorOpenInEditor.tsxindex c056da5b4c..8c9b197b61 100644--- a/packages/studio/src/components/InspectorOpenInEditor.tsx+++ b/packages/studio/src/components/InspectorOpenInEditor.tsx@@ -173,6 +173,7 @@ export const InspectorOpenInEditor: React.FC<{excludeEditorId: preferredEditorId,fileManagerDisabled: !location?.source,folder: locationType === 'folder',+ location,onConfigureApps: () => {setSelectedModal({type: 'settings',diff --git a/packages/studio/src/components/Timeline/get-sequence-context-menu-items.ts b/packages/studio/src/components/Timeline/get-sequence-context-menu-items.tsindex 37885975ef..edc7068fbd 100644--- a/packages/studio/src/components/Timeline/get-sequence-context-menu-items.ts+++ b/packages/studio/src/components/Timeline/get-sequence-context-menu-items.ts@@ -117,6 +117,7 @@ export const getSequenceContextMenuItems = ({excludeEditorId: defaultEditorId,fileManagerDisabled: !originalLocation?.source,folder: false,+ location: originalLocation,onConfigureApps,onOpenInCodingAgent: openInCodingAgentWithContext,onOpenInEditor: openInEditor,diff --git a/packages/studio/src/components/get-open-in-menu-items.tsx b/packages/studio/src/components/get-open-in-menu-items.tsxindex e2cef0c638..88a5646ef0 100644--- a/packages/studio/src/components/get-open-in-menu-items.tsx+++ b/packages/studio/src/components/get-open-in-menu-items.tsx@@ -6,9 +6,16 @@ import type {GetDefaultEditorInfoResponse,} from '@remotion/studio-shared';import React from 'react';+import {NoReactInternals} from 'remotion/no-react';+import type {OriginalPosition} from '../error-overlay/react-overlay/utils/get-source-map';import {getFileManagerName} from '../helpers/get-file-manager-name';+import {+ getGitRefUrl,+ getGitSourceBranchUrl,+} from '../helpers/get-git-menu-item';import {EditorIcon} from '../icons/editor';import {FinderIcon} from '../icons/finder';+import {GitHubIcon} from '../icons/github';import {TerminalIcon} from '../icons/terminal';import {CodingAgentIcon} from './CodingAgentIcon';import type {ComboboxValue} from './NewComposition/ComboBox';@@ -28,6 +35,7 @@ export const getOpenInMenuItems = ({excludeEditorId,fileManagerDisabled,folder,+ location,onConfigureApps,onOpenInCodingAgent,onOpenInEditor,@@ -41,6 +49,7 @@ export const getOpenInMenuItems = ({readonly excludeEditorId: EditorPickerId | null;readonly fileManagerDisabled: boolean;readonly folder: boolean;+ readonly location: OriginalPosition | null;readonly onConfigureApps: () => void;readonly onOpenInCodingAgent: (codingAgentId: DefaultCodingAgent,@@ -89,7 +98,54 @@ export const getOpenInMenuItems = ({value: `coding-agent-${codingAgent.id}`,}));const terminals = folder ? (codingAgentInfo?.installedTerminals ?? []) : [];- const showSystemApps = showFinder || terminals.length > 0;+ const gitHubItem: ComboboxValue | null = window.remotion_gitSource+ ? {+ id: 'open-in-github',+ keyHint: null,+ label: <span style={menuLabel}>GitHub.com</span>,+ leftItem: <GitHubIcon size={18} />,+ onClick: () => {+ const gitSource = window.remotion_gitSource;+ if (!gitSource) {+ return;+ }++ window.open(+ folder || !location+ ? getGitSourceBranchUrl(gitSource)+ : getGitRefUrl(gitSource, location, window.remotion_cwd),+ '_blank',+ );+ },+ quickSwitcherLabel: null,+ subMenu: null,+ type: 'item' as const,+ value: 'github',+ }+ : null;+ const systemApps: ComboboxValue[] = [+ gitHubItem,+ showFinder+ ? {+ disabled: fileManagerDisabled,+ id: 'open-in-file-explorer',+ keyHint: null,+ label: <span style={menuLabel}>{fileManagerName}</span>,+ leftItem: <FinderIcon size={18} />,+ onClick: () => {+ if (!fileManagerDisabled) {+ onOpenInFileExplorer();+ }+ },+ quickSwitcherLabel: null,+ subMenu: null,+ type: 'item' as const,+ value: 'file-explorer',+ }+ : null,+ ].filter(NoReactInternals.truthy);+ const hasCategorizedApps =+ editors.length > 0 || codingAgents.length > 0 || terminals.length > 0;return [...(editors.length > 0@@ -112,61 +168,40 @@ export const getOpenInMenuItems = ({...codingAgents,]: []),- ...(showSystemApps+ ...(terminals.length > 0? [- ...(terminals.length > 0- ? [- {- type: 'section-header' as const,- id: 'terminal-header',- label: 'Terminal',- },- ...terminals.map((terminal) => ({- id: `open-in-terminal-${terminal.id}`,- keyHint: null,- label: <span style={menuLabel}>{terminal.name}</span>,- leftItem: <TerminalIcon terminalId={terminal.id} size={18} />,- onClick: () => onOpenInTerminal?.(terminal.id),- quickSwitcherLabel: null,- subMenu: null,- type: 'item' as const,- value: `terminal-${terminal.id}`,- })),- ]- : []),- ...(showFinder+ {+ type: 'section-header' as const,+ id: 'terminal-header',+ label: 'Terminal',+ },+ ...terminals.map((terminal) => ({+ id: `open-in-terminal-${terminal.id}`,+ keyHint: null,+ label: <span style={menuLabel}>{terminal.name}</span>,+ leftItem: <TerminalIcon terminalId={terminal.id} size={18} />,+ onClick: () => onOpenInTerminal?.(terminal.id),+ quickSwitcherLabel: null,+ subMenu: null,+ type: 'item' as const,+ value: `terminal-${terminal.id}`,+ })),+ ]+ : []),+ ...(systemApps.length > 0+ ? [+ ...(hasCategorizedApps? [- ...(editors.length > 0 ||- codingAgents.length > 0 ||- terminals.length > 0- ? [- {- type: 'divider' as const,- id: 'open-in-file-explorer-divider',- },- ]- : []),{- disabled: fileManagerDisabled,- id: 'open-in-file-explorer',- keyHint: null,- label: <span style={menuLabel}>{fileManagerName}</span>,- leftItem: <FinderIcon size={18} />,- onClick: () => {- if (!fileManagerDisabled) {- onOpenInFileExplorer();- }- },- quickSwitcherLabel: null,- subMenu: null,- type: 'item' as const,- value: 'file-explorer',+ type: 'divider' as const,+ id: 'open-in-system-apps-divider',},]: []),+ ...systemApps,]: []),- ...(editors.length > 0 || codingAgents.length > 0 || showSystemApps+ ...(hasCategorizedApps || systemApps.length > 0? [{type: 'divider' as const, id: 'open-in-settings-divider'}]: []),{diff --git a/packages/studio/src/helpers/get-git-menu-item.ts b/packages/studio/src/helpers/get-git-menu-item.tsindex f50bbcb85f..f8c93399ba 100644--- a/packages/studio/src/helpers/get-git-menu-item.ts+++ b/packages/studio/src/helpers/get-git-menu-item.ts@@ -12,11 +12,14 @@ export const getGitSourceName = (gitSource: GitSource) => {export const getGitSourceBranchUrl = (gitSource: GitSource) => {if (gitSource.type === 'github') {+ const relativeFromGitRoot = gitSource.relativeFromGitRoot.replaceAll(+ '\\',+ '/',+ );+return `https://github.com/${gitSource.org}/${gitSource.name}/tree/${gitSource.ref- }${- gitSource.relativeFromGitRoot ? `/${gitSource.relativeFromGitRoot}` : ''- }`;+ }${relativeFromGitRoot ? `/${relativeFromGitRoot}` : ''}`;}throw new Error('Unknown git source type');@@ -25,13 +28,45 @@ export const getGitSourceBranchUrl = (gitSource: GitSource) => {export const getGitRefUrl = (gitSource: GitSource,originalLocation: OriginalPosition,+ remotionRoot: string,) => {if (gitSource.type === 'github') {- return `https://github.com/${gitSource.org}/${gitSource.name}/tree/${- gitSource.ref- }/${- gitSource.relativeFromGitRoot ? `${gitSource.relativeFromGitRoot}/` : ''- }${originalLocation.source}#L${originalLocation.line}`;+ if (!originalLocation.source) {+ return getGitSourceBranchUrl(gitSource);+ }++ const source = originalLocation.source.replaceAll('\\', '/');+ const root = remotionRoot.replaceAll('\\', '/').replace(/\/+$/, '');+ const shouldCompareCaseInsensitive =+ /^[a-z]:\//i.test(source) || /^[a-z]:\//i.test(root);+ const comparableSource = shouldCompareCaseInsensitive+ ? source.toLowerCase()+ : source;+ const comparableRoot = shouldCompareCaseInsensitive+ ? root.toLowerCase()+ : root;+ const sourceIsInsideRoot =+ root.length > 0 && comparableSource.startsWith(`${comparableRoot}/`);+ const relativeSource = sourceIsInsideRoot+ ? source.slice(root.length + 1)+ : source.replace(/^\.\/+/, '');++ if (/^(?:[a-z]:\/|\/)/i.test(relativeSource)) {+ return getGitSourceBranchUrl(gitSource);+ }++ const filePath = [+ gitSource.relativeFromGitRoot.replaceAll('\\', '/'),+ relativeSource,+ ]+ .filter(Boolean)+ .map((part) => part.replace(/^\/+|\/+$/g, ''))+ .join('/');+ const lineSuffix = originalLocation.line+ ? `#L${originalLocation.line}`+ : '';++ return `https://github.com/${gitSource.org}/${gitSource.name}/blob/${gitSource.ref}/${filePath}${lineSuffix}`;}throw new Error('Unknown git source type');diff --git a/packages/studio/src/icons/github.tsx b/packages/studio/src/icons/github.tsxnew file mode 100644index 0000000000..2248403b8b--- /dev/null+++ b/packages/studio/src/icons/github.tsx@@ -0,0 +1,23 @@+import React from 'react';+import {CURRENT_COLOR} from '../helpers/colors';++// Brand shape adapted from Simple Icons (CC0 1.0):+// https://github.com/simple-icons/simple-icons/blob/develop/icons/github.svg++export const GitHubIcon: React.FC<{+ readonly size: number;+}> = ({size}) => {+ return (+ <svg+ aria-hidden+ data-github-icon+ style={{flexShrink: 0, height: size, width: size}}+ viewBox="0 0 24 24"+ >+ <path+ d="M12 .3a12 12 0 0 0-3.79 23.39c.6.11.82-.26.82-.58v-2.23c-3.34.73-4.04-1.42-4.04-1.42-.55-1.39-1.34-1.76-1.34-1.76-1.09-.75.08-.73.08-.73 1.2.09 1.84 1.24 1.84 1.24 1.07 1.83 2.81 1.3 3.5.99.11-.78.42-1.31.76-1.61-2.67-.31-5.47-1.34-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.13-.3-.54-1.52.11-3.18 0 0 1.01-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.29-1.55 3.3-1.23 3.3-1.23.65 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.6-2.81 5.62-5.48 5.92.43.37.81 1.1.81 2.22v3.3c0 .32.22.7.82.58A12 12 0 0 0 12 .3Z"+ fill={CURRENT_COLOR}+ />+ </svg>+ );+};diff --git a/packages/studio/src/test/sequence-context-menu-items.test.ts b/packages/studio/src/test/sequence-context-menu-items.test.tsindex 096410d6d1..f3f285c0ba 100644--- a/packages/studio/src/test/sequence-context-menu-items.test.ts+++ b/packages/studio/src/test/sequence-context-menu-items.test.ts@@ -79,6 +79,7 @@ test('the file manager entry is only shown on macOS', () => {excludeEditorId: null,fileManagerDisabled: false,folder: false,+ location: null,onConfigureApps: noop,onOpenInCodingAgent: noop,onOpenInEditor: noop,