Skip to content

Commit

Permalink
[cli] Restructure and clean up init command
Browse files Browse the repository at this point in the history
  • Loading branch information
rexxars authored and skogsmaskin committed Dec 7, 2017
1 parent b18a115 commit b033986
Show file tree
Hide file tree
Showing 25 changed files with 122 additions and 150 deletions.
14 changes: 14 additions & 0 deletions packages/@sanity/cli/scripts/pack.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,20 @@ compiler.run((err, stats) => {
throw err
}

if (stats.compilation.warnings.length > 0) {
console.warn('=== [ Warnings ]========')
stats.compilation.warnings.forEach(warn => {
if (!warn.name === 'ModuleDependencyWarning') {
console.warn(warn)
return
}

console.warn(`\n${warn.origin.userRequest}:`)
console.warn(`${warn}\n`)
})
console.warn('=== [ /Warnings ]========\n')
}

if (stats.compilation.errors.length > 0) {
console.error(stats.compilation.errors)
process.exit(1)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import os from 'os'
import path from 'path'
import fse from 'fs-extra'
import resolveFrom from 'resolve-from'
import deburr from 'lodash/deburr'
import noop from 'lodash/noop'
import debug from '../../debug'
import getUserConfig from '../../util/getUserConfig'
import getProjectDefaults from '../../util/getProjectDefaults'
import createProject from '../../actions/project/createProject'
import login from '../../actions/login/login'
import createProject from '../project/createProject'
import login from '../login/login'
import dynamicRequire from '../../util/dynamicRequire'
import promptForDatasetName from './promptForDatasetName'
import gatherInput from './gatherInput'
import bootstrapTemplate from './bootstrapTemplate'

export default async function initSanity(args, context) {
Expand Down Expand Up @@ -71,17 +72,30 @@ export default async function initSanity(args, context) {
outputPath: path.resolve(flags['output-path'])
})
} else {
answers = await gatherInput(prompt, defaults, {workDir, sluggedName})
answers = {}
answers.description = answers.description || defaults.description
answers.gitRemote = defaults.gitRemote
answers.author = defaults.author
answers.license = 'UNLICENSED'

const workDirIsEmpty = (await fse.readdir(workDir)).length === 0
answers.outputPath = await prompt.single({
type: 'input',
message: 'Output path:',
default: workDirIsEmpty ? workDir : path.join(workDir, sluggedName),
validate: validateEmptyPath,
filter: absolutify
})
}

// Ensure we are using the output path provided by user
const outputPath = answers.outputPath || workDir

// Prompt for template to use
const defaultTemplate = unattended ? flags.template || 'clean' : null
const templateName
= defaultTemplate
|| (await prompt.single({
const templateName =
defaultTemplate ||
(await prompt.single({
message: 'Select project template',
type: 'list',
choices: [
Expand Down Expand Up @@ -268,3 +282,39 @@ export default async function initSanity(args, context) {
return {datasetName: selected}
}
}

async function validateEmptyPath(dir) {
const checkPath = absolutify(dir)
return (await pathIsEmpty(checkPath)) ? true : 'Given path is not empty'
}

function pathIsEmpty(dir) {
return fse
.readdir(dir)
.then(content => content.length === 0)
.catch(err => {
if (err.code === 'ENOENT') {
return true
}

throw err
})
}

function expandHome(filePath) {
if (filePath.charCodeAt(0) === 126 /* ~ */) {
if (filePath.charCodeAt(1) === 43 /* + */) {
return path.join(process.cwd(), filePath.slice(2))
}

const home = os.homedir()
return home ? path.join(home, filePath.slice(1)) : filePath
}

return filePath
}

function absolutify(dir) {
const pathName = expandHome(dir)
return path.isAbsolute(pathName) ? pathName : path.resolve(process.cwd(), pathName)
}
6 changes: 4 additions & 2 deletions packages/@sanity/cli/src/actions/yarn/yarnWithProgress.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import split2 from 'split2'
import chalk from 'chalk'
import progrescii from 'progrescii'
import {noop, padEnd, throttle} from 'lodash'
import dynamicRequire from '../../util/dynamicRequire'

const useProgress = process.stderr && process.stderr.isTTY && !process.env.CI
const isBundled = typeof __SANITY_IS_BUNDLED__ !== 'undefined'
Expand All @@ -14,7 +15,7 @@ const isBundled = typeof __SANITY_IS_BUNDLED__ !== 'undefined'
const binDir = path.join(__dirname, '..', '..', '..', 'vendor')
const yarnPath = isBundled
? path.join(__dirname, '..', 'vendor', 'yarn')
: require.resolve(path.join(binDir, 'yarn'))
: dynamicRequire.resolve(path.join(binDir, 'yarn'))

const parseJson = data => {
try {
Expand Down Expand Up @@ -59,7 +60,8 @@ export default function yarnWithProgress(args, options = {}) {
return proc
}

[proc.stdout, proc.stderr].forEach(stream => {
const streams = [proc.stdout, proc.stderr]
streams.forEach(stream => {
stream
.pipe(split2(parseJson))
.on('data', onChunk)
Expand Down
111 changes: 0 additions & 111 deletions packages/@sanity/cli/src/commands/init/gatherInput.js

This file was deleted.

16 changes: 0 additions & 16 deletions packages/@sanity/cli/src/commands/init/initAction.js

This file was deleted.

19 changes: 16 additions & 3 deletions packages/@sanity/cli/src/commands/init/initCommand.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import initAction from './initAction'
import initProject from '../../actions/init-project/initProject'
import initPlugin from '../../actions/init-plugin/initPlugin'

const helpText = `
Options
Expand Down Expand Up @@ -28,6 +29,18 @@ export default {
name: 'init',
signature: 'init [plugin]',
description: 'Initialize a new Sanity project or plugin',
action: initAction,
helpText
helpText,
action: (args, context) => {
const [type] = args.argsWithoutOptions

if (!type) {
return initProject(args, context)
}

if (type === 'plugin') {
return initPlugin(args, context)
}

return Promise.reject(new Error(`Unknown init type "${type}"`))
}
}
12 changes: 6 additions & 6 deletions packages/@sanity/cli/src/util/dynamicRequire.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
// use regular node require for unbundled context

/* eslint-disable camelcase, no-undef */
const requireFunc = (
typeof __webpack_require__ === 'function'
? __non_webpack_require__
: require
)
const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require
/* eslint-enable camelcase, no-undef */

module.exports = request => {
const dynamicRequire = request => {
const mod = requireFunc(request)
return mod.__esModule && mod.default ? mod.default : mod
}

dynamicRequire.resolve = requireFunc.resolve

module.exports = dynamicRequire
15 changes: 15 additions & 0 deletions packages/@sanity/util/src/dynamicRequire.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Prevent webpack from bundling in webpack context,
// use regular node require for unbundled context

/* eslint-disable camelcase, no-undef */
const requireFunc = (
typeof __webpack_require__ === 'function'
? __non_webpack_require__
: require
)
/* eslint-enable camelcase, no-undef */

module.exports = request => {
const mod = requireFunc(request)
return mod.__esModule && mod.default ? mod.default : mod
}
5 changes: 3 additions & 2 deletions packages/@sanity/util/src/getSanityVersions.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
const path = require('path')
const uniq = require('lodash/uniq')
const resolveFrom = require('resolve-from')
const dynamicRequire = require('./dynamicRequire')

const getSanityVersions = basePath => {
const manifestPath = path.join(basePath, 'package.json')

let pkg
try {
pkg = require(manifestPath)
pkg = dynamicRequire(manifestPath)
} catch (err) {
throw new Error(`Could not load package.json from ${manifestPath}`)
}
Expand All @@ -16,7 +17,7 @@ const getSanityVersions = basePath => {
const sanityDeps = dependencies.filter(depName => depName.indexOf('@sanity/') === 0)
const versions = uniq(sanityDeps).reduce((target, moduleId) => {
const modulePath = resolveFrom.silent(basePath, path.join(moduleId, 'package.json'))
target[moduleId] = modulePath && require(modulePath).version
target[moduleId] = modulePath && dynamicRequire(modulePath).version
return target
}, {})

Expand Down
2 changes: 2 additions & 0 deletions packages/@sanity/util/src/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import getConfig from './getConfig'
import reduceConfig from './reduceConfig'
import lazyRequire from './lazyRequire'
import dynamicRequire from './dynamicRequire'
import safeJson from './safeJson'
import getSanityVersions from './getSanityVersions'
import * as pathTools from './pathTools'
Expand All @@ -9,6 +10,7 @@ export {
getConfig,
reduceConfig,
lazyRequire,
dynamicRequire,
safeJson,
getSanityVersions,
pathTools
Expand Down
8 changes: 5 additions & 3 deletions packages/@sanity/util/src/lazyRequire.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
export default id => (...args) => {
const mod = require(id)
return mod.__esModule ? mod.default(...args) : mod(...args)
const dynamicRequire = require('./dynamicRequire')

module.exports = id => (...args) => {
const mod = dynamicRequire(id)
return mod(...args)
}

0 comments on commit b033986

Please sign in to comment.