Skip to content

Commit

Permalink
some console reporting improvements (#1746)
Browse files Browse the repository at this point in the history
* Prettier console reporting!

* Add some better GraphQL errors

* fixup CLI commands

* prettier

* Move Reporter to own directory
  • Loading branch information
jquense authored and KyleAMathews committed Aug 10, 2017
1 parent 1e8bf37 commit f8956a6
Show file tree
Hide file tree
Showing 17 changed files with 8,028 additions and 428 deletions.
4 changes: 3 additions & 1 deletion packages/gatsby/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
},
"dependencies": {
"async": "^2.1.2",
"babel-code-frame": "^6.22.0",
"babel-core": "^6.24.1",
"babel-loader": "^6.0.0",
"babel-plugin-add-module-exports": "^0.2.1",
Expand Down Expand Up @@ -85,6 +86,7 @@
"postcss-import": "^8.2.0",
"postcss-loader": "^0.13.0",
"postcss-reporter": "^1.4.1",
"pretty-error": "^2.1.1",
"raw-loader": "^0.5.1",
"react": "^15.6.0",
"react-dom": "^15.6.0",
Expand Down Expand Up @@ -152,6 +154,6 @@
"build:cli": "babel src/gatsby-cli.js --out-file dist/gatsby-cli.js --presets es2015",
"clean-test-bundles": "find test/ -type f -name bundle.js* -exec rm -rf {} +",
"test-coverage": "node_modules/.bin/nyc --reporter=lcov --reporter=text npm test",
"watch": "rimraf dist && mkdir dist && npm run build:cli && npm run build:src -- --watch && npm run build:internal-plugins && npm run build:rawfiles"
"watch": "rimraf dist && mkdir dist && npm run build:cli && npm run build:internal-plugins && npm run build:rawfiles && npm run build:src -- --watch"
}
}
15 changes: 13 additions & 2 deletions packages/gatsby/src/bin/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,25 @@ const _ = require(`lodash`)
const Promise = require(`bluebird`)
const resolveCwd = require(`resolve-cwd`)

const report = require(`../reporter`)

// Improve Promise error handling. Maybe... what's the best
// practice for this these days?
global.Promise = require(`bluebird`)

Promise.onPossiblyUnhandledRejection(error => {
report.error(error)
throw error
})

process.on(`unhandledRejection`, error => {
console.error(`UNHANDLED REJECTION`, error.stack)
// This will exit the process in newer Node anyway so lets be consistent
// across versions and crash
report.panic(`UNHANDLED REJECTION`, error)
})

process.on(`uncaughtException`, error => {
report.panic(`UNHANDLED EXCEPTION`, error)
})

const defaultHost = `localhost`
Expand Down Expand Up @@ -92,7 +103,7 @@ if (inGatsbySite) {
browserslist,
}
build(p).then(() => {
console.log(`Done building in`, process.uptime(), `seconds`)
report.success(`Done building in ${process.uptime()} seconds`)
process.exit()
})
})
Expand Down
91 changes: 31 additions & 60 deletions packages/gatsby/src/bootstrap/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@ const slash = require(`slash`)
const fs = require(`fs-extra`)
const md5File = require(`md5-file/promise`)
const crypto = require(`crypto`)
const report = require(`yurnalist`)
const convertHrtime = require(`convert-hrtime`)

const apiRunnerNode = require(`../utils/api-runner-node`)
const { graphql } = require(`graphql`)
const { store, emitter } = require(`../redux`)
const loadPlugins = require(`./load-plugins`)
const { initCache } = require(`../utils/cache`)
const report = require(`../reporter`)

const {
extractQueries,
Expand All @@ -23,26 +22,6 @@ const {
} = require(`../internal-plugins/query-runner/page-query-runner`)
const { writePages } = require(`../internal-plugins/query-runner/pages-writer`)

const activityTimer = name => {
const spinner = report.activity()
const start = process.hrtime()

const elapsedTime = function() {
var precision = 3 // 3 decimal places
var elapsed = process.hrtime(start)
return `${convertHrtime(elapsed)[`seconds`].toFixed(precision)} s`
}
return {
start: () => {
spinner.tick(name)
},
end: () => {
report.success(`${name}${elapsedTime()}`)
spinner.end()
},
}
}

// Override console.log to add the source file + line number.
// Useful for debugging if you lose a console.log somewhere.
// Otherwise leave commented out.
Expand All @@ -60,18 +39,16 @@ module.exports = async (program: any) => {
})

