Skip to content

Commit

Permalink
refactor: rename getLogColor
Browse files Browse the repository at this point in the history
  • Loading branch information
maneike committed Nov 4, 2024
1 parent 0aa3eed commit 19629ea
Show file tree
Hide file tree
Showing 21 changed files with 104 additions and 86 deletions.
6 changes: 4 additions & 2 deletions packages/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
StateFrom,
PromiseSnapshot,
} from 'xstate';

import { ProjectOptions, StaplerState } from './types';
import { initializeState, saveState } from './utils/stateManager/stateManager';
import { createEnvFile } from './utils/env/createEnvFile';
Expand All @@ -22,6 +23,7 @@ import { setupAndCreateVercelProject } from './utils/vercel/setupAndCreate';
import { prepareDrink } from './utils/bar/prepareDrink';
import { createDocFiles } from './utils/docs/create';
import { pushToGitHub } from './utils/github/repositoryManager';
import { logWithColoredPrefix } from './utils/shared/logWithColoredPrefix';
interface InstallMachineContext {
type: 'install';
projectDir: string;
Expand Down Expand Up @@ -164,7 +166,7 @@ const createInstallMachine = (initialContext: InstallMachineContext) => {
},
done: {
type: 'final',
entry: () => console.log('Installation process completed!'),
entry: () => logWithColoredPrefix('stapler', 'Installation process completed!'),
},
failed: {
type: 'final',
Expand Down Expand Up @@ -308,7 +310,7 @@ export const createProject = async (options: ProjectOptions, projectDir: string)

installActor.subscribe((state: StateFrom<typeof installMachine>) => {
if (state.matches('done')) {
console.log('Installation process completed!');
logWithColoredPrefix('stapler', 'Installation process completed!');
} else if (state.matches('failed')) {
console.error('Installation process failed.');
}
Expand Down
3 changes: 2 additions & 1 deletion packages/core/utils/docs/create.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { docFiles } from '../../templates/docs/installConfig';
import { templateGenerator } from '../generator/generator';
import { logWithColoredPrefix } from '../shared/logWithColoredPrefix';
import { getTemplateDirectory } from '../shared/getTemplateDirectory';

export const createDocFiles = () => {
console.log('Writing docs...');
logWithColoredPrefix('stapler', 'Writing docs...');
const templateDirectory = getTemplateDirectory(`/templates/docs/files`);
const destinationDirectory = process.cwd();

Expand Down
7 changes: 4 additions & 3 deletions packages/core/utils/env/createEnvFile.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as fs from 'fs';
import * as path from 'path';
import fs from 'fs';
import path from 'path';
import { logWithColoredPrefix } from '../shared/logWithColoredPrefix';

const requiredEnvVariables: Record<string, 'required' | 'optional'> = {
NEXT_PUBLIC_SUPABASE_URL: 'required',
Expand All @@ -14,7 +15,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...');
logWithColoredPrefix('stapler', 'Creating .env file...');
let envTemplate = '';
for (const [key, status] of Object.entries(requiredEnvVariables)) {
envTemplate += `${key}=\n`;
Expand Down
12 changes: 6 additions & 6 deletions packages/core/utils/github/ghInstaller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { execSync } from 'child_process';
import * as os from 'os';
import { getLogColor } from '../shared/getLogColor';
import { logWithColoredPrefix } from '../shared/logWithColoredPrefix';

export const isGitHubCLIInstalled = (): boolean => {
try {
Expand Down Expand Up @@ -28,7 +28,7 @@ export const installGitHubCLI = (): boolean => {
installCommand =
'sudo dnf config-manager --add-repo https://cli.github.com/packages/rpm/gh-cli.repo && sudo dnf install gh';
} else {
getLogColor('github', [
logWithColoredPrefix('github', [
'Automatic installation is not supported for your Linux distribution.',
'\n Please visit https://github.com/cli/cli#installation for installation instructions.',
]);
Expand All @@ -39,21 +39,21 @@ export const installGitHubCLI = (): boolean => {
installCommand = 'winget install --id GitHub.cli';
break;
default:
getLogColor('github', [
logWithColoredPrefix('github', [
'Automatic installation is not supported for your operating system.',
'\nPlease visit https://github.com/cli/cli#installation for installation instructions.',
]);
return false;
}

getLogColor('github', 'Installing GitHub CLI...');
logWithColoredPrefix('github', 'Installing GitHub CLI...');
try {
execSync(installCommand, { stdio: 'inherit' });
getLogColor('github', 'GitHub CLI installed successfully.');
logWithColoredPrefix('github', 'GitHub CLI installed successfully.');
return true;
} catch (error) {
console.error('Failed to install GitHub CLI.');
getLogColor('github', 'Please install it manually from: https://github.com/cli/cli#installation');
logWithColoredPrefix('github', 'Please install it manually from: https://github.com/cli/cli#installation');
return false;
}
};
Expand Down
12 changes: 6 additions & 6 deletions packages/core/utils/github/install.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getLogColor } from '../shared/getLogColor';
import { logWithColoredPrefix } from '../shared/logWithColoredPrefix';
import { installGitHubCLI, isGitHubCLIInstalled } from './ghInstaller';
import {
authenticateGitHub,
Expand All @@ -15,9 +15,9 @@ interface ProjectRepositoryOptions {

// Helper function to check if GitHub CLI is installed
const checkGitHubCLI = () => {
getLogColor('github', 'Checking if GitHub CLI is installed...');
logWithColoredPrefix('github', 'Checking if GitHub CLI is installed...');
if (!isGitHubCLIInstalled()) {
getLogColor('github', 'GitHub CLI is not installed.');
logWithColoredPrefix('github', 'GitHub CLI is not installed.');
const installed = installGitHubCLI();
if (!installed) {
console.error('GitHub CLI installation failed. Exiting...');
Expand All @@ -28,11 +28,11 @@ const checkGitHubCLI = () => {

// Helper function to ensure GitHub authentication
const ensureGitHubAuthentication = () => {
getLogColor('github', 'Checking authentication status...');
logWithColoredPrefix('github', 'Checking authentication status...');

// Check if the user is already authenticated
if (isGitHubAuthenticated()) {
getLogColor('github', 'You are already logged in.');
logWithColoredPrefix('github', 'You are already logged in.');
return; // Exit early if authenticated
}

Expand All @@ -44,7 +44,7 @@ const ensureGitHubAuthentication = () => {

export const initializeRepository = async (options: ProjectRepositoryOptions) => {
const { projectName, visibility } = options;
getLogColor('github', `Initializing repository for project "${projectName}"...`);
logWithColoredPrefix('github', `Initializing repository for project "${projectName}"...`);

checkGitHubCLI();
ensureGitHubAuthentication();
Expand Down
20 changes: 10 additions & 10 deletions packages/core/utils/github/repositoryManager.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { exec, execSync } from 'child_process';
import inquirer from 'inquirer';
import { promisify } from 'util';
import { getLogColor } from '../shared/getLogColor';
import { logWithColoredPrefix } from '../shared/logWithColoredPrefix';

const execAsync = promisify(exec);

Expand Down Expand Up @@ -50,7 +50,7 @@ export const isGitHubAuthenticated = (): boolean => {
};

export const authenticateGitHub = async (): Promise<boolean> => {
getLogColor('github', 'Attempting to authenticate...');
logWithColoredPrefix('github', 'Attempting to authenticate...');

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

Expand All @@ -69,13 +69,13 @@ export const fetchGitHubUsername = async (): Promise<string | null> => {
try {
const username = execSync('echo "$(gh api user --jq .login)"', { stdio: 'pipe' }).toString().trim();

getLogColor('github', `Retrieved GitHub username: ${username}`);
logWithColoredPrefix('github', `Retrieved GitHub username: ${username}`);

if (username) {
getLogColor('github', `Hello ${username}!`);
logWithColoredPrefix('github', `Hello ${username}!`);
return username;
} else {
getLogColor('github', 'No username returned or an error occurred.');
logWithColoredPrefix('github', 'No username returned or an error occurred.');
return null;
}
} catch (error) {
Expand All @@ -89,7 +89,7 @@ export const createGitHubRepository = async (
repositoryVisibility: 'public' | 'private',
username: string,
): Promise<string | undefined> => {
getLogColor('github', `Checking if repository already exists...`);
logWithColoredPrefix('github', `Checking if repository already exists...`);

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

getLogColor('github', `Creating repository: ${repoName}`);
logWithColoredPrefix('github', `Creating repository: ${repoName}`);

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

const result = execSync(command);

if (result) {
getLogColor('github', `Repository successfully created at ${result}`);
logWithColoredPrefix('github', `Repository successfully created at ${result}`);
return repoName; // Return true to indicate success
}

Expand All @@ -144,7 +144,7 @@ const executeCommands = (commands: string[]) => {

// New function to set up the local Git repository
export const setupGitRepository = async (projectName: string, username: string) => {
getLogColor('github', `Setting up Git for the repository...`);
logWithColoredPrefix('github', `Setting up Git for the repository...`);

// Set the remote origin and push to GitHub
const commands = [`git init`, `git add .`];
Expand All @@ -153,7 +153,7 @@ export const setupGitRepository = async (projectName: string, username: string)
};

export const pushToGitHub = async (projectName: string) => {
getLogColor('github', 'Pushing changes to GitHub...');
logWithColoredPrefix('github', 'Pushing changes to GitHub...');

const username = await fetchGitHubUsername();
const commands = [
Expand Down
8 changes: 4 additions & 4 deletions packages/core/utils/payload/install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,26 @@ import { preparePayloadConfig } from './preparePayloadConfig';
import { prepareTsConfig } from './prepareTsConfig';
import { removeTurboFlag } from './removeTurboFlag';
import { updatePackages } from './updatePackages';
import { getLogColor } from '../shared/getLogColor';
import { logWithColoredPrefix } from '../shared/logWithColoredPrefix';

export const preparePayload = async () => {
getLogColor('payload', 'Initializing...');
logWithColoredPrefix('payload', 'Initializing...');

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

prepareTsConfig();

updatePackages();

getLogColor('payload', ['Moving files to (app) directory...']);
logWithColoredPrefix('payload', ['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',
},
);

getLogColor('payload', 'Installing to Next.js...');
logWithColoredPrefix('payload', 'Installing to Next.js...');
execSync(`npx create-payload-app@beta`, { stdio: 'inherit' });

// Payload doesn't work with Turbopack yet
Expand Down
4 changes: 2 additions & 2 deletions packages/core/utils/payload/preparePayloadConfig.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { PathLike } from 'fs';
import fs from 'fs/promises';
import { getLogColor } from '../shared/getLogColor';
import { logWithColoredPrefix } from '../shared/logWithColoredPrefix';

export const preparePayloadConfig = async (configPath: PathLike) => {
getLogColor('payload', 'Preparing payload.config.ts...');
logWithColoredPrefix('payload', 'Preparing payload.config.ts...');

try {
// Read the payload.config.ts file
Expand Down
4 changes: 2 additions & 2 deletions packages/core/utils/payload/prepareTsConfig.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import fs from 'fs';
import path from 'path';
import { getLogColor } from '../shared/getLogColor';
import { logWithColoredPrefix } from '../shared/logWithColoredPrefix';

export const prepareTsConfig = () => {
getLogColor('payload', 'Preparing tsconfig.json...');
logWithColoredPrefix('payload', 'Preparing tsconfig.json...');

// Path to your tsconfig.json file
const tsconfigPath = path.join(process.cwd(), 'tsconfig.json');
Expand Down
4 changes: 2 additions & 2 deletions packages/core/utils/payload/removeTurboFlag.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import fs from 'fs';
import path from 'path';
import { getLogColor } from '../shared/getLogColor';
import { logWithColoredPrefix } from '../shared/logWithColoredPrefix';

export const removeTurboFlag = () => {
getLogColor('payload', 'Removing --turbo flag from dev script...');
logWithColoredPrefix('payload', 'Removing --turbo flag from dev script...');

// Path to your package.json file
const packageJsonPath = path.join(process.cwd(), 'package.json');
Expand Down
6 changes: 3 additions & 3 deletions packages/core/utils/payload/updatePackages.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { execSync } from 'child_process';
import { getLogColor } from '../shared/getLogColor';
import { logWithColoredPrefix } from '../shared/logWithColoredPrefix';

export const updatePackages = () => {
getLogColor('payload', 'Updating Next and React to their respective release candidates...');
logWithColoredPrefix('payload', 'Updating Next and React to their respective release candidates...');
execSync(`pnpm up next@rc react@rc react-dom@rc eslint-config-next@rc --reporter silent`, {
stdio: 'inherit',
});

getLogColor('payload', 'Installing necessary packages...');
logWithColoredPrefix('payload', 'Installing necessary packages...');
execSync(`pnpm i pg sharp --reporter silent`, {
stdio: 'inherit',
});
Expand Down
4 changes: 2 additions & 2 deletions packages/core/utils/prettier/prettify.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { execSync } from 'child_process';
import { getLogColor } from '../shared/getLogColor';
import { logWithColoredPrefix } from '../shared/logWithColoredPrefix';

export const prettify = async () => {
getLogColor('prettier', 'Prettifying...');
logWithColoredPrefix('prettier', 'Prettifying...');

const ignorePatterns = [
'node_modules/',
Expand Down
4 changes: 2 additions & 2 deletions packages/core/utils/shared/continueOnKeypress.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as readline from 'readline';
import { getLogColor } from './getLogColor';
import { logWithColoredPrefix } from './logWithColoredPrefix';

export const continueOnAnyKeypress = async (message: string): Promise<void> => {
getLogColor('supabase', message);
logWithColoredPrefix('supabase', message);

const rl = readline.createInterface({
input: process.stdin,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,20 @@
import chalk from 'chalk';
import gradient from 'gradient-string';

type Name = 'turborepo' | 'supabase' | 'payload' | 'github' | 'prettier' | 'vercel';
type Name = 'stapler' | 'turborepo' | 'supabase' | 'payload' | 'github' | 'prettier' | 'vercel';

const names = [
type NameProps = {
name: Name;
prefix: string;
colors: string[];
};

const names: NameProps[] = [
{
name: 'stapler',
prefix: 'Stapler',
colors: ['#FAFAFA', '#FAFAFA'],
},
{
name: 'turborepo',
prefix: 'Turbo',
Expand Down Expand Up @@ -36,7 +47,7 @@ const names = [
},
];

export const getLogColor = (name: Name, messages: string[] | string) => {
export const logWithColoredPrefix = (name: Name, messages: string[] | string) => {
const color = names.find((color) => color.name === name);
if (!color) {
console.log(chalk.red('Invalid color name.'));
Expand Down
Loading

0 comments on commit 19629ea

Please sign in to comment.