feat(create-medusa-app,medusa-cli): Allow clearing project (#4273)
- Added build step - Added `--no-boilerplate` option to `create-medusa-app` to allow clearing onboarding files - Clear project files by default in medusa-cli
This commit is contained in:
@@ -13,12 +13,15 @@
|
||||
"prepare": "cross-env NODE_ENV=production yarn run build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@medusajs/utils": "^1.9.0",
|
||||
"boxen": "^7.1.0",
|
||||
"chalk": "^5.2.0",
|
||||
"commander": "^10.0.1",
|
||||
"glob": "^10.2.7",
|
||||
"inquirer": "^9.2.2",
|
||||
"medusa-telemetry": "^0.0.16",
|
||||
"nanoid": "^4.0.2",
|
||||
"node-emoji": "^2.0.2",
|
||||
"node-fetch": "^3.3.1",
|
||||
"open": "^9.1.0",
|
||||
"ora": "^6.3.0",
|
||||
@@ -33,6 +36,7 @@
|
||||
"@types/commander": "^2.12.2",
|
||||
"@types/configstore": "^6.0.0",
|
||||
"@types/inquirer": "^9.0.3",
|
||||
"@types/node-emoji": "^1.8.2",
|
||||
"@types/pg": "^8.6.6",
|
||||
"@types/uuid": "^9.0.1",
|
||||
"@types/validator": "^13.7.17",
|
||||
|
||||
@@ -15,13 +15,14 @@ import fs from "fs"
|
||||
import { nanoid } from "nanoid"
|
||||
import isEmailImported from "validator/lib/isEmail.js"
|
||||
import logMessage from "../utils/log-message.js"
|
||||
import onProcessTerminated from "../utils/on-process-terminated.js"
|
||||
import createAbortController, {
|
||||
isAbortError,
|
||||
} from "../utils/create-abort-controller.js"
|
||||
import { track } from "medusa-telemetry"
|
||||
import { createFactBox, resetFactBox } from "../utils/facts.js"
|
||||
import boxen from "boxen"
|
||||
import { emojify } from "node-emoji"
|
||||
import ProcessManager from "../utils/process-manager.js"
|
||||
|
||||
const slugify = slugifyType.default
|
||||
const isEmail = isEmailImported.default
|
||||
@@ -29,9 +30,11 @@ const isEmail = isEmailImported.default
|
||||
type CreateOptions = {
|
||||
repoUrl?: string
|
||||
seed?: boolean
|
||||
// commander passed --no-boilerplate as boilerplate
|
||||
boilerplate?: boolean
|
||||
}
|
||||
|
||||
export default async ({ repoUrl = "", seed }: CreateOptions) => {
|
||||
export default async ({ repoUrl = "", seed, boilerplate }: CreateOptions) => {
|
||||
track("CREATE_CLI")
|
||||
if (repoUrl) {
|
||||
track("STARTER_SELECTED", { starter: repoUrl })
|
||||
@@ -39,7 +42,8 @@ export default async ({ repoUrl = "", seed }: CreateOptions) => {
|
||||
if (seed) {
|
||||
track("SEED_SELECTED", { seed })
|
||||
}
|
||||
const abortController = createAbortController()
|
||||
const processManager = new ProcessManager()
|
||||
const abortController = createAbortController(processManager)
|
||||
|
||||
const { projectName } = await inquirer.prompt([
|
||||
{
|
||||
@@ -114,7 +118,7 @@ export default async ({ repoUrl = "", seed }: CreateOptions) => {
|
||||
type: "input",
|
||||
name: "adminEmail",
|
||||
message: "Enter an email for your admin dashboard user",
|
||||
default: !seed ? "admin@medusa-test.com" : undefined,
|
||||
default: !seed && boilerplate ? "admin@medusa-test.com" : undefined,
|
||||
validate: (input) => {
|
||||
return typeof input === "string" && input.length > 0 && isEmail(input)
|
||||
? true
|
||||
@@ -123,13 +127,20 @@ export default async ({ repoUrl = "", seed }: CreateOptions) => {
|
||||
},
|
||||
])
|
||||
|
||||
logMessage({
|
||||
message: `${emojify(
|
||||
":rocket:"
|
||||
)} Starting project setup, this may take a few minutes.`,
|
||||
})
|
||||
|
||||
const spinner = ora().start()
|
||||
|
||||
onProcessTerminated(() => spinner.stop())
|
||||
processManager.onTerminated(() => spinner.stop())
|
||||
|
||||
let interval: NodeJS.Timer | null = createFactBox(
|
||||
spinner,
|
||||
"Setting up project..."
|
||||
"Setting up project...",
|
||||
processManager
|
||||
)
|
||||
|
||||
// clone repository
|
||||
@@ -155,6 +166,7 @@ export default async ({ repoUrl = "", seed }: CreateOptions) => {
|
||||
interval,
|
||||
spinner,
|
||||
"Created project directory",
|
||||
processManager,
|
||||
"Creating database..."
|
||||
)
|
||||
|
||||
@@ -182,7 +194,12 @@ export default async ({ repoUrl = "", seed }: CreateOptions) => {
|
||||
db: dbName,
|
||||
})
|
||||
|
||||
resetFactBox(interval, spinner, `Database ${dbName} created`)
|
||||
resetFactBox(
|
||||
interval,
|
||||
spinner,
|
||||
`Database ${dbName} created`,
|
||||
processManager
|
||||
)
|
||||
}
|
||||
|
||||
// prepare project
|
||||
@@ -195,7 +212,9 @@ export default async ({ repoUrl = "", seed }: CreateOptions) => {
|
||||
email: adminEmail,
|
||||
},
|
||||
seed,
|
||||
boilerplate,
|
||||
spinner,
|
||||
processManager,
|
||||
abortController,
|
||||
})
|
||||
} catch (e: any) {
|
||||
@@ -240,19 +259,13 @@ export default async ({ repoUrl = "", seed }: CreateOptions) => {
|
||||
// this ensures that the message isn't printed twice to the user
|
||||
let printedMessage = false
|
||||
|
||||
onProcessTerminated(() => {
|
||||
processManager.onTerminated(() => {
|
||||
if (!printedMessage) {
|
||||
printedMessage = true
|
||||
console.log(
|
||||
boxen(
|
||||
chalk.green(
|
||||
`Change to the \`${projectName}\` directory to explore your Medusa project.
|
||||
|
||||
Check out the Medusa documentation to start your development:
|
||||
https://docs.medusajs.com/
|
||||
|
||||
Star us on GitHub if you like what we're building:
|
||||
https://github.com/medusajs/medusa/stargazers`
|
||||
`Change to the \`${projectName}\` directory to explore your Medusa project.\n\nStart your Medusa app again with the following command:\n\nnpx @medusajs/medusa-cli develop\n\nCheck out the Medusa documentation to start your development:\n\nhttps://docs.medusajs.com/\n\nStar us on GitHub if you like what we're building:\n\nhttps://github.com/medusajs/medusa/stargazers`
|
||||
),
|
||||
{
|
||||
titleAlignment: "center",
|
||||
@@ -271,8 +284,8 @@ export default async ({ repoUrl = "", seed }: CreateOptions) => {
|
||||
}).then(async () =>
|
||||
open(
|
||||
inviteToken
|
||||
? `http://localhost:9000/app/invite?token=${inviteToken}&first_run=true`
|
||||
: "http://localhost:9000/app"
|
||||
? `http://localhost:7001/invite?token=${inviteToken}&first_run=true`
|
||||
: "http://localhost:7001"
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,10 @@ program
|
||||
.description("Create a new Medusa project")
|
||||
.option("--repo-url <url>", "URL of repository to use to setup project.")
|
||||
.option("--seed", "Seed the created database with demo data.")
|
||||
.option(
|
||||
"--no-boilerplate",
|
||||
"Install a Medusa project without the boilerplate and demo files."
|
||||
)
|
||||
.parse()
|
||||
|
||||
void create(program.opts())
|
||||
|
||||
@@ -6,7 +6,6 @@ type CloneRepoOptions = {
|
||||
abortController?: AbortController
|
||||
}
|
||||
|
||||
// TODO change default repo URL
|
||||
const DEFAULT_REPO = "https://github.com/medusajs/medusa-starter-default"
|
||||
|
||||
export default async ({
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import onProcessTerminated from "./on-process-terminated.js"
|
||||
import ProcessManager from "./process-manager.js"
|
||||
|
||||
export default () => {
|
||||
export default (processManager: ProcessManager) => {
|
||||
const abortController = new AbortController()
|
||||
onProcessTerminated(() => abortController.abort())
|
||||
processManager.onTerminated(() => abortController.abort())
|
||||
return abortController
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import boxen from "boxen"
|
||||
import chalk from "chalk"
|
||||
import { Ora } from "ora"
|
||||
import onProcessTerminated from "./on-process-terminated.js"
|
||||
import { emojify } from "node-emoji"
|
||||
import ProcessManager from "./process-manager.js"
|
||||
|
||||
const facts = [
|
||||
"Plugins allow you to integrate third-party services for payment, fulfillment, notifications, and more.",
|
||||
@@ -31,17 +32,20 @@ export const getFact = () => {
|
||||
|
||||
export const showFact = (spinner: Ora, title: string) => {
|
||||
const fact = getFact()
|
||||
spinner.text = `${boxen(fact, {
|
||||
spinner.text = `${boxen(`${emojify(":bulb:")} Medusa Tips\n\n${fact}`, {
|
||||
title: chalk.cyan(title),
|
||||
titleAlignment: "center",
|
||||
textAlignment: "center",
|
||||
padding: 1,
|
||||
margin: 1,
|
||||
float: "center",
|
||||
})}`
|
||||
}
|
||||
|
||||
export const createFactBox = (spinner: Ora, title: string): NodeJS.Timer => {
|
||||
export const createFactBox = (
|
||||
spinner: Ora,
|
||||
title: string,
|
||||
processManager: ProcessManager
|
||||
): NodeJS.Timer => {
|
||||
spinner.spinner = {
|
||||
frames: [""],
|
||||
}
|
||||
@@ -50,7 +54,7 @@ export const createFactBox = (spinner: Ora, title: string): NodeJS.Timer => {
|
||||
showFact(spinner, title)
|
||||
}, 10000)
|
||||
|
||||
onProcessTerminated(() => clearInterval(interval))
|
||||
processManager.addInterval(interval)
|
||||
|
||||
return interval
|
||||
}
|
||||
@@ -59,6 +63,7 @@ export const resetFactBox = (
|
||||
interval: NodeJS.Timer | null,
|
||||
spinner: Ora,
|
||||
successMessage: string,
|
||||
processManager: ProcessManager,
|
||||
newTitle?: string
|
||||
): NodeJS.Timer | null => {
|
||||
if (interval) {
|
||||
@@ -69,7 +74,7 @@ export const resetFactBox = (
|
||||
spinner.succeed(chalk.green(successMessage)).start()
|
||||
let newInterval = null
|
||||
if (newTitle) {
|
||||
newInterval = createFactBox(spinner, newTitle)
|
||||
newInterval = createFactBox(spinner, newTitle, processManager)
|
||||
}
|
||||
|
||||
return newInterval
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
export default (fn: Function) => {
|
||||
process.on("SIGTERM", () => fn())
|
||||
process.on("SIGINT", () => fn())
|
||||
}
|
||||
@@ -4,8 +4,9 @@ import path from "path"
|
||||
import { Ora } from "ora"
|
||||
import promiseExec from "./promise-exec.js"
|
||||
import { EOL } from "os"
|
||||
import runProcess from "./run-process.js"
|
||||
import { createFactBox, resetFactBox } from "./facts.js"
|
||||
import { clearProject } from "@medusajs/utils"
|
||||
import ProcessManager from "./process-manager.js"
|
||||
|
||||
type PrepareOptions = {
|
||||
directory: string
|
||||
@@ -14,7 +15,9 @@ type PrepareOptions = {
|
||||
email: string
|
||||
}
|
||||
seed?: boolean
|
||||
boilerplate?: boolean
|
||||
spinner: Ora
|
||||
processManager: ProcessManager
|
||||
abortController?: AbortController
|
||||
}
|
||||
|
||||
@@ -23,7 +26,9 @@ export default async ({
|
||||
dbConnectionString,
|
||||
admin,
|
||||
seed,
|
||||
boilerplate,
|
||||
spinner,
|
||||
processManager,
|
||||
abortController,
|
||||
}: PrepareOptions) => {
|
||||
// initialize execution options
|
||||
@@ -43,10 +48,11 @@ export default async ({
|
||||
|
||||
let interval: NodeJS.Timer | null = createFactBox(
|
||||
spinner,
|
||||
"Installing dependencies..."
|
||||
"Installing dependencies...",
|
||||
processManager
|
||||
)
|
||||
|
||||
await runProcess({
|
||||
await processManager.runProcess({
|
||||
process: async () => {
|
||||
try {
|
||||
await promiseExec(`yarn`, execOptions)
|
||||
@@ -63,26 +69,73 @@ export default async ({
|
||||
interval,
|
||||
spinner,
|
||||
"Installed Dependencies",
|
||||
"Running Migrations...."
|
||||
processManager
|
||||
)
|
||||
|
||||
// run migrations
|
||||
await runProcess({
|
||||
if (!boilerplate) {
|
||||
interval = createFactBox(
|
||||
spinner,
|
||||
"Preparing Project Directory...",
|
||||
processManager
|
||||
)
|
||||
// delete files and directories related to onboarding
|
||||
clearProject(directory)
|
||||
interval = resetFactBox(
|
||||
interval,
|
||||
spinner,
|
||||
"Prepared Project Directory",
|
||||
processManager
|
||||
)
|
||||
}
|
||||
|
||||
interval = createFactBox(spinner, "Building Project...", processManager)
|
||||
await processManager.runProcess({
|
||||
process: async () => {
|
||||
await promiseExec(
|
||||
try {
|
||||
await promiseExec(`yarn build`, execOptions)
|
||||
} catch (e) {
|
||||
// yarn isn't available
|
||||
// use npm
|
||||
await promiseExec(`npm run build`, execOptions)
|
||||
}
|
||||
},
|
||||
ignoreERESOLVE: true,
|
||||
})
|
||||
|
||||
interval = resetFactBox(interval, spinner, "Project Built", processManager)
|
||||
|
||||
interval = createFactBox(spinner, "Running Migrations...", processManager)
|
||||
|
||||
// run migrations
|
||||
await processManager.runProcess({
|
||||
process: async () => {
|
||||
const proc = await promiseExec(
|
||||
"npx -y @medusajs/medusa-cli@latest migrations run",
|
||||
execOptions
|
||||
)
|
||||
|
||||
// ensure that migrations actually ran in case of an uncaught error
|
||||
if (!proc.stdout.includes("Migrations completed")) {
|
||||
throw new Error(
|
||||
`An error occurred while running migrations: ${
|
||||
proc.stderr || proc.stdout
|
||||
}`
|
||||
)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
interval = resetFactBox(interval, spinner, "Ran Migrations")
|
||||
interval = resetFactBox(interval, spinner, "Ran Migrations", processManager)
|
||||
|
||||
if (admin) {
|
||||
// create admin user
|
||||
interval = createFactBox(spinner, "Creating an admin user...")
|
||||
interval = createFactBox(
|
||||
spinner,
|
||||
"Creating an admin user...",
|
||||
processManager
|
||||
)
|
||||
|
||||
await runProcess({
|
||||
await processManager.runProcess({
|
||||
process: async () => {
|
||||
const proc = await promiseExec(
|
||||
`npx -y @medusajs/medusa-cli@latest user -e ${admin.email} --invite`,
|
||||
@@ -94,11 +147,16 @@ export default async ({
|
||||
},
|
||||
})
|
||||
|
||||
interval = resetFactBox(interval, spinner, "Created admin user")
|
||||
interval = resetFactBox(
|
||||
interval,
|
||||
spinner,
|
||||
"Created admin user",
|
||||
processManager
|
||||
)
|
||||
}
|
||||
|
||||
if (seed) {
|
||||
interval = createFactBox(spinner, "Seeding database...")
|
||||
if (seed || !boilerplate) {
|
||||
interval = createFactBox(spinner, "Seeding database...", processManager)
|
||||
|
||||
// check if a seed file exists in the project
|
||||
if (!fs.existsSync(path.join(directory, "data", "seed.json"))) {
|
||||
@@ -112,7 +170,7 @@ export default async ({
|
||||
return inviteToken
|
||||
}
|
||||
|
||||
await runProcess({
|
||||
await processManager.runProcess({
|
||||
process: async () => {
|
||||
await promiseExec(
|
||||
`npx -y @medusajs/medusa-cli@latest seed --seed-file=${path.join(
|
||||
@@ -123,14 +181,19 @@ export default async ({
|
||||
)
|
||||
},
|
||||
})
|
||||
resetFactBox(interval, spinner, "Seeded database with demo data")
|
||||
resetFactBox(
|
||||
interval,
|
||||
spinner,
|
||||
"Seeded database with demo data",
|
||||
processManager
|
||||
)
|
||||
} else if (
|
||||
fs.existsSync(path.join(directory, "data", "seed-onboarding.json"))
|
||||
) {
|
||||
// seed the database with onboarding seed
|
||||
interval = createFactBox(spinner, "Finish preparation...")
|
||||
interval = createFactBox(spinner, "Finish preparation...", processManager)
|
||||
|
||||
await runProcess({
|
||||
await processManager.runProcess({
|
||||
process: async () => {
|
||||
await promiseExec(
|
||||
`npx -y @medusajs/medusa-cli@latest seed --seed-file=${path.join(
|
||||
@@ -141,7 +204,7 @@ export default async ({
|
||||
)
|
||||
},
|
||||
})
|
||||
resetFactBox(interval, spinner, "Finished Preparation")
|
||||
resetFactBox(interval, spinner, "Finished Preparation", processManager)
|
||||
}
|
||||
|
||||
return inviteToken
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
type ProcessOptions = {
|
||||
process: Function
|
||||
ignoreERESOLVE?: boolean
|
||||
}
|
||||
|
||||
export default class ProcessManager {
|
||||
intervals: NodeJS.Timer[] = []
|
||||
static MAX_RETRIES = 3
|
||||
|
||||
constructor() {
|
||||
this.onTerminated(() => {
|
||||
this.intervals.forEach((interval) => {
|
||||
clearInterval(interval)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
onTerminated(fn: Function) {
|
||||
process.on("SIGTERM", () => fn())
|
||||
process.on("SIGINT", () => fn())
|
||||
}
|
||||
|
||||
addInterval(interval: NodeJS.Timer) {
|
||||
this.intervals.push(interval)
|
||||
}
|
||||
|
||||
// when running commands with npx or npm sometimes they
|
||||
// terminate with EAGAIN error unexpectedly
|
||||
// this utility function allows retrying the process if
|
||||
// EAGAIN occurs, or otherwise throw the error that occurs
|
||||
async runProcess({ process, ignoreERESOLVE }: ProcessOptions) {
|
||||
let processError = false
|
||||
let retries = 0
|
||||
do {
|
||||
retries++
|
||||
try {
|
||||
await process()
|
||||
} catch (error) {
|
||||
if (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"code" in error &&
|
||||
error?.code === "EAGAIN"
|
||||
) {
|
||||
processError = true
|
||||
} else if (
|
||||
ignoreERESOLVE &&
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"code" in error &&
|
||||
error?.code === "ERESOLVE"
|
||||
) {
|
||||
// ignore error
|
||||
} else {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
} while (processError && retries <= ProcessManager.MAX_RETRIES)
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
type ProcessOptions = {
|
||||
process: Function
|
||||
ignoreERESOLVE?: boolean
|
||||
}
|
||||
|
||||
// when running commands with npx or npm sometimes they
|
||||
// terminate with EAGAIN error unexpectedly
|
||||
// this utility function allows retrying the process if
|
||||
// EAGAIN occurs, or otherwise throw the error that occurs
|
||||
export default async ({ process, ignoreERESOLVE }: ProcessOptions) => {
|
||||
let processError = false
|
||||
do {
|
||||
try {
|
||||
await process()
|
||||
} catch (error) {
|
||||
if (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"code" in error &&
|
||||
error?.code === "EAGAIN"
|
||||
) {
|
||||
processError = true
|
||||
} else if (
|
||||
ignoreERESOLVE &&
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"code" in error &&
|
||||
error?.code === "ERESOLVE"
|
||||
) {
|
||||
// ignore error
|
||||
} else {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
} while (processError)
|
||||
}
|
||||
@@ -45,6 +45,7 @@
|
||||
"execa": "^5.1.1",
|
||||
"fs-exists-cached": "^1.0.0",
|
||||
"fs-extra": "^10.0.0",
|
||||
"glob": "^10.2.7",
|
||||
"hosted-git-info": "^4.0.2",
|
||||
"inquirer": "^8.0.0",
|
||||
"is-valid-path": "^0.1.1",
|
||||
|
||||
@@ -15,9 +15,11 @@ import url from "url"
|
||||
import { createDatabase } from "pg-god"
|
||||
import { track } from "medusa-telemetry"
|
||||
import inquirer from "inquirer"
|
||||
import { globSync } from "glob"
|
||||
|
||||
import reporter from "../reporter"
|
||||
import { getPackageManager, setPackageManager } from "../util/package-manager"
|
||||
import { clearProject } from "@medusajs/utils"
|
||||
|
||||
const removeUndefined = (obj) => {
|
||||
return Object.fromEntries(
|
||||
@@ -632,6 +634,12 @@ medusa new ${rootPath} [url-to-starter]
|
||||
}
|
||||
}
|
||||
|
||||
if (!selectedOtherStarter) {
|
||||
reporter.info("Final project preparations...")
|
||||
// remove demo files
|
||||
clearProject(rootPath)
|
||||
}
|
||||
|
||||
successMessage(rootPath)
|
||||
track("CLI_NEW_SUCCEEDED")
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"awilix": "^8.0.1",
|
||||
"glob": "^10.2.7",
|
||||
"ulid": "^2.3.0"
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import fs from "fs"
|
||||
import path from "path"
|
||||
import { globSync } from "glob"
|
||||
|
||||
export function clearProject (directory: string) {
|
||||
const files = globSync([
|
||||
path.join(directory, `src`, `admin/**/*`),
|
||||
path.join(directory, `src`, `**/onboarding/`),
|
||||
path.join(directory, `src`, `types`),
|
||||
path.join(directory, `src`, `**/*.{ts,tsx,js,jsx}`),
|
||||
])
|
||||
files.forEach((file) =>
|
||||
fs.rmSync(file, {
|
||||
recursive: true,
|
||||
force: true,
|
||||
})
|
||||
)
|
||||
// add empty typescript file to avoid build errors
|
||||
fs.openSync(path.join(directory, "src", "index.ts"), "w")
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./clear-project"
|
||||
@@ -1,5 +1,6 @@
|
||||
export * from "./bundles"
|
||||
export * from "./cli"
|
||||
export * from "./common"
|
||||
export * from "./decorators"
|
||||
export * from "./event-bus"
|
||||
export * from "./search"
|
||||
export * from "./search"
|
||||
Reference in New Issue
Block a user