Skip to content

Commit

Permalink
Merge branch 'main' of github.com:tonik/stapler
Browse files Browse the repository at this point in the history
  • Loading branch information
maneike committed Oct 24, 2024
2 parents af1ef17 + 0b0c23a commit 9029a36
Show file tree
Hide file tree
Showing 17 changed files with 118 additions and 77 deletions.
6 changes: 3 additions & 3 deletions packages/cli/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#!/usr/bin/env node
import { Command } from 'commander';
import inquirer from 'inquirer';
import chalk from 'chalk';
import { Command } from 'commander';
import gradient from 'gradient-string';
import inquirer from 'inquirer';

import { createProject } from '@create-stapler-app/core';

Expand All @@ -27,7 +27,7 @@ function displayHeader() {
]);

console.log(metalGradient(asciiArt));
console.log(chalk.bold('\nπŸ–‡οΈ Welcome to Stapler!\n'));
console.log(chalk.bold('\nπŸ–‡οΈ Welcome to Stapler!\n'));
}

const program = new Command();
Expand Down
2 changes: 1 addition & 1 deletion packages/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ interface ProjectOptions {
export async function createProject(options: ProjectOptions) {
const { name, usePayload } = options;

console.log(`πŸ–‡οΈ Stapling ${name}...`);
console.log(`πŸ–‡οΈ Stapling ${name}...`);

await createTurboRepo(name);

Expand Down
4 changes: 2 additions & 2 deletions packages/core/utils/docs/create.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import path from 'path';
import { templateGenerator } from '../generator/generator';
import { docFiles } from '../../templates/docs/installConfig';
import { templateGenerator } from '../generator/generator';

export const createDocFiles = () => {
console.log('πŸ–‡οΈ Writing docs...');
console.log('πŸ–‡οΈ Writing docs...');
const templateDirectory = path.join(__dirname, '../templates/docs/files');
const destinationDirectory = process.cwd();

Expand Down
2 changes: 1 addition & 1 deletion packages/core/utils/env/createEnvFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const requiredEnvVariables: Record<string, 'required' | 'optional'> = {

// Function to create .env file with empty fields
export const createEnvFile = (destinationDirectory: string) => {
console.log('πŸ–‡οΈ Creating .env file...');
console.log('πŸ–‡οΈ Creating .env file...');
let envTemplate = '';
for (const [key, status] of Object.entries(requiredEnvVariables)) {
envTemplate += `${key}=\n`;
Expand Down
16 changes: 8 additions & 8 deletions packages/core/utils/github/ghInstaller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,28 +27,28 @@ export function installGitHubCLI(): boolean {
installCommand =
'sudo dnf config-manager --add-repo https://cli.github.com/packages/rpm/gh-cli.repo && sudo dnf install gh';
} else {
console.log('πŸ–‡οΈ Automatic installation is not supported for your Linux distribution.');
console.log('πŸ–‡οΈ Please visit https://github.com/cli/cli#installation for installation instructions.');
console.log('πŸ–‡οΈ Automatic installation is not supported for your Linux distribution.');
console.log('πŸ–‡οΈ Please visit https://github.com/cli/cli#installation for installation instructions.');
return false;
}
break;
case 'win32': // Windows
installCommand = 'winget install --id GitHub.cli';
break;
default:
console.log('πŸ–‡οΈ Automatic installation is not supported for your operating system.');
console.log('πŸ–‡οΈ Please visit https://github.com/cli/cli#installation for installation instructions.');
console.log('πŸ–‡οΈ Automatic installation is not supported for your operating system.');
console.log('πŸ–‡οΈ Please visit https://github.com/cli/cli#installation for installation instructions.');
return false;
}

console.log('πŸ–‡οΈ Installing GitHub CLI...');
console.log('πŸ–‡οΈ Installing GitHub CLI...');
try {
execSync(installCommand, { stdio: 'inherit' });
console.log('πŸ–‡οΈ GitHub CLI installed successfully.');
console.log('πŸ–‡οΈ GitHub CLI installed successfully.');
return true;
} catch (error) {
console.error('πŸ–‡οΈ Failed to install GitHub CLI.');
console.log('πŸ–‡οΈ Please install it manually from: https://github.com/cli/cli#installation');
console.error('πŸ–‡οΈ Failed to install GitHub CLI.');
console.log('πŸ–‡οΈ Please install it manually from: https://github.com/cli/cli#installation');
return false;
}
}
Expand Down
24 changes: 13 additions & 11 deletions packages/core/utils/github/install.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { installGitHubCLI, isGitHubCLIInstalled } from './ghInstaller';
import {
isGitHubAuthenticated,
authenticateGitHub,
createGitHubRepository,
fetchGitHubUsername,
authenticateGitHub,
isGitHubAuthenticated,
setupGitRepository,
} from './repositoryManager';
import { installGitHubCLI, isGitHubCLIInstalled } from './ghInstaller';

interface ProjectOptions {
projectName: string;
Expand All @@ -14,29 +14,29 @@ interface ProjectOptions {

// Helper function to check if GitHub CLI is installed
function checkGitHubCLI() {
console.log('πŸ–‡οΈ Checking GitHub CLI installation...');
console.log('πŸ–‡οΈ Checking GitHub CLI installation...');
if (!isGitHubCLIInstalled()) {
console.log('πŸ–‡οΈ GitHub CLI is not installed.');
console.log('πŸ–‡οΈ GitHub CLI is not installed.');
const installed = installGitHubCLI();
if (!installed) {
console.error('πŸ–‡οΈ GitHub CLI installation failed. Exiting...');
console.error('πŸ–‡οΈ GitHub CLI installation failed. Exiting...');
process.exit(1);
}
}
}

// Helper function to ensure GitHub authentication
function ensureGitHubAuthentication() {
console.log('πŸ–‡οΈ Checking GitHub authentication status...');
console.log('πŸ–‡οΈ Checking GitHub authentication status...');

// Check if the user is already authenticated
if (isGitHubAuthenticated()) {
console.log('πŸ–‡οΈ You are already logged in to GitHub.');
console.log('πŸ–‡οΈ You are already logged in to GitHub.');
return; // Exit early if authenticated
}

if (!isGitHubAuthenticated()) {
console.error(`πŸ–‡οΈ It looks like you're not logged in...`);
console.error(`πŸ–‡οΈ It looks like you're not logged in...`);
authenticateGitHub();
}
}
Expand All @@ -50,14 +50,16 @@ export async function initializeRepository(options: ProjectOptions) {
// Retrieve GitHub username once
const username = await fetchGitHubUsername();
if (!username) {
console.error('πŸ–‡οΈ Failed to retrieve GitHub username. Aborting repository creation.');
console.error('πŸ–‡οΈ Failed to retrieve GitHub username. Aborting repository creation.');
process.exit(1);
}

// Check if the repository exists and create it
const repoName = await createGitHubRepository(projectName, visibility, username);
if (!repoName) {
console.error('πŸ–‡οΈ Failed to create GitHub repository. Check your permissions or if the repository already exists.');
console.error(
'πŸ–‡οΈ Failed to create GitHub repository. Check your permissions or if the repository already exists.',
);
process.exit(1);
}

Expand Down
28 changes: 14 additions & 14 deletions packages/core/utils/github/repositoryManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ async function generateUniqueRepoName(baseName: string): Promise<string> {
// Try the base name first
try {
await execAsync(`gh repo view ${cleanBaseName}`);
console.error(`πŸ–‡οΈ Repository "${cleanBaseName}" already exists.`);
console.error(`πŸ–‡οΈ Repository "${cleanBaseName}" already exists.`);
// If we get here, the repo exists, so we need a new name
} catch (error) {
// If repo doesn't exist, we can use the clean base name
Expand All @@ -26,7 +26,7 @@ async function generateUniqueRepoName(baseName: string): Promise<string> {
const candidateName = `${cleanBaseName}-v${counter}`;
try {
await execAsync(`gh repo view ${candidateName}`);
console.error(`πŸ–‡οΈ Repository "${candidateName}" already exists.`);
console.error(`πŸ–‡οΈ Repository "${candidateName}" already exists.`);
counter++;
} catch (error) {
if (error) {
Expand All @@ -49,18 +49,18 @@ export function isGitHubAuthenticated(): boolean {
}

export async function authenticateGitHub(): Promise<boolean> {
console.log('πŸ–‡οΈ Attempting to authenticate with GitHub...');
console.log('πŸ–‡οΈ Attempting to authenticate with GitHub...');

execSync('gh auth login', { stdio: 'inherit' });

// Immediately check authentication status after login attempt
const isAuthenticated = isGitHubAuthenticated();

if (isAuthenticated) {
console.log('πŸ–‡οΈ Authentication was successful.');
console.log('πŸ–‡οΈ Authentication was successful.');
return true;
} else {
console.error('πŸ–‡οΈ Authentication failed after login attempt.');
console.error('πŸ–‡οΈ Authentication failed after login attempt.');
return false;
}
}
Expand All @@ -71,14 +71,14 @@ export async function fetchGitHubUsername(): Promise<string | null> {
const username = execSync('echo "$(gh api user --jq .login)"', { stdio: 'pipe' }).toString().trim();

if (username) {
console.log(`πŸ–‡οΈ Hello \x1b[36m${username}\x1b[0m!`);
console.log(`πŸ–‡οΈ Hello \x1b[36m${username}\x1b[0m!`);
return username;
} else {
console.log('πŸ–‡οΈ No username returned or an error occurred.');
console.log('πŸ–‡οΈ No username returned or an error occurred.');
return null;
}
} catch (error) {
console.error('πŸ–‡οΈ Error fetching GitHub username:', error);
console.error('πŸ–‡οΈ Error fetching GitHub username:', error);
return null;
}
}
Expand All @@ -88,7 +88,7 @@ export async function createGitHubRepository(
repositoryVisibility: 'public' | 'private',
username: string,
): Promise<string | undefined> {
console.log(`πŸ–‡οΈ Checking if repository already exists...`);
console.log(`πŸ–‡οΈ Checking if repository already exists...`);

// Check if the repository exists
const repoCheckCommand = `echo "$(gh repo view ${username}/${projectName} --json name)"`;
Expand All @@ -114,25 +114,25 @@ export async function createGitHubRepository(
repoName = confirmedName;
}

console.log(`πŸ–‡οΈ Creating GitHub repository: \x1b[36m${repoName}\x1b[0m`);
console.log(`πŸ–‡οΈ Creating GitHub repository: \x1b[36m${repoName}\x1b[0m`);

const visibility = repositoryVisibility === 'public' ? '--public' : '--private';
const command = `gh repo create ${repoName} ${visibility}`;

const result = execSync(command);

if (result) {
console.log(`πŸ–‡οΈ Repository successfully created at \x1b[36m${result}\x1b[0m`);
console.log(`πŸ–‡οΈ Repository successfully created at \x1b[36m${result}\x1b[0m`);
return repoName; // Return true to indicate success
}

console.error('πŸ–‡οΈ Failed to create GitHub repository.');
console.error('πŸ–‡οΈ Failed to create GitHub repository.');
return; // Return false on failure
}

// New function to set up the local Git repository
export async function setupGitRepository(projectName: string, username: string) {
console.log(`πŸ–‡οΈ Setting up Git for the repository...`);
console.log(`πŸ–‡οΈ Setting up Git for the repository...`);

// Set the remote origin and push to GitHub
const commands = [
Expand All @@ -147,7 +147,7 @@ export async function setupGitRepository(projectName: string, username: string)
for (const cmd of commands) {
const result = execSync(cmd, { stdio: 'pipe' });
if (!result) {
console.error(`πŸ–‡οΈ Failed to execute command: ${cmd}`);
console.error(`πŸ–‡οΈ Failed to execute command: ${cmd}`);
process.exit(1);
}
}
Expand Down
12 changes: 6 additions & 6 deletions packages/core/utils/payload/install.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
import { execSync } from 'child_process';
import { existsSync } from 'fs';
import { join } from 'path';
import { removeTurboFlag } from './removeTurboFlag';
import { preparePayloadConfig } from './preparePayloadConfig';
import { prepareTsConfig } from './prepareTsConfig';
import { removeTurboFlag } from './removeTurboFlag';
import { updatePackages } from './updatePackages';
import { preparePayloadConfig } from './preparePayloadConfig';

export const preparePayload = async () => {
console.log('πŸ–‡οΈ Initializing Payload...');
console.log('πŸ–‡οΈ Initializing Payload...');

process.chdir('./apps/web/');

prepareTsConfig();

updatePackages();

console.log('πŸ–‡οΈ Moving files to (app) directory...');
console.log('πŸ–‡οΈ Moving files to (app) directory...');
execSync(
`mkdir -p ./app/\\(app\\) && find ./app -maxdepth 1 ! -path './app' ! -path './app/\\(app\\)' -exec mv {} ./app/\\(app\\)/ \\;`,
{
stdio: 'inherit',
},
);

console.log('πŸ–‡οΈ Installing Payload to Next.js...');
console.log('πŸ–‡οΈ Installing Payload to Next.js...');
execSync(`npx create-payload-app@beta`, { stdio: 'inherit' });

// Payload doesn't work with Turbopack yet
Expand All @@ -32,7 +32,7 @@ export const preparePayload = async () => {
// Check if the payload configuration file exists
const payloadConfigPath = join(process.cwd(), 'payload.config.ts');
if (!existsSync(payloadConfigPath)) {
console.error('πŸ–‡οΈ Payload installation cancelled/failed.');
console.error('πŸ–‡οΈ Payload installation cancelled/failed.');
} else {
await preparePayloadConfig(payloadConfigPath);
}
Expand Down
4 changes: 2 additions & 2 deletions packages/core/utils/payload/preparePayloadConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { PathLike } from 'fs';
import fs from 'fs/promises';

export const preparePayloadConfig = async (configPath: PathLike) => {
console.log('πŸ–‡οΈ Preparing payload.config.ts...');
console.log('πŸ–‡οΈ Preparing payload.config.ts...');

try {
// Read the payload.config.ts file
Expand All @@ -20,6 +20,6 @@ export const preparePayloadConfig = async (configPath: PathLike) => {
// Write the updated payload.config.ts back to the file
await fs.writeFile(configPath, updatedConfig);
} catch (err) {
console.error('πŸ–‡οΈ Error during processing payload.config.ts', err);
console.error('πŸ–‡οΈ Error during processing payload.config.ts', err);
}
};
6 changes: 3 additions & 3 deletions packages/core/utils/payload/prepareTsConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import fs from 'fs';
import path from 'path';

export const prepareTsConfig = () => {
console.log('πŸ–‡οΈ Preparing tsconfig.json...');
console.log('πŸ–‡οΈ Preparing tsconfig.json...');

// Path to your tsconfig.json file
const tsconfigPath = path.join(process.cwd(), 'tsconfig.json');

// Read the tsconfig.json file
fs.readFile(tsconfigPath, 'utf8', (err, data) => {
if (err) {
console.error('πŸ–‡οΈ Error reading tsconfig.json', err);
console.error('πŸ–‡οΈ Error reading tsconfig.json', err);
return;
}

Expand All @@ -33,7 +33,7 @@ export const prepareTsConfig = () => {
// Write the updated tsconfig.json back to the file
fs.writeFile(tsconfigPath, JSON.stringify(tsconfig, null, 2), (err) => {
if (err) {
console.error('πŸ–‡οΈ Error writing to tsconfig.json', err);
console.error('πŸ–‡οΈ Error writing to tsconfig.json', err);
}
});
});
Expand Down
6 changes: 3 additions & 3 deletions packages/core/utils/payload/removeTurboFlag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import fs from 'fs';
import path from 'path';

export const removeTurboFlag = () => {
console.log('πŸ–‡οΈ Removing --turbo flag from dev script...');
console.log('πŸ–‡οΈ Removing --turbo flag from dev script...');

// Path to your package.json file
const packageJsonPath = path.join(process.cwd(), 'package.json');

// Read the package.json file
fs.readFile(packageJsonPath, 'utf8', (err: Error | null, data: string) => {
if (err) {
console.error('πŸ–‡οΈ Error reading package.json', err);
console.error('πŸ–‡οΈ Error reading package.json', err);
return;
}

Expand All @@ -25,7 +25,7 @@ export const removeTurboFlag = () => {
// Write the updated package.json back to the file
fs.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2), (err: Error | null) => {
if (err) {
console.error('πŸ–‡οΈ Error writing to package.json', err);
console.error('πŸ–‡οΈ Error writing to package.json', err);
}
});
});
Expand Down
4 changes: 2 additions & 2 deletions packages/core/utils/payload/updatePackages.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { execSync } from 'child_process';

export const updatePackages = () => {
console.log('πŸ–‡οΈ Updating Next and React to their respective release candidates...');
console.log('πŸ–‡οΈ Updating Next and React to their respective release candidates...');
execSync(`pnpm up next@rc react@rc react-dom@rc eslint-config-next@rc`, {
stdio: 'inherit',
});

console.log('πŸ–‡οΈ Installing necessary packages...');
console.log('πŸ–‡οΈ Installing necessary packages...');
execSync(`pnpm i pg sharp`, {
stdio: 'inherit',
});
Expand Down
Loading

0 comments on commit 9029a36

Please sign in to comment.