Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Init github integration

Joshen Lim48d5e326f6cc
diff --git a/studio/components/interfaces/App/RouteValidationWrapper.tsx b/studio/components/interfaces/App/RouteValidationWrapper.tsx
index 8e9ef20f0f6..38e325bbbc7 100644
--- a/studio/components/interfaces/App/RouteValidationWrapper.tsx
+++ b/studio/components/interfaces/App/RouteValidationWrapper.tsx
@@ -68,7 +68,7 @@ const RouteValidationWrapper = ({ children }: PropsWithChildren<{}>) => {
// Check validity of project that the user is trying to access
const projects = projectsRef.current ?? []
const isValidProject = projects.some((project) => project.ref === ref)
- const isValidBranch = projects.some((project) => project.preview_branch_refs.includes(ref))
+ const isValidBranch = projects.some((project) => project.preview_branch_refs?.includes(ref))
if (!isValidProject && !isValidBranch) {
ui.setNotification({ category: 'error', message: 'This project does not exist' })
diff --git a/studio/components/interfaces/BranchManagement/BranchManagement.tsx b/studio/components/interfaces/BranchManagement/BranchManagement.tsx
index cbe3798f39b..3e47554e824 100644
--- a/studio/components/interfaces/BranchManagement/BranchManagement.tsx
+++ b/studio/components/interfaces/BranchManagement/BranchManagement.tsx
@@ -1,4 +1,5 @@
import { partition } from 'lodash'
+import { useRouter } from 'next/router'
import { useState } from 'react'
import { Button, IconSearch, Input } from 'ui'
@@ -15,7 +16,6 @@ import CreateBranchSidePanel from './CreateBranchSidePanel'
import PreviewBranches from './PreviewBranches'
import PullRequests from './PullRequests'
import UpdateBranchSidePanel from './UpdateBranchSidePanel'
-import { useRouter } from 'next/router'
const BranchManagement = () => {
const { ui } = useStore()
@@ -73,7 +73,10 @@ const BranchManagement = () => {
{isError && <AlertError error={error} subject="Failed to retrieve branches" />}
{isSuccess && (
<>
- <MainBranchPanel branch={mainBranch} onSelectUpdate={() => {}} />
+ <MainBranchPanel
+ branch={mainBranch}
+ onSelectUpdate={() => setSelectedBranchToUpdate(mainBranch)}
+ />
<PullRequests previewBranches={previewBranches} />
<PreviewBranches
previewBranches={previewBranches}
diff --git a/studio/components/interfaces/BranchManagement/CreateBranchSidePanel.tsx b/studio/components/interfaces/BranchManagement/CreateBranchSidePanel.tsx
index 7ca6d3f87af..6d7ed02114e 100644
--- a/studio/components/interfaces/BranchManagement/CreateBranchSidePanel.tsx
+++ b/studio/components/interfaces/BranchManagement/CreateBranchSidePanel.tsx
@@ -1,32 +1,82 @@
-import { useRef } from 'react'
-import { Button, Form, Input, Listbox, SidePanel } from 'ui'
+import { useRef, useState } from 'react'
+import {
+ Button,
+ CommandEmpty_Shadcn_,
+ CommandGroup_Shadcn_,
+ CommandInput_Shadcn_,
+ CommandItem_Shadcn_,
+ CommandList_Shadcn_,
+ Command_Shadcn_,
+ Form,
+ IconCheck,
+ IconCode,
+ Listbox,
+ PopoverContent_Shadcn_,
+ PopoverTrigger_Shadcn_,
+ Popover_Shadcn_,
+ SidePanel,
+} from 'ui'
import { useParams } from 'common'
+import AlertError from 'components/ui/AlertError'
+import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { useBranchCreateMutation } from 'data/branches/branch-create-mutation'
-import { useSelectedProject, useStore } from 'hooks'
+import { useGithubBranchesQuery } from 'data/integrations/integrations-github-branches-query'
+import { useOrgIntegrationsQuery } from 'data/integrations/integrations-query-org-only'
+import { useSelectedOrganization, useSelectedProject, useStore } from 'hooks'
interface CreateBranchSidePanelProps {
visible: boolean
onClose: () => void
}
-const MOCK_BRANCHES = [
- { id: 1, name: 'feat/branch-01' },
- { id: 2, name: 'feat/branch-02' },
-]
+// [Joshen] Optimization: Remove Form component, just use Combobox
const CreateBranchSidePanel = ({ visible, onClose }: CreateBranchSidePanelProps) => {
const { ui } = useStore()
- const submitRef: any = useRef()
const { ref } = useParams()
+ const submitRef: any = useRef()
const projectDetails = useSelectedProject()
+ const selectedOrg = useSelectedOrganization()
+
+ const [open, setOpen] = useState(false)
+ const [selectedBranch, setSelectedBranch] = useState('---')
const isBranch = projectDetails?.parent_project_ref !== undefined
const projectRef =
projectDetails !== undefined ? (isBranch ? projectDetails.parent_project_ref : ref) : undefined
const formId = 'create-branch-form'
- const initialValues = { branchName: '', gitBranch: 'no-selection' }
+ const initialValues = { gitBranch: 'no-selection' }
+
+ const {
+ data: integrations,
+ error: integrationsError,
+ isLoading: isLoadingIntegrations,
+ isSuccess: isSuccessIntegrations,
+ isError: isErrorIntegrations,
+ } = useOrgIntegrationsQuery({
+ orgSlug: selectedOrg?.slug,
+ })
+ const githubIntegration = integrations?.find(
+ (integration) =>
+ integration.integration.name === 'GitHub' &&
+ integration.connections.some((connection) => connection.supabase_project_ref === projectRef)
+ )
+ const repositoryMeta = githubIntegration?.connections?.[0]
+ const [repoOwner, repoName] = repositoryMeta?.metadata.name.split('/') || []
+ const {
+ data: githubBranches,
+ error: githubBranchesError,
+ isLoading: isLoadingBranches,
+ isSuccess: isSuccessBranches,
+ isError: isErrorBranches,
+ } = useGithubBranchesQuery({
+ organizationIntegrationId: githubIntegration?.id,
+ repoOwner,
+ repoName,
+ })
+
const { mutate: createBranch, isLoading: isCreating } = useBranchCreateMutation({
onSuccess: () => {
ui.setNotification({ category: 'success', message: `Successfully created new branch` })
@@ -36,18 +86,93 @@ const CreateBranchSidePanel = ({ visible, onClose }: CreateBranchSidePanelProps)
const validate = (values: any) => {
const errors: any = {}
- if (values.branchName.length === 0)
- errors.branchName = 'Please provide a name for your preview branch'
if (values.gitBranch.length === 0 || values.gitBranch === 'no-selection')
- errors.gitBranch = 'Please select a Git branch to link to this database preview branch'
+ errors.gitBranch = 'Please select a Git branch to link to this preview branch'
return errors
}
const onConfirmCreate = (values: any) => {
if (!projectRef) return console.error('Project ref is required')
- createBranch({ projectRef, ...values })
+ createBranch({ projectRef, ...values, branchName: values.gitBranch })
}
+ return (
+ <SidePanel
+ visible={visible}
+ loading={isCreating}
+ onCancel={onClose}
+ onConfirm={() => {}}
+ header="Create a new database preview branch"
+ >
+ <div className="py-6">
+ <SidePanel.Content>
+ {(isLoadingIntegrations || isLoadingBranches) && (
+ <div>
+ <p className="text-sm prose mb-2">
+ Select a Git branch to create a database preview from
+ </p>
+ <ShimmeringLoader className="py-4" />
+ </div>
+ )}
+ {(isErrorIntegrations || isErrorBranches) && (
+ <AlertError
+ error={integrationsError || githubBranchesError}
+ subject="Failed to retrieve Github branches"
+ />
+ )}
+ {isSuccessIntegrations && isSuccessBranches && (
+ <Popover_Shadcn_ open={open} onOpenChange={setOpen} modal={false}>
+ <PopoverTrigger_Shadcn_ asChild>
+ <div className="space-y-2">
+ <p className="text-sm prose mb-2">
+ Select a Git branch to create a database preview from
+ </p>
+ <div className="bg-surface-200 border border-scale-700 w-full py-2 rounded-md h-[38px] flex items-center justify-between px-4">
+ <p className="text-sm">{selectedBranch}</p>
+ <IconCode className="text-scale-1100 rotate-90" strokeWidth={2} size={12} />
+ </div>
+ </div>
+ </PopoverTrigger_Shadcn_>
+ <PopoverContent_Shadcn_ className="p-0" side="bottom" align="start">
+ <Command_Shadcn_>
+ <CommandInput_Shadcn_ placeholder="Find branch..." />
+ <CommandList_Shadcn_>
+ <CommandEmpty_Shadcn_>No branches found</CommandEmpty_Shadcn_>
+ <CommandGroup_Shadcn_>
+ {githubBranches?.map((branch) => {
+ return (
+ <CommandItem_Shadcn_
+ asChild
+ key={branch.name}
+ value={branch.name}
+ className="cursor-pointer w-full flex items-center justify-between"
+ onSelect={() => {
+ setSelectedBranch(branch.name)
+ setOpen(false)
+ }}
+ onClick={() => {
+ setSelectedBranch(branch.name)
+ setOpen(false)
+ }}
+ >
+ <div className="w-full flex items-center justify-between">
+ {branch.name}
+ {branch.name === selectedBranch && <IconCheck />}
+ </div>
+ </CommandItem_Shadcn_>
+ )
+ })}
+ </CommandGroup_Shadcn_>
+ </CommandList_Shadcn_>
+ </Command_Shadcn_>
+ </PopoverContent_Shadcn_>
+ </Popover_Shadcn_>
+ )}
+ </SidePanel.Content>
+ </div>
+ </SidePanel>
+ )
+
return (
<SidePanel
visible={visible}
@@ -90,28 +215,47 @@ const CreateBranchSidePanel = ({ visible, onClose }: CreateBranchSidePanelProps)
{() => {
return (
<div className="space-y-6">
- <Input id="branchName" label="Branch name" />
- <Listbox size="medium" id="gitBranch" name="gitBranch" label="Git branch">
- <Listbox.Option
- label="---"
- key="no-selection"
- id="no-selection"
- value="no-selection"
+ {(isLoadingIntegrations || isLoadingBranches) && (
+ <div>
+ <p className="text-sm prose mb-2">
+ Select a Git branch to create a database preview from
+ </p>
+ <ShimmeringLoader className="py-4" />
+ </div>
+ )}
+ {(isErrorIntegrations || isErrorBranches) && (
+ <AlertError
+ error={integrationsError || githubBranchesError}
+ subject="Failed to retrieve Github branches"
+ />
+ )}
+ {isSuccessIntegrations && isSuccessBranches && (
+ <Listbox
+ size="medium"
+ id="gitBranch"
+ name="gitBranch"
+ label="Select a Git branch to create a database preview from"
>
- ---
- </Listbox.Option>
- {MOCK_BRANCHES.map((branch) => (
<Listbox.Option
- key={branch.id}
- id={branch.id.toString()}
- value={branch.name}
- label={branch.name}
+ label="---"
+ key="no-selection"
+ id="no-selection"
+ value="no-selection"
>
- <p className="text-scale-1200">{branch.name}</p>
+ ---
</Listbox.Option>
- ))}
- </Listbox>
-
+ {githubBranches?.map((branch) => (
+ <Listbox.Option
+ key={branch.name}
+ id={branch.name}
+ value={branch.name}
+ label={branch.name}
+ >
+ <p className="text-scale-1200">{branch.name}</p>
+ </Listbox.Option>
+ ))}
+ </Listbox>
+ )}
<button ref={submitRef} type="submit" className="hidden" />
</div>
)
diff --git a/studio/data/api.d.ts b/studio/data/api.d.ts
index 8a16ffd26b7..6047bd3dbab 100644
--- a/studio/data/api.d.ts
+++ b/studio/data/api.d.ts
@@ -714,6 +714,30 @@ export interface paths {
/** Deletes vercel project connection */
delete: operations["VercelConnectionsController_deleteVercelConnection"];
};
+ "/platform/integrations/github": {
+ /** Create github integration */
+ post: operations["GitHubIntegrationController_createGitHubIntegration"];
+ };
+ "/platform/integrations/github/connections/{organization_integration_id}": {
+ /** Gets installed github project connections for the given organization integration */
+ get: operations["GitHubConnectionsController_getGitHubConnections"];
+ };
+ "/platform/integrations/github/connections": {
+ /** Connects a GitHub project to a supabase project */
+ post: operations["GitHubConnectionsController_createGitHubConnection"];
+ };
+ "/platform/integrations/github/connections/{connection_id}": {
+ /** Deletes github project connection */
+ delete: operations["GitHubConnectionsController_deleteGitHubConnection"];
+ };
+ "/platform/integrations/github/repos/{organization_integration_id}": {
+ /** Gets github repos for the given organization */
+ get: operations["GitHubRepoController_getRepos"];
+ };
+ "/platform/integrations/github/branches/{organization_integration_id}/{repo_owner}/{repo_name}": {
+ /** Gets github branches for a given repo */
+ get: operations["GitHubBranchController_getBranches"];
+ };
"/system/auth/{ref}/templates/{template}": {
/** Gets GoTrue template */
get: operations["AuthTemplateController_getTemplate"];
@@ -794,6 +818,10 @@ export interface paths {
/** Processes Vercel event */
post: operations["VercelWebhooksController_processEvent"];
};
+ "/system/integrations/github/webhooks": {
+ /** Processes GitHub event */
+ post: operations["GitHubWebhooksController_processEvent"];
+ };
"/system/stripe/webhooks-v2": {
/** Processes Stripe event */
post: operations["StripeWebhooksController_processEvent"];
@@ -3126,7 +3154,6 @@ export interface components {
id: string;
name: string;
project_ref: string;
- parent_project_ref: string;
is_default: boolean;
git_branch: string;
created_at: string;
@@ -3153,7 +3180,6 @@ export interface components {
maxDatabasePreprovisionGb?: number;
lastDatabaseResizeAt?: string;
preview_branches: (components["schemas"]["BranchResponse"])[];
- parent_project_ref?: string;
};
ProjectRefResponse: {
id: number;
@@ -3178,7 +3204,7 @@ export interface components {
back_ups: (components["schemas"]["BackupId"])[];
};
RestartServiceRequest: {
- services: ("adminapi" | "api-gateway" | "functions" | "gotrue" | "kong" | "pgbouncer" | "pgsodium" | "postgresql" | "postgrest" | "realtime" | "storage" | "walg")[];
+ services: ("adminapi" | "api-gateway" | "functions" | "gotrue" | "kong" | "pgbouncer" | "pgsodium" | "postgresql" | "postgrest" | "realtime" | "storage" | "walg" | "autoshutdown")[];
source_notification_id?: string;
region: string;
};
@@ -3851,6 +3877,34 @@ export interface components {
DeleteVercelConnectionResponse: {
id: string;
};
+ CreateGitHubIntegrationBody: {
+ installation_id: number;
+ organization_slug: string;
+ metadata: Record<string, never>;
+ };
+ CreateGitHubIntegrationResponse: {
+ id: string;
+ };
+ GetGitHubConnections: {
+ id: string;
+ inserted_at: string;
+ updated_at: string;
+ organization_integration_id: string;
+ supabase_project_ref: string;
+ foreign_project_id: string;
+ metadata: Record<string, never>;
+ };
+ CreateGitHubConnectionsBody: {
+ organization_integration_id: string;
+ connection: components["schemas"]["IntegrationConnection"];
+ };
+ GetGithubRepo: {
+ id: number;
+ full_name: string;
+ };
+ GetGithubBranch: {
+ name: string;
+ };
FunctionResponse: {
id: string;
slug: string;
@@ -8415,6 +8469,102 @@ export interface operations {
500: never;
};
};
+ /** Create github integration */
+ GitHubIntegrationController_createGitHubIntegration: {
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["CreateGitHubIntegrationBody"];
+ };
+ };
+ responses: {
+ 201: {
+ content: {
+ "application/json": components["schemas"]["CreateGitHubIntegrationResponse"];
+ };
+ };
+ /** @description Failed to create github integration */
+ 500: never;
+ };
+ };
+ /** Gets installed github project connections for the given organization integration */
+ GitHubConnectionsController_getGitHubConnections: {
+ parameters: {
+ path: {
+ organization_integration_id: string;
+ };
+ };
+ responses: {
+ 200: {
+ content: {
+ "application/json": (components["schemas"]["GetGitHubConnections"])[];
+ };
+ };
+ /** @description Failed to get installed github connections for the given organization integration */
+ 500: never;
+ };
+ };
+ /** Connects a GitHub project to a supabase project */
+ GitHubConnectionsController_createGitHubConnection: {
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["CreateGitHubConnectionsBody"];
+ };
+ };
+ responses: {
+ 201: never;
+ /** @description Failed to create project connections */
+ 500: never;
+ };
+ };
+ /** Deletes github project connection */
+ GitHubConnectionsController_deleteGitHubConnection: {
+ parameters: {
+ path: {
+ connection_id: string;
+ };
+ };
+ responses: {
+ 200: never;
+ /** @description Failed to delete github integration project connection */
+ 500: never;
+ };
+ };
+ /** Gets github repos for the given organization */
+ GitHubRepoController_getRepos: {
+ parameters: {
+ path: {
+ organization_integration_id: string;
+ };
+ };
+ responses: {
+ 200: {
+ content: {
+ "application/json": (components["schemas"]["GetGithubRepo"])[];
+ };
+ };
+ /** @description Failed to get github repos for the given organization */
+ 500: never;
+ };
+ };
+ /** Gets github branches for a given repo */
+ GitHubBranchController_getBranches: {
+ parameters: {
+ path: {
+ organization_integration_id: string;
+ repo_owner: string;
+ repo_name: string;
+ };
+ };
+ responses: {
+ 200: {
+ content: {
+ "application/json": (components["schemas"]["GetGithubBranch"])[];
+ };
+ };
+ /** @description Failed to get github branches for a given repo */
+ 500: never;
+ };
+ };
/** Gets GoTrue template */
AuthTemplateController_getTemplate: {
parameters: {
@@ -8776,6 +8926,25 @@ export interface operations {
500: never;
};
};
+ /** Processes GitHub event */
+ GitHubWebhooksController_processEvent: {
+ parameters: {
+ header: {
+ "x-github-delivery": string;
+ "x-hub-signature-256": string;
+ };
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["Buffer"];
+ };
+ };
+ responses: {
+ 201: never;
+ /** @description Failed to process GitHub event */
+ 500: never;
+ };
+ };
/** Processes Stripe event */
StripeWebhooksController_processEvent: {
parameters: {
diff --git a/studio/data/integrations/integrations-github-branches-query.ts b/studio/data/integrations/integrations-github-branches-query.ts
new file mode 100644
index 00000000000..c894ec47223
--- /dev/null
+++ b/studio/data/integrations/integrations-github-branches-query.ts
@@ -0,0 +1,57 @@
+import { useQuery, UseQueryOptions } from '@tanstack/react-query'
+import { get } from 'data/fetchers'
+import { integrationKeys } from './keys'
+import { ResponseError } from 'types'
+
+export type GithubBranchesVariables = {
+ organizationIntegrationId?: string
+ repoOwner: string
+ repoName: string
+}
+
+export async function getGithubBranches(
+ { organizationIntegrationId, repoOwner, repoName }: GithubBranchesVariables,
+ signal?: AbortSignal
+) {
+ if (!organizationIntegrationId) throw new Error('Organization integration ID is required')
+
+ const { data, error } = await get(
+ `/platform/integrations/github/branches/{organization_integration_id}/{repo_owner}/{repo_name}`,
+ {
+ params: {
+ path: {
+ organization_integration_id: organizationIntegrationId,
+ repo_owner: repoOwner,
+ repo_name: repoName,
+ },
+ },
+ signal,
+ }
+ )
+
+ if (error) throw error
+ return data
+}
+
+export type GithubBranchesData = Awaited<ReturnType<typeof getGithubBranches>>
+export type GithubBranchesError = ResponseError
+
+export const useGithubBranchesQuery = <TData = GithubBranchesData>(
+ { organizationIntegrationId, repoOwner, repoName }: GithubBranchesVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseQueryOptions<GithubBranchesData, GithubBranchesError, TData> = {}
+) =>
+ useQuery<GithubBranchesData, GithubBranchesError, TData>(
+ integrationKeys.githubBranchesList(organizationIntegrationId, repoOwner, repoName),
+ ({ signal }) => getGithubBranches({ organizationIntegrationId, repoOwner, repoName }, signal),
+ {
+ enabled:
+ enabled &&
+ typeof organizationIntegrationId !== 'undefined' &&
+ typeof repoOwner !== 'undefined' &&
+ typeof repoName !== 'undefined',
+ ...options,
+ }
+ )
diff --git a/studio/data/integrations/integrations-query-org-only.ts b/studio/data/integrations/integrations-query-org-only.ts
index 664f4aced96..70b8d620a21 100644
--- a/studio/data/integrations/integrations-query-org-only.ts
+++ b/studio/data/integrations/integrations-query-org-only.ts
@@ -3,6 +3,7 @@ import { get } from 'lib/common/fetch'
import { API_URL } from 'lib/constants'
import { integrationKeys } from './keys'
import { IntegrationsVariables, Integration } from './integrations.types'
+import { ResponseError } from 'types'
export type IntegrationsResponse = Integration[]
@@ -22,7 +23,7 @@ export async function getIntegrations({ orgSlug }: IntegrationsVariables, signal
export type IntegrationsData = Awaited<ReturnType<typeof getIntegrations>>
export type ProjectIntegrationConnectionsData = Awaited<ReturnType<typeof getIntegrations>>
-export type IntegrationsError = unknown
+export type IntegrationsError = ResponseError
export const useOrgIntegrationsQuery = <TData = IntegrationsData>(
{ orgSlug }: IntegrationsVariables,
diff --git a/studio/data/integrations/keys.ts b/studio/data/integrations/keys.ts
index c099d9d7783..ff1223ca57c 100644
--- a/studio/data/integrations/keys.ts
+++ b/studio/data/integrations/keys.ts
@@ -6,4 +6,9 @@ export const integrationKeys = {
['organizations', organization_integration_id, 'vercel-projects'] as const,
vercelConnectionsList: (organization_integration_id: string | undefined) =>
['organizations', organization_integration_id, 'vercel-connections'] as const,
+ githubBranchesList: (
+ organization_integration_id: string | undefined,
+ repo_owner: string,
+ repo_name: string
+ ) => ['organizations', organization_integration_id, 'branches', repo_owner, repo_name],
}
diff --git a/studio/next.config.js b/studio/next.config.js
index fd60e53fd46..2264edfaffd 100644
--- a/studio/next.config.js
+++ b/studio/next.config.js
@@ -203,7 +203,12 @@ const nextConfig = {
]
},
images: {
- domains: ['github.com', 'api-frameworks.vercel.sh', 'vercel.com'],
+ domains: [
+ 'github.com',
+ 'avatars.githubusercontent.com',
+ 'api-frameworks.vercel.sh',
+ 'vercel.com',
+ ],
},
// Ref: https://nextjs.org/docs/advanced-features/output-file-tracing#caveats
experimental: {