Skip to content

Commit

Permalink
Add tests for all helpers
Browse files Browse the repository at this point in the history
- Refactored helper tests to actually use handlebars
- Fix tests and code-style
- Refactored tests for example helper and added for json helper
- Tests for exec- and renderTree-helpers
- Test für "#withPackageOf"- and "github"-helpers
- Test for npm-helper and hasCoveralls-helper
- Test for dirtree with condensed nodes
  • Loading branch information
nknapp committed Mar 19, 2017
1 parent 8f2cc3b commit 5ad6c17
Show file tree
Hide file tree
Showing 47 changed files with 598 additions and 156 deletions.
3 changes: 2 additions & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
coverage
test/fixtures
test/fixtures
test-output
32 changes: 7 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
[![NPM version](https://badge.fury.io/js/thought.svg)](http://badge.fury.io/js/thought)
[![Travis Build Status](https://travis-ci.org/nknapp/thought.svg?branch=master)](https://travis-ci.org/nknapp/thought)
[![Coverage Status](https://img.shields.io/coveralls/nknapp/thought.svg)](https://coveralls.io/r/nknapp/thought)
[![Greenkeeper badge](https://badges.greenkeeper.io/nknapp/thought.svg)](https://greenkeeper.io/)

> A customizable documentation generator for github projects
Expand Down Expand Up @@ -66,9 +65,8 @@ In the default configuration, this will generate a `README.md` from the informat
Consider the following example

<pre><code>

├── LICENSE.md
├── examples
├── examples/
├── index.js
└── package.json
</code></pre>
Expand Down Expand Up @@ -164,11 +162,10 @@ You can find the default configuration in the [partials/](partials/) directory.
has the structure.

<pre><code>

├── helpers.js
├─┬ partials
├─┬ partials/
│ ├── api.md.hbs
│ ├─┬ badge
│ ├─┬ badge/
│ │ ├── appveyor.md.hbs
│ │ ├── coveralls.md.hbs
│ │ ├── greenkeeper.md.hbs
Expand All @@ -183,7 +180,7 @@ has the structure.
│ ├── overview.md.hbs
│ └── usage.md.hbs
├── preprocessor.js
└─┬ templates
└─┬ templates/
├── CONTRIBUTING.md.hbs
└── README.md.hbs
</code></pre>
Expand Down Expand Up @@ -229,30 +226,15 @@ as context data, but if you return promises, they will be resolved seamlessly.


## API-reference

<a name="thought"></a>

## thought(options)
Execute Thought in the current directory

**Kind**: global function
**Api**: public

| Param | Type | Description |
| --- | --- | --- |
| options | <code>object</code> | |
| [options.cwd] | <code>string</code> | the working directory to use as project root |
| [options.addToGit] | <code>boolean</code> | add created files to git |




## License

`thought` is published under the MIT-license.
`thought` is published under the MIT-license.

See [LICENSE.md](LICENSE.md) for details.


## Release-Notes

For release notes, see [CHANGELOG.md](CHANGELOG.md)
Expand Down
11 changes: 8 additions & 3 deletions bin/thought.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,20 @@ program
changeDir()
var packageJson = findPackage()
if (!(packageJson.scripts && packageJson.scripts.thought)) {
/* eslint-disable no-console */
console.log('\nNot registered in package.json yet!\n' +
'I can add a `scripts`-property to your package.json to ensure that ' +
'documentation is generated automatically on version bumps.\n' +
'If you want that, run `thought init`\n')
/* eslint-enable no-console */
}
thought({
addToGit: options.addToGit,
debug: program.debug
}).done(function (filenames) {
/* eslint-disable no-console */
console.log('The following files were updated: ' + filenames.join(', '))
/* eslint-enable no-console */
})
})

Expand All @@ -58,7 +62,7 @@ program
require('../lib/check-engines.js')()
.then(require('../lib/init.js'))
.done(function () {
console.log('OK')
console.log('OK') // eslint-disable-line no-console
})
})

Expand All @@ -68,7 +72,7 @@ program
.action(function () {
require('../lib/check-engines.js')()
.done(function () {
console.log('OK')
console.log('OK') // eslint-disable-line no-console
})
})

Expand All @@ -78,7 +82,7 @@ program
.action(function () {
changeDir()
require('../lib/up-to-date.js')().done(function () {
console.log('OK')
console.log('OK') // eslint-disable-line no-console
})
})

Expand All @@ -101,5 +105,6 @@ function changeDir () {

var moduleRoot = path.dirname(packageJson.paths.absolute)
process.chdir(moduleRoot)
// eslint-disable-next-line no-console
console.log("I'm running inside module '" + packageJson.name + "' in '" + moduleRoot)
}
5 changes: 4 additions & 1 deletion examples/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,8 @@ module.exports = {
"plugins": [
"standard",
"promise"
]
],
"rules": {
"no-console": "off"
}
};
99 changes: 60 additions & 39 deletions handlebars/helpers.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
var fs = require('fs')
var path = require('path')
var cp = require('child_process')
var _ = require('lodash')
var debug = require('debug')('thought:helpers')
var glob = require('glob')
var Promise = require('bluebird')
var glob = Promise.promisify(require('glob'))
var findPackage = require('find-package')
var Handlebars = require('handlebars')
var qfs = require('m-io/fs')
Expand Down Expand Up @@ -31,10 +31,10 @@ module.exports = {
include: function (filename, language) {
return qfs.read(filename).then(function (contents) {
return '```' +
(_.isString(language) ? language : path.extname(filename).substr(1)) +
'\n' +
contents +
'\n```\n'
(_.isString(language) ? language : path.extname(filename).substr(1)) +
'\n' +
contents +
'\n```\n'
})
},

Expand Down Expand Up @@ -71,9 +71,9 @@ module.exports = {
.then(function (contents) {
// Relative path to the current module (e.g. "../"). This path must be replaced
// by the module name in the
var modulePath = path.relative(path.dirname(filename), '.') + '/'
var modulePath = path.relative(path.dirname(filename), '.')
debug('example modulepath', modulePath)
var requireModuleRegex = new RegExp(`require\\('${_.escapeRegExp(modulePath)}(.*?)'\\)`, 'm')
var requireModuleRegex = new RegExp(regex`require\('${modulePath}/?(.*?)'\)`, 'g')
if (options && options.hash && options.hash.snippet) {
contents = contents.match(/---<snip>---.*\n([\S\s]*?)\n.*---<\/snip>---/)[1]
}
Expand All @@ -98,8 +98,10 @@ module.exports = {
},

/**
* Execute a commad and include the output in a fenced code-block.
* Execute a command and include the output in a fenced code-block.
*
* @param {string} command the command, passed to `child-process#execSync()`
* @param {object} options optional arguments and Handlebars internal args.
* @param {string} options.hash.lang the language tag that should be attached to the fence
* (like `js` or `bash`). If this is set to `raw`, the output is included as-is, without fences.
* @param {string} options.hash.cwd the current working directory of the example process
Expand Down Expand Up @@ -136,35 +138,53 @@ module.exports = {
* @returns {string} a display of the directory tree of the selected files and directories.
* @api public
*/
dirTree: function (baseDir, globPattern) {
dirTree: function (baseDir, globPattern, options) {
// Is basedir is not a string, it is probably the handlebars "options" object
if (!_.isString(globPattern)) {
globPattern = '**'
}
var defer = Q.defer()
glob(globPattern, {cwd: baseDir}, function (err, files) {
if (err) {
return defer.reject(err)
}
debug('dirTree glob result', files)
files.sort()
// Split paths into components
var components = files.map(function (file) {
return _.compact(file.split(path.sep))

const label = options && options.data && options.data.label
return glob(globPattern, {cwd: baseDir, mark: true})
.then((files) => {
debug('dirTree glob result', files)
if (files.length === 0) {
throw new Error('Cannot find a single file for \'' + globPattern + '\' in \'' + baseDir + '\'')
}
files.sort()
// Split paths into components
const pathComponents = files.map((file) => {
// a/b/c or a/b/dir/
return file.split(path.sep)
// a, b, c or a, b, dir, ''
.map((component, index, all) => component + (index < all.length - 1 ? '/' : ''))
// a/, b/, c or a/, b/, dir/, ''
.filter(component => component) // Filter empty parts
})
const treeObject = treeFromPathComponents(pathComponents, label)
const tree = require('archy')(treeObject)
return '<pre><code>\n' + tree.trim() + '\n</code></pre>'
})
if (components.length === 0) {
defer.reject("Cannot find a single file for '" + globPattern + "' in '" + baseDir + "'")
return
}
var treeObject = treeFromPathComponents(components)
var tree = require('archy')(treeObject)
defer.fulfill('<pre><code>\n' + tree + '</code></pre>')
})
return defer.promise
},

/**
* Render an object hierarchy
* Render an object hierarchy of the form
*
* ```
* {
* prop1: 'value',
* prop2: 'value',
* ...,
* children: [
* {
* prop1: 'value',
* propt2: 'value',
* ...,
* children: ...
* }
* ]
* }
* ```
* @param object
* @param options
* @param {function} options.fn computes the label for a node based on the node itself
Expand All @@ -184,9 +204,7 @@ module.exports = {
* @param options block-helper options
*/
withPackageOf: function (filePath, options) {
if (options.data) {
var data = Handlebars.createFrame(options.data || {})
}
const data = Handlebars.createFrame(options.data)
data.url = githubUrl(filePath)
data.package = findPackage(path.resolve(filePath), false)
return options.fn(this, {data: data})
Expand All @@ -200,7 +218,7 @@ module.exports = {
* Returns the path to the github repository (below github.com) based on the $.repository.url.
* @param options
* @returns {string=} the repository path within github.com (or null)
*/
*/
githubRepo: githubRepo,

/**
Expand Down Expand Up @@ -341,7 +359,7 @@ function treeFromPathComponents (files, label) {
// Condense path if directory only has one entry
if (result.nodes.length === 1 && _.isPlainObject(result.nodes[0])) {
return {
label: (result.label ? result.label + '/' : '') + result.nodes[0].label,
label: (result.label || '') + result.nodes[0].label,
nodes: result.nodes[0].nodes
}
} else {
Expand All @@ -362,17 +380,20 @@ function githubUrl (filePath) {
}

function githubRepo (options) {
var url = null
try {
url = options.data.root.package.repository.url
var url = options.data.root.package.repository.url
var match = url.match(/.*?(:\/\/|@)github\.com[/:](.*?)(#.*?)?$/)
if (match) {
return match[2].replace(/\.git$/, '')
} else {
return null
}
} catch (e) {
console.log('Cannot find repository url')
url = null
// No repositor-url exists
return null
}
}

function regex (strings, ...args) {
return String.raw(strings, ...args.map(_.escapeRegExp))
}
1 change: 1 addition & 0 deletions lib/check-engines.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ module.exports = function () {
throw new Error('npm<2.13.0 will not execute the `version`-script in your package.json.\n' +
'Please upgrade to at least 2.13.0.')
} else {
// eslint-disable-next-line no-console
console.log('npm@' + stdout.trim() + ': OK')
}
})
Expand Down
2 changes: 1 addition & 1 deletion lib/dev-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ var thought = customize().load(require('../customize.js')('.'))
function handleMessage (message) {
switch (message.cmd) {
case 'run': {
// eslint-disable-next-line no-console
console.log('Running thought')
return thought.run()
}
Expand All @@ -16,7 +17,6 @@ process.on('message', (message) => {
.then((result) => {
process.send({ message: message, result: result })
}, (err) => {
console.error('error', err)
process.send({ error: err })
})
})
1 change: 1 addition & 0 deletions lib/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ module.exports = function () {
})
.spread(function (stderr, stdout) {
debug('git commit package.json...', 'stdout', stdout, 'stderr', stderr)
// eslint-disable-next-line no-console
console.log('\nI have committed a new package.json. Please verify the changes made to the file!')
})
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
},
"dependencies": {
"archy": "^1.0.0",
"bluebird": "^3.5.0",
"cheerio": "^0.22.0",
"commander": "^2.8.1",
"customize": "^1.0.0",
Expand All @@ -49,7 +50,6 @@
"trace-and-clarify-if-possible": "^1.0.0"
},
"devDependencies": {
"bluebird": "^3.5.0",
"chai": "^3.2.0",
"chai-as-promised": "^5.1.0",
"customize-engine-handlebars": "^2.0.0-alpha.0",
Expand Down
4 changes: 2 additions & 2 deletions test/dev-server-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ xdescribe('the thought dev-server', function () {
'result': {
'handlebars': {
'CONTRIBUTING.md': fs.readFileSync('test/fixtures/scenarios/simple-project/expected/CONTRIBUTING.md',
{ encoding: 'utf-8'}),
{encoding: 'utf-8'}),
'README.md': fs.readFileSync('test/fixtures/scenarios/simple-project/expected/README.md',
{ encoding: 'utf-8'})
{encoding: 'utf-8'})
}
}
})
Expand Down
Loading

0 comments on commit 5ad6c17

Please sign in to comment.