// Try opening the site's gatsby-config.js file.
let activity = activityTimer(`open and validate gatsby-config.js`)
let activity = report.activityTimer(`open and validate gatsby-config.js`)
activity.start()
let config
try {
// $FlowFixMe
config = preferDefault(require(`${program.directory}/gatsby-config`))
} catch (e) {
const firstLine = e.toString().split(`\n`)[0]
} catch (err) {
const firstLine = err.toString().split(`\n`)[0]
if (!/Error: Cannot find module.*gatsby-config/.test(firstLine)) {
console.log(``)
console.log(``)
console.log(e)
report.error(`Could not load gatsby-config`, err)
process.exit(1)
}
}
Expand Down Expand Up @@ -116,20 +93,18 @@ module.exports = async (program: any) => {
// Also if the hash isn't there, then delete things just in case something
// is weird.
if (oldPluginsHash && pluginsHash !== oldPluginsHash) {
console.log(
`
One or more of your plugins have changed since the last time you ran Gatsby. As
a precaution, we're deleting your site's cache to ensure there's not any stale
data
`
)
report.info(report.stripIndent`
One or more of your plugins have changed since the last time you ran Gatsby. As
a precaution, we're deleting your site's cache to ensure there's not any stale
data
`)
}

if (!oldPluginsHash || pluginsHash !== oldPluginsHash) {
try {
await fs.remove(`${program.directory}/.cache`)
} catch (e) {
console.error(`Failed to remove .cache files. ${e.message}`)
report.error(`Failed to remove .cache files.`, e)
}
// Tell reducers to delete their data (the store will already have
// been loaded from the file system cache).
Expand All @@ -152,18 +127,16 @@ data
await fs.ensureDirSync(`${program.directory}/public/static`)

// Copy our site files to the root of the site.
activity = activityTimer(`copy gatsby files`)
activity = report.activityTimer(`copy gatsby files`)
activity.start()
const srcDir = `${__dirname}/../cache-dir`
const siteDir = `${program.directory}/.cache`
try {
await fs.copy(srcDir, siteDir, { clobber: true })
await fs.ensureDirSync(`${program.directory}/.cache/json`)
await fs.ensureDirSync(`${program.directory}/.cache/layouts`)
} catch (e) {
console.log(`Unable to copy site files to .cache`)
console.log(e)
process.exit(1)
} catch (err) {
report.panic(`Unable to copy site files to .cache`, err)
}

// Find plugins which implement gatsby-browser and gatsby-ssr and write
Expand Down Expand Up @@ -199,7 +172,7 @@ data
`utf-8`
)
} catch (err) {
console.error(`Failed to read ${siteDir}/api-runner-browser.js`)
report.panic(`Failed to read ${siteDir}/api-runner-browser.js`, err)
}

const browserPluginsRequires = browserPlugins
Expand All @@ -219,7 +192,7 @@ data
try {
sSRAPIRunner = fs.readFileSync(`${siteDir}/api-runner-ssr.js`, `utf-8`)
} catch (err) {
console.error(`Failed to read ${siteDir}/api-runner-ssr.js`)
report.panic(`Failed to read ${siteDir}/api-runner-ssr.js`, err)
}

const ssrPluginsRequires = ssrPlugins
Expand All @@ -243,13 +216,13 @@ data
activity.end()

// Source nodes
activity = activityTimer(`source and transform nodes`)
activity = report.activityTimer(`source and transform nodes`)
activity.start()
await require(`../utils/source-nodes`)()
activity.end()

// Create Schema.
activity = activityTimer(`building schema`)
activity = report.activityTimer(`building schema`)
activity.start()
await require(`../schema`)()
activity.end()
Expand All @@ -273,7 +246,7 @@ data
}

