1
0
Fork 0

fix(new-design): Handle cwd for NodeJS 16

This commit is contained in:
Joost De Cock 2022-10-04 23:37:03 +02:00
parent 6f0b1a6ce3
commit 7eccffe177

View file

@ -8,28 +8,38 @@ import prompts from 'prompts'
import { oraPromise } from 'ora' import { oraPromise } from 'ora'
import { execa } from 'execa' import { execa } from 'execa'
import axios from 'axios' import axios from 'axios'
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url'
// Current working directory // Current working directory
const cwd = __dirname let cwd
? __dirname try {
: dirname(fileURLToPath(import.meta.url)) cwd = __dirname
} catch {
cwd = dirname(fileURLToPath(import.meta.url))
}
const nl = '\n'
const nl = "\n" const tab = ' '
const tab = " " const nlt = nl + tab
const nlt = nl+tab
// Checks for node 14 or higher // Checks for node 14 or higher
export const checkNodeVersion = () => { export const checkNodeVersion = () => {
const node_version = process.version.slice(1).split('.')[0] const node_version = process.version.slice(1).split('.')[0]
if (parseInt(node_version) < config.node) { if (parseInt(node_version) < config.node) {
console.log( console.log(
chalk.yellow(nlt+`⚠️ FreeSewing requires Node v${config.node} or newer`) + chalk.yellow(nlt + `⚠️ FreeSewing requires Node v${config.node} or newer`) +
nl+nlt+'We hightly recommend using NVM to manage your Node versions:' + nl +
nlt+chalk.blue('https://github.com/nvm-sh/nvm') + nlt +
nl+nlt+'When in doubt, pick an active LTS version:' + 'We hightly recommend using NVM to manage your Node versions:' +
nlt+chalk.blue('https://nodejs.org/en/about/releases/')+nl+nl nlt +
chalk.blue('https://github.com/nvm-sh/nvm') +
nl +
nlt +
'When in doubt, pick an active LTS version:' +
nlt +
chalk.blue('https://nodejs.org/en/about/releases/') +
nl +
nl
) )
process.exit(1) process.exit(1)
} }
@ -43,18 +53,37 @@ const validateDesignName = (name) => {
// Gets user input to figure out what to do // Gets user input to figure out what to do
export const getChoices = async () => { export const getChoices = async () => {
const { template } = await prompts({ const { template } = await prompts({
type: 'select', type: 'select',
name: 'template', name: 'template',
message: 'What template would you like to use? 📑', message: 'What template would you like to use? 📑',
choices: [ choices: [
{ title: 'From Scratch', value: 'scratch', description: 'Create a design from scratch' }, { title: 'From Scratch', value: 'scratch', description: 'Create a design from scratch' },
{ title: 'Extend Brian', value: 'brian', description: "Extend the Brian design (basic torso block for menswear)" }, {
{ title: 'Extend Bent', value: 'bent', description: "Extend the Bent design (like brian with added two-part sleeve)" }, title: 'Extend Brian',
{ title: 'Extend Bella', value: 'bella', description: "Extend the Bella design (womenswear torso block)" }, value: 'brian',
{ title: 'Extend Breanna', value: 'breanna', description: "Extend the Breanna design (womenswear torso block - YMMV)" }, description: 'Extend the Brian design (basic torso block for menswear)',
{ title: 'Extend Titan', value: 'titan', description: "Extend the Titan design (gender-neutral trouser block)" }, },
{
title: 'Extend Bent',
value: 'bent',
description: 'Extend the Bent design (like brian with added two-part sleeve)',
},
{
title: 'Extend Bella',
value: 'bella',
description: 'Extend the Bella design (womenswear torso block)',
},
{
title: 'Extend Breanna',
value: 'breanna',
description: 'Extend the Breanna design (womenswear torso block - YMMV)',
},
{
title: 'Extend Titan',
value: 'titan',
description: 'Extend the Titan design (gender-neutral trouser block)',
},
], ],
initial: 0, initial: 0,
}) })
@ -72,7 +101,7 @@ export const getChoices = async () => {
message: 'Last but not least, what package manager do you use? 📦', message: 'Last but not least, what package manager do you use? 📦',
choices: [ choices: [
{ title: 'yarn', value: 'yarn', description: 'Yarn - Nice if you have it' }, { title: 'yarn', value: 'yarn', description: 'Yarn - Nice if you have it' },
{ title: 'npm', value: 'npm', description: "NPM - Comes with NodeJS" }, { title: 'npm', value: 'npm', description: 'NPM - Comes with NodeJS' },
], ],
initial: 0, initial: 0,
}) })
@ -82,10 +111,8 @@ export const getChoices = async () => {
// Keep track of directories that need to be created // Keep track of directories that need to be created
const dirs = {} const dirs = {}
const ensureDir = async (file, suppress=false) => { const ensureDir = async (file, suppress = false) => {
const dir = suppress const dir = suppress ? dirname(file.replace(suppress)) : dirname(file)
? dirname(file.replace(suppress))
: dirname(file)
if (!dirs[dir]) { if (!dirs[dir]) {
await mkdir(dir, { recursive: true }) await mkdir(dir, { recursive: true })
dirs[dir] = true dirs[dir] = true
@ -94,7 +121,6 @@ const ensureDir = async (file, suppress=false) => {
// Helper method to copy template files // Helper method to copy template files
const copyTemplate = async (config, choices) => { const copyTemplate = async (config, choices) => {
// Copy files in parallel rather than using await // Copy files in parallel rather than using await
const promises = [] const promises = []
@ -114,17 +140,15 @@ const copyTemplate = async (config, choices) => {
* in our package. So we use _package.json, and if we see that we * in our package. So we use _package.json, and if we see that we
* rename it here to package.json * rename it here to package.json
*/ */
let to = join(config.dest, from.slice(config.source.template.length -7)) let to = join(config.dest, from.slice(config.source.template.length - 7))
if (to.slice(-13) === '_package.json') { if (to.slice(-13) === '_package.json') {
to = to.slice(0, -13) + 'package.json' to = to.slice(0, -13) + 'package.json'
} }
if (!dirs[to]) await ensureDir(to) if (!dirs[to]) await ensureDir(to)
if ([ 'config.js', 'kage.json'].indexOf(from.slice(-9)) !== -1) { if (['config.js', 'kage.json'].indexOf(from.slice(-9)) !== -1) {
// Template out file rather than coy it // Template out file rather than coy it
const src = await readFile(from, 'utf-8') const src = await readFile(from, 'utf-8')
promises.push( promises.push(writeFile(to, mustache.render(src, { name: choices.name })))
writeFile(to, mustache.render(src, { name: choices.name }))
)
} else { } else {
// Just copy the file // Just copy the file
promises.push(copyFile(from, to)) promises.push(copyFile(from, to))
@ -137,27 +161,28 @@ const copyTemplate = async (config, choices) => {
} }
// Helper method to run [yarn|npm] install // Helper method to run [yarn|npm] install
const installDependencies = async (config, choices) => await execa( const installDependencies = async (config, choices) =>
`${choices.manager} install`, await execa(`${choices.manager} install`, {
{
cwd: config.dest, cwd: config.dest,
shell: true shell: true,
} })
)
// Helper method to download web environment // Helper method to download web environment
const downloadLabFiles = async (config) => { const downloadLabFiles = async (config) => {
const promises = [] const promises = []
for (const dir in config.fetch) { for (const dir in config.fetch) {
for (const file of config.fetch[dir]) { for (const file of config.fetch[dir]) {
const to = (typeof file === 'string') const to = typeof file === 'string' ? join(config.dest, file) : join(config.dest, file.to)
? join(config.dest, file)
: join(config.dest, file.to)
if (!dirs[to]) await ensureDir(to) if (!dirs[to]) await ensureDir(to)
promises.push( promises.push(
axios.get(`${config.fileUri}/${config.repo}/${config.branch}/${dir}/${typeof file === 'string' ? file : file.from}`) axios
.catch(err => console.log(err)) .get(
.then(res => promises.push(writeFile(to, res.data))) `${config.fileUri}/${config.repo}/${config.branch}/${dir}/${
typeof file === 'string' ? file : file.from
}`
)
.catch((err) => console.log(err))
.then((res) => promises.push(writeFile(to, res.data)))
) )
} }
} }
@ -175,14 +200,17 @@ const initGitRepo = async (config, choices) => {
`git init -b main && git add . && git commit -m ":tada: Initialized ${choices.name} repository"`, `git init -b main && git add . && git commit -m ":tada: Initialized ${choices.name} repository"`,
{ {
cwd: config.dest, cwd: config.dest,
shell: true shell: true,
} }
) )
} }
// Tips // Tips
const showTips = (config, choices) => console.log(` const showTips = (config, choices) =>
All done 🤓 Your new design ${chalk.yellow.bold(choices.name)} was initialized in: ${chalk.green.bold(config.dest)} console.log(`
All done 🤓 Your new design ${chalk.yellow.bold(
choices.name
)} was initialized in: ${chalk.green.bold(config.dest)}
The code for your design is in the ${chalk.yellow.bold('design')} folder. The code for your design is in the ${chalk.yellow.bold('design')} folder.
The other files and folders are the development environment. You can safely ignore those. The other files and folders are the development environment. You can safely ignore those.
@ -190,13 +218,17 @@ const showTips = (config, choices) => console.log(`
To start your development environment, follow these three steps: To start your development environment, follow these three steps:
1) Start by entering the directory: ${chalk.blue.bold('cd ' + config.dest)} 1) Start by entering the directory: ${chalk.blue.bold('cd ' + config.dest)}
2) Then run this command: ${chalk.blue.bold((choices.manager === 'yarn' ? 'yarn dev' : 'npm run dev'))} 2) Then run this command: ${chalk.blue.bold(
choices.manager === 'yarn' ? 'yarn dev' : 'npm run dev'
)}
3) Now open your browser and navigate to ${chalk.green('http://localhost:8000/')} 3) Now open your browser and navigate to ${chalk.green('http://localhost:8000/')}
${chalk.bold.yellow('🤔 More info & help')} ${chalk.bold.yellow('🤔 More info & help')}
${chalk.gray('≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡')} ${chalk.gray('≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡')}
FreeSewing's documentation for developers is available at: ${chalk.green('https://freesewing.dev/')} FreeSewing's documentation for developers is available at: ${chalk.green(
'https://freesewing.dev/'
)}
Our community is on Discord: ${chalk.green('https://discord.freesewing.dev/')} Our community is on Discord: ${chalk.green('https://discord.freesewing.dev/')}
The ${chalk.bold('development-help')} channel is a good place to ask for help if you get stuck The ${chalk.bold('development-help')} channel is a good place to ask for help if you get stuck
@ -205,17 +237,15 @@ const showTips = (config, choices) => console.log(`
Happy hacking 🤓 Happy hacking 🤓
`) `)
// Creates the environment based on the user's choices // Creates the environment based on the user's choices
export const createEnvironment = async (choices) => { export const createEnvironment = async (choices) => {
// Store directories for re-use // Store directories for re-use
config.cwd = cwd, ;(config.cwd = cwd),
config.source = { (config.source = {
root: cwd, root: cwd,
template: cwd + `/../templates/from-${choices.template}`, template: cwd + `/../templates/from-${choices.template}`,
shared: cwd + `/../shared` shared: cwd + `/../shared`,
} })
config.dest = join(process.cwd(), choices.name) config.dest = join(process.cwd(), choices.name)
// Create target directory // Create target directory
@ -232,53 +262,64 @@ export const createEnvironment = async (choices) => {
// Copy/Template files // Copy/Template files
try { try {
await oraPromise( await oraPromise(copyTemplate(config, choices), {
copyTemplate(config, choices), text:
{ chalk.white.bold('🟨⬜⬜⬜ Copying template files') +
text: chalk.white.bold('🟨⬜⬜⬜ Copying template files')+chalk.white.dim(' | Just a moment'), chalk.white.dim(' | Just a moment'),
successText: chalk.white.bold('🟩⬜⬜⬜ Copied template files'), successText: chalk.white.bold('🟩⬜⬜⬜ Copied template files'),
failText: chalk.white.bold('🟥⬜⬜⬜ Failed to copy template files | Development environment will not function'), failText: chalk.white.bold(
'🟥⬜⬜⬜ Failed to copy template files | Development environment will not function'
),
})
} catch (err) {
/* no feedback here */
} }
)
} catch (err) { /* no feedback here */ }
// Install dependencies // Install dependencies
try { try {
await oraPromise( await oraPromise(installDependencies(config, choices), {
installDependencies(config, choices), text:
{ chalk.white.bold('🟩🟨⬜⬜ Installing dependencies') +
text: chalk.white.bold('🟩🟨⬜⬜ Installing dependencies')+chalk.white.dim(' | Please wait, this will take a while'), chalk.white.dim(' | Please wait, this will take a while'),
successText: chalk.white.bold('🟩🟩⬜⬜ Installed dependencies'), successText: chalk.white.bold('🟩🟩⬜⬜ Installed dependencies'),
failText: chalk.white.bold('🟩🟥⬜⬜ Failed to install dependencies | Development environment will not function'), failText: chalk.white.bold(
'🟩🟥⬜⬜ Failed to install dependencies | Development environment will not function'
),
})
} catch (err) {
/* no feedback here */
} }
)
} catch (err) { /* no feedback here */ }
// Fetch web components // Fetch web components
try { try {
await oraPromise( await oraPromise(downloadLabFiles(config), {
downloadLabFiles(config), text:
{ chalk.white.bold('🟩🟩🟨⬜ Downloading web components') +
text: chalk.white.bold('🟩🟩🟨⬜ Downloading web components')+chalk.white.dim(' | Almost there'), chalk.white.dim(' | Almost there'),
successText: chalk.white.bold('🟩🟩🟩⬜ Downloaded web components'), successText: chalk.white.bold('🟩🟩🟩⬜ Downloaded web components'),
failText: chalk.white.bold('🟩🟩🟥⬜ Failed to download web components | Development environment will not function'), failText: chalk.white.bold(
'🟩🟩🟥⬜ Failed to download web components | Development environment will not function'
),
})
} catch (err) {
/* no feedback here */
} }
)
} catch (err) { /* no feedback here */ }
// Initialize git repository // Initialize git repository
try { try {
await oraPromise( await oraPromise(initGitRepo(config, choices), {
initGitRepo(config, choices), text:
{ chalk.white.bold('🟩🟩🟩⬜ Initializing git repository') +
text: chalk.white.bold('🟩🟩🟩⬜ Initializing git repository')+chalk.white.dim(' | You have git, right?'), chalk.white.dim(' | You have git, right?'),
successText: chalk.white.bold('🟩🟩🟩🟩 Initialized git repository'), successText: chalk.white.bold('🟩🟩🟩🟩 Initialized git repository'),
failText: chalk.white.bold('🟩🟩🟩🟥 Failed to initialize git repository')+chalk.white.dim(' | This does not stop you from developing your design'), failText:
chalk.white.bold('🟩🟩🟩🟥 Failed to initialize git repository') +
chalk.white.dim(' | This does not stop you from developing your design'),
})
} catch (err) {
/* no git no worries */
} }
)
} catch (err) { /* no git no worries */ }
// All done. Show tips // All done. Show tips
showTips(config, choices) showTips(config, choices)
} }