Skip to content

Commit

Permalink
Merge branch 'main' into feat/add-prod-db-connection-to-payload
Browse files Browse the repository at this point in the history
  • Loading branch information
maneike authored Nov 12, 2024
2 parents dd1f9b9 + e91764b commit 330c96d
Show file tree
Hide file tree
Showing 16 changed files with 74 additions and 220 deletions.
15 changes: 0 additions & 15 deletions packages/cli/templates/supabase/files/docker-compose.yml

This file was deleted.

2 changes: 1 addition & 1 deletion packages/cli/templates/supabase/installConfig.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export const supabaseFiles = [
{
path: 'supabase/src/',
files: ['client.ts', 'index.ts', 'middleware.ts', 'server.ts', 'types.ts', 'docker-compose.yml'],
files: ['client.ts', 'index.ts', 'middleware.ts', 'server.ts', 'types.ts'],
},
{
path: 'supabase/',
Expand Down
62 changes: 4 additions & 58 deletions packages/core/installMachine/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { createMachine, fromPromise, ActorLogic, AnyEventObject, PromiseSnapshot, createActor, and, not } from 'xstate';

import { createEnvFile } from './installSteps/env/createEnvFile';
import { initializeRepository } from './installSteps/github/install';
import { preparePayload } from './installSteps/payload/install';
import { prettify } from './installSteps/prettier/prettify';
Expand All @@ -15,7 +14,6 @@ import { createDocFiles } from './installSteps/docs/create';
import { pushToGitHub } from './installSteps/github/repositoryManager';
import { InstallMachineContext, StepsCompleted } from '../types';
import { saveStateToRcFile } from '../utils/rcFileManager';
import { setupDatabaseWithDocker } from './installSteps/supabase/setupDatabaseWithDocker';

const isStepCompleted = (stepName: keyof StepsCompleted) => {
return ({ context }: { context: InstallMachineContext; event: AnyEventObject }) => {
Expand Down Expand Up @@ -59,25 +57,11 @@ const createInstallMachine = (initialContext: InstallMachineContext) => {
always: [
{
guard: isStepCompleted('initializeProject'),
target: 'createEnvFile',
},
],
invoke: {
src: 'initializeProjectActor',
input: ({ context }) => context,
onDone: 'createEnvFile',
onError: 'failed',
},
},
createEnvFile: {
always: [
{
guard: isStepCompleted('createEnvFile'),
target: 'installSupabase',
},
],
invoke: {
src: 'createEnvFileActor',
src: 'initializeProjectActor',
input: ({ context }) => context,
onDone: 'installSupabase',
onError: 'failed',
Expand All @@ -86,31 +70,17 @@ const createInstallMachine = (initialContext: InstallMachineContext) => {
installSupabase: {
always: [
{
guard: isStepCompleted('installSupabase'),
target: 'setupDatabaseWithDocker',
},
],
invoke: {
input: ({ context }) => context,
src: 'installSupabaseActor',
onDone: 'setupDatabaseWithDocker',
onError: 'failed',
},
},
setupDatabaseWithDocker: {
always: [
{
guard: and([isStepCompleted('setupDatabaseWithDocker'), 'shouldInstallPayload']),
guard: and([isStepCompleted('installSupabase'), 'shouldInstallPayload']),
target: 'installPayload',
},
{
guard: isStepCompleted('setupDatabaseWithDocker'),
guard: isStepCompleted('installSupabase'),
target: 'createDocFiles',
},
],
invoke: {
input: ({ context }) => context,
src: 'setupDatabaseWithDockerActor',
src: 'installSupabaseActor',
onDone: [{ guard: 'shouldInstallPayload', target: 'installPayload' }, { target: 'createDocFiles' }],
onError: 'failed',
},
Expand Down Expand Up @@ -288,18 +258,6 @@ const createInstallMachine = (initialContext: InstallMachineContext) => {
}
}),
),
createEnvFileActor: createStepMachine(
fromPromise<void, InstallMachineContext, AnyEventObject>(async ({ input }) => {
try {
createEnvFile(input.projectDir);
input.stateData.stepsCompleted.createEnvFile = true;
saveStateToRcFile(input.stateData, input.projectDir);
} catch (error) {
console.error('Error in createEnvFileActor:', error);
throw error;
}
}),
),
installSupabaseActor: createStepMachine(
fromPromise<void, InstallMachineContext, AnyEventObject>(async ({ input }) => {
try {
Expand All @@ -313,18 +271,6 @@ const createInstallMachine = (initialContext: InstallMachineContext) => {
}
}),
),
setupDatabaseWithDockerActor: createStepMachine(
fromPromise<void, InstallMachineContext, AnyEventObject>(async ({ input }) => {
try {
setupDatabaseWithDocker();
input.stateData.stepsCompleted.setupDatabaseWithDocker = true;
saveStateToRcFile(input.stateData, input.projectDir);
} catch (error) {
console.error('Error in setupDatabaseWithDockerActor:', error);
throw error;
}
}),
),
installPayloadActor: createStepMachine(
fromPromise<void, InstallMachineContext, AnyEventObject>(async ({ input }) => {
try {
Expand Down
29 changes: 0 additions & 29 deletions packages/core/installMachine/installSteps/env/createEnvFile.ts

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ export const installGitHubCLI = (): boolean => {
logWithColoredPrefix('github', 'Installing GitHub CLI...');
try {
execSync(installCommand, { stdio: 'inherit' });
logWithColoredPrefix('github', 'GitHub CLI installed successfully.');
return true;
} catch (error) {
console.error('Failed to install GitHub CLI.');
Expand Down
23 changes: 19 additions & 4 deletions packages/core/installMachine/installSteps/github/install.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import inquirer from 'inquirer';
import { logWithColoredPrefix } from '../../../utils/logWithColoredPrefix';
import { installGitHubCLI, isGitHubCLIInstalled } from './ghInstaller';
import {
Expand All @@ -14,13 +15,27 @@ interface ProjectRepositoryOptions {
}

// Helper function to check if GitHub CLI is installed
const checkGitHubCLI = () => {
const checkGitHubCLI = async () => {
logWithColoredPrefix('github', 'Checking if GitHub CLI is installed...');
if (!isGitHubCLIInstalled()) {
logWithColoredPrefix('github', 'GitHub CLI is not installed.');
const installed = installGitHubCLI();
if (!installed) {
console.error('GitHub CLI installation failed. Exiting...');
const { shouldInstallGitHubCLI } = await inquirer.prompt([
{
type: 'confirm',
name: 'shouldInstallGitHubCLI',
message: 'Would you like us to install GitHub CLI?',
default: true,
},
]);

if (shouldInstallGitHubCLI) {
const installed = installGitHubCLI();
if (!installed) {
console.error('GitHub CLI installation failed. Exiting...');
process.exit(1);
}
} else {
console.error('GitHub CLI is not installed. Please install GitHub CLI and try again.');
process.exit(1);
}
}
Expand Down
13 changes: 8 additions & 5 deletions packages/core/installMachine/installSteps/payload/install.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { execSync } from 'child_process';
import { existsSync } from 'fs';
import { join } from 'path';
import path, { join } from 'path';
import chalk from 'chalk';
import { preparePayloadConfig } from './preparePayloadConfig';
import { prepareTsConfig } from './prepareTsConfig';
import { updatePackages } from './updatePackages';
import { updateTurboJson } from './updateTurboJson';
import { updatePackageJson } from './updatePackageJson';
import { logWithColoredPrefix } from '../../../utils/logWithColoredPrefix';
import { loadEnvFile } from './utils/loadEnvFile';

export const preparePayload = async () => {
logWithColoredPrefix('payload', 'Initializing...');
Expand All @@ -25,10 +26,12 @@ export const preparePayload = async () => {
);

logWithColoredPrefix('payload', 'Installing to Next.js...');
logWithColoredPrefix(
'postgres',
`Local connection string: ${chalk.cyan('postgresql://user:password@localhost:5432/postgres')}`,
);

// Show the local Supabase connection string
loadEnvFile(path.resolve('../../supabase/.env'));
logWithColoredPrefix('postgres', `Local connection string: ${chalk.cyan(process.env.DB_URL)}`);

// Install Payload
execSync('npx create-payload-app@beta --db postgres', { stdio: 'inherit' });

// removeTurboFlag();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import fs from 'fs';

export const loadEnvFile = (filePath: fs.PathOrFileDescriptor) => {
const envData = fs.readFileSync(filePath, 'utf-8');
envData.split('\n').forEach((line) => {
const [key, value] = line.split('=');
if (key && value) {
process.env[key.trim()] = value.trim();
}
});
};
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import inquirer from 'inquirer';
import { promisify } from 'util';
import chalk from 'chalk';
import { continueOnAnyKeypress } from '../../../utils/continueOnKeypress';
import { updateEnvFile } from '../../../utils/updateEnvFile';
import { getSupabaseKeys, parseProjectsList } from './utils';
import { logWithColoredPrefix } from '../../../utils/logWithColoredPrefix';

Expand Down Expand Up @@ -33,18 +32,6 @@ export const connectSupabaseProject = async (projectName: string, currentDir: st
throw new Error('Failed to retrieve Supabase API keys. Please check your project configuration.');
}

const SUPABASE_URL = `https://${newProject.refId}.supabase.co/`;

logWithColoredPrefix('supabase', `Saving keys to .env...`);
await updateEnvFile({
currentDir,
pairs: [
['SUPABASE_ANON_KEY', anonKey],
['SUPABASE_SERVICE_ROLE_KEY', serviceRoleKey],
['SUPABASE_URL', SUPABASE_URL],
],
});

logWithColoredPrefix('supabase', 'Linking project...');
execSync(`npx supabase link --project-ref ${newProject.refId}`, { stdio: 'inherit' });

Expand Down
30 changes: 30 additions & 0 deletions packages/core/installMachine/installSteps/supabase/install.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';
import chalk from 'chalk';
import { supabaseFiles } from '../../../templates/supabase/installConfig';
import { templateGenerator } from '../../../utils/generator/generator';
import { getTemplateDirectory } from '../../../utils/getTemplateDirectory';
Expand Down Expand Up @@ -80,5 +81,34 @@ export const installSupabase = async (destinationDirectory: string) => {

execSync('pnpm i --reporter silent', { stdio: 'inherit' });

logWithColoredPrefix('supabase', 'Starting local database...');

try {
execSync('npx supabase start', { stdio: 'ignore' });
} catch (error) {
console.error(
`Failed to start local database. Is your ${chalk.hex('#0db7ed')('Docker')} daemon running?`,
`\n${error}`,
);
process.exit(1);
}

logWithColoredPrefix('supabase', 'Writing local variables to .env file...');

const output = execSync('npx supabase status --output json', {
encoding: 'utf-8',
stdio: ['ignore', 'pipe', 'ignore'],
});
// Parse the JSON output
const jsonData = JSON.parse(output);

// Convert JSON data to .env format
const envData = Object.entries(jsonData)
.map(([key, value]) => `${key}=${value}`)
.join('\n');

// Write the formatted data to .env file
fs.writeFileSync('.env', envData, 'utf8');

process.chdir('..');
};

This file was deleted.

15 changes: 0 additions & 15 deletions packages/core/templates/supabase/files/docker-compose.yml

This file was deleted.

2 changes: 1 addition & 1 deletion packages/core/templates/supabase/installConfig.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export const supabaseFiles = [
{
path: 'supabase/src/',
files: ['client.ts', 'index.ts', 'middleware.ts', 'server.ts', 'types.ts', 'docker-compose.yml'],
files: ['client.ts', 'index.ts', 'middleware.ts', 'server.ts', 'types.ts'],
},
{
path: 'supabase/',
Expand Down
2 changes: 0 additions & 2 deletions packages/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ export interface ProjectOptions {

export interface StepsCompleted {
initializeProject: boolean;
createEnvFile: boolean;
installSupabase: boolean;
setupDatabaseWithDocker: boolean;
installPayload: boolean;
createDocFiles: boolean;
prettifyCode: boolean;
Expand Down
1 change: 0 additions & 1 deletion packages/core/utils/rcFileManager/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ export const initializeRcFile = (projectDir: string, name: string, usePayload: b
projectName: name,
stepsCompleted: {
initializeProject: false,
createEnvFile: false,
installPayload: false,
installSupabase: false,
prettifyCode: false,
Expand Down
Loading

0 comments on commit 330c96d

Please sign in to comment.