// Collect layouts.
activity = activityTimer(`createLayouts`)
activity = report.activityTimer(`createLayouts`)
activity.start()
await apiRunnerNode(`createLayouts`, {
graphql: graphqlRunner,
Expand All @@ -283,7 +256,7 @@ data
activity.end()

// Collect pages.
activity = activityTimer(`createPages`)
activity = report.activityTimer(`createPages`)
activity.start()
await apiRunnerNode(`createPages`, {
graphql: graphqlRunner,
Expand All @@ -296,7 +269,7 @@ data
// have full control over adding/removing pages. The normal
// "createPages" API is called every time (during development)
// that data changes.
activity = activityTimer(`createPagesStatefully`)
activity = report.activityTimer(`createPagesStatefully`)
activity.start()
await apiRunnerNode(`createPagesStatefully`, {
graphql: graphqlRunner,
Expand All @@ -305,45 +278,43 @@ data
})
activity.end()
// Extract queries
activity = activityTimer(`extract queries from components`)
activity = report.activityTimer(`extract queries from components`)
activity.start()
await extractQueries()
activity.end()

// Run queries
activity = activityTimer(`run graphql queries`)
activity = report.activityTimer(`run graphql queries`)
activity.start()
await runQueries()
activity.end()

// Write out files.
activity = activityTimer(`write out page data`)
activity = report.activityTimer(`write out page data`)
activity.start()
await writePages()
activity.end()

// Update Schema for SitePage.
activity = activityTimer(`update schema`)
activity = report.activityTimer(`update schema`)
activity.start()
await require(`../schema`)()
activity.end()

const checkJobsDone = _.debounce(resolve => {
const state = store.getState()
if (state.jobs.active.length === 0) {
console.log(``)
console.log(
`bootstrap finished, time since started: ${process.uptime()}sec`
)
console.log(``)
report.log(``)
report.info(`bootstrap finished - ${process.uptime()} s`)
report.log(``)
resolve({ graphqlRunner })
}
}, 100)

if (store.getState().jobs.active.length === 0) {
console.log(``)
console.log(`bootstrap finished, time since started: ${process.uptime()} s`)
console.log(``)
report.log(``)
report.info(`bootstrap finished - ${process.uptime()} s`)
report.log(``)
return { graphqlRunner }
} else {
return new Promise(resolve => {
Expand Down
19 changes: 9 additions & 10 deletions packages/gatsby/src/gatsby-cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@ const path = require(`path`)
const fs = require(`fs`)
const _ = require(`lodash`)

const report = require(`./reporter`)

const version = process.version
const verDigit = Number(version.match(/\d+/)[0])

if (verDigit < 4) {
console.error(
`Gatsby 1.0+ requires node.js v4 or higher (you have ${version}).
Upgrade node to the latest stable release.`
report.panic(
`Gatsby 1.0+ requires node.js v4 or higher (you have ${version}). \n` +
`Upgrade node to the latest stable release.`
)
process.exit()
}

/*
Expand All @@ -24,11 +25,10 @@ const localPath = path.resolve(`node_modules/gatsby`, cliFile)
const useGlobalGatsby = function() {
// Never use global install *except* for new and help commands
if (!_.includes([`new`, `--help`], process.argv[2])) {
console.error(
`A local install of Gatsby was not found.
You should save Gatsby as a site dependency e.g. npm install --save gatsby`
report.panic(
`A local install of Gatsby was not found. \n` +
`You should save Gatsby as a site dependency e.g. npm install --save gatsby`
)
process.exit()
}

require(`./bin/cli`)
Expand All @@ -38,8 +38,7 @@ if (fs.existsSync(localPath)) {
try {
require(localPath)
} catch (error) {
console.error(`A local install of Gatsby exists but failed to load.`)
console.error(error)
report.error(`A local install of Gatsby exists but failed to load.`, error)
}
} else {
useGlobalGatsby()
Expand Down
Loading

0 comments on commit f8956a6

Please sign in to comment.