diff --git a/.eslintrc b/.eslintrc index a45116ed..e3578aad 100644 --- a/.eslintrc +++ b/.eslintrc @@ -1,12 +1,3 @@ { - "extends": "standard", - "rules": { - "brace-style": 0, - "comma-dangle": 0, - "indent": 0, - "operator-linebreak": 0, - "padded-blocks": 0, - "quotes": 0, - "semi": 0 - } + "extends": "standard" } diff --git a/bin/commitizen.js b/bin/commitizen.js index b36087ab..72812371 100644 --- a/bin/commitizen.js +++ b/bin/commitizen.js @@ -1,2 +1,2 @@ -require('../dist/cli/commitizen.js').bootstrap(); +require('../dist/cli/commitizen.js').bootstrap() diff --git a/bin/git-cz.js b/bin/git-cz.js index af58adb8..9aed2470 100644 --- a/bin/git-cz.js +++ b/bin/git-cz.js @@ -1,10 +1,10 @@ -var path = require('path'); +var path = require('path') process.on('uncaughtException', function (err) { - console.error(err.message || err); - process.exit(1); + console.error(err.message || err) + process.exit(1) }) require('../dist/cli/git-cz.js').bootstrap({ cliPath: path.join(__dirname, '../') -}); +}) diff --git a/src/cli/commitizen.js b/src/cli/commitizen.js index ad21b30e..643497a9 100644 --- a/src/cli/commitizen.js +++ b/src/cli/commitizen.js @@ -1,38 +1,37 @@ -import { init } from '../commitizen'; -import { commitizen as commitizenParser } from './parsers'; -import * as sh from 'shelljs'; +import { init } from '../commitizen' +import { commitizen as commitizenParser } from './parsers' +import * as sh from 'shelljs' -let { parse } = commitizenParser; +let { parse } = commitizenParser export { bootstrap -}; +} /** * This is the main cli entry point. * environment may be used for debugging. */ function bootstrap (environment = {}) { - // Get cli args - let rawGitArgs = process.argv.slice(2, process.argv.length); + let rawGitArgs = process.argv.slice(2, process.argv.length) // Parse the args - let parsedArgs = parse(rawGitArgs); - let command = parsedArgs._[0]; + let parsedArgs = parse(rawGitArgs) + let command = parsedArgs._[0] // Do actions based on commands - if (command === "init") { - let adapterNpmName = parsedArgs._[1]; + if (command === 'init') { + let adapterNpmName = parsedArgs._[1] if (adapterNpmName) { - console.log(`Attempting to initialize using the npm package ${adapterNpmName}`); + console.log(`Attempting to initialize using the npm package ${adapterNpmName}`) try { - init(sh, process.cwd(), adapterNpmName, parsedArgs); + init(sh, process.cwd(), adapterNpmName, parsedArgs) } catch (e) { - console.error(`Error: ${e}`); + console.error(`Error: ${e}`) } } else { - console.error('Error: You must provide an adapter name as the second argument.'); + console.error('Error: You must provide an adapter name as the second argument.') } } else { console.log(` @@ -80,7 +79,6 @@ function bootstrap (environment = {}) { note: git-cz may even be run as 'git cz' if installed with -g. - `); + `) } - } diff --git a/src/cli/git-cz.js b/src/cli/git-cz.js index 04851277..0aa236fc 100644 --- a/src/cli/git-cz.js +++ b/src/cli/git-cz.js @@ -1,27 +1,26 @@ -import { configLoader } from '../commitizen'; -import { git as useGitStrategy, gitCz as useGitCzStrategy } from './strategies'; +import { configLoader } from '../commitizen' +import { git as useGitStrategy, gitCz as useGitCzStrategy } from './strategies' export { bootstrap -}; +} /** * This is the main cli entry point. * environment may be used for debugging. */ function bootstrap (environment = {}) { - // Get cli args - let rawGitArgs = process.argv.slice(2, process.argv.length); + let rawGitArgs = process.argv.slice(2, process.argv.length) - let adapterConfig = environment.config || configLoader.load(); + let adapterConfig = environment.config || configLoader.load() // Choose a strategy based on the existance the adapter config if (typeof adapterConfig !== 'undefined') { // This tells commitizen we're in business - useGitCzStrategy(rawGitArgs, environment, adapterConfig); + useGitCzStrategy(rawGitArgs, environment, adapterConfig) } else { // This tells commitizen that it is not needed, just use git - useGitStrategy(rawGitArgs, environment); + useGitStrategy(rawGitArgs, environment) } } diff --git a/src/cli/parsers.js b/src/cli/parsers.js index beb6db64..e20578d0 100644 --- a/src/cli/parsers.js +++ b/src/cli/parsers.js @@ -1,7 +1,7 @@ -import * as commitizen from './parsers/commitizen'; -import * as gitCz from './parsers/git-cz'; +import * as commitizen from './parsers/commitizen' +import * as gitCz from './parsers/git-cz' export { commitizen, gitCz -}; +} diff --git a/src/cli/parsers/commitizen.js b/src/cli/parsers/commitizen.js index 36be5969..43e984fc 100644 --- a/src/cli/parsers/commitizen.js +++ b/src/cli/parsers/commitizen.js @@ -1,8 +1,8 @@ -import minimist from 'minimist'; +import minimist from 'minimist' export { parse -}; +} /** * Takes args, parses with minimist and some ugly vudoo, returns output @@ -10,10 +10,9 @@ export { * TODO: Aww shit this is ugly. Rewrite with mega leet tests plz, kthnx. */ function parse (rawGitArgs) { + var args = minimist(rawGitArgs, { + boolean: true + }) - var args = minimist(rawGitArgs, { - boolean: true - }); - - return args; + return args } diff --git a/src/cli/parsers/git-cz.js b/src/cli/parsers/git-cz.js index 7b60663a..343af97b 100644 --- a/src/cli/parsers/git-cz.js +++ b/src/cli/parsers/git-cz.js @@ -1,51 +1,51 @@ export { parse -}; +} -const reShortMessage = /^-([a-zA-Z]*)m(.*)$/; -const reLongMessage = /^--message(=.*)?$/; +const reShortMessage = /^-([a-zA-Z]*)m(.*)$/ +const reLongMessage = /^--message(=.*)?$/ /** * Strip message declaration from git arguments */ function parse (rawGitArgs) { - let result = []; - let skipNext = false; + let result = [] + let skipNext = false for (const arg of rawGitArgs) { - let match; + let match if (skipNext) { - skipNext = false; - continue; + skipNext = false + continue } - match = reShortMessage.exec(arg); + match = reShortMessage.exec(arg) if (match) { if (match[1]) { - result.push(`-${match[1]}`); + result.push(`-${match[1]}`) } if (!match[2]) { - skipNext = true; + skipNext = true } - continue; + continue } - match = reLongMessage.exec(arg); + match = reLongMessage.exec(arg) if (match) { if (!match[1]) { - skipNext = true; + skipNext = true } - continue; + continue } - result.push(arg); + result.push(arg) } - return result; + return result } diff --git a/src/cli/strategies.js b/src/cli/strategies.js index 3e6752b5..84d692f3 100644 --- a/src/cli/strategies.js +++ b/src/cli/strategies.js @@ -1,7 +1,7 @@ -import git from './strategies/git'; -import gitCz from './strategies/git-cz'; +import git from './strategies/git' +import gitCz from './strategies/git-cz' export { git, gitCz -}; +} diff --git a/src/cli/strategies/git-cz.js b/src/cli/strategies/git-cz.js index f3938eb4..ddc68f9a 100644 --- a/src/cli/strategies/git-cz.js +++ b/src/cli/strategies/git-cz.js @@ -1,57 +1,56 @@ -import sh from 'shelljs'; -import inquirer from 'inquirer'; -import findRoot from 'find-root'; -import { getParsedPackageJsonFromPath } from '../../common/util'; -import { gitCz as gitCzParser, commitizen as commitizenParser } from '../parsers'; -import { commit, staging, adapter } from '../../commitizen'; -import * as gitStrategy from './git'; +import sh from 'shelljs' +import inquirer from 'inquirer' +import findRoot from 'find-root' +import { getParsedPackageJsonFromPath } from '../../common/util' +import { gitCz as gitCzParser, commitizen as commitizenParser } from '../parsers' +import { commit, staging, adapter } from '../../commitizen' +import * as gitStrategy from './git' // destructure for shorter apis -let { parse } = gitCzParser; +let { parse } = gitCzParser -let { getPrompter, resolveAdapterPath } = adapter; -let { isClean } = staging; +let { getPrompter, resolveAdapterPath } = adapter +let { isClean } = staging -export default gitCz; +export default gitCz function gitCz (rawGitArgs, environment, adapterConfig) { - // See if any override conditions exist. // In these very specific scenarios we may want to use a different // commit strategy than git-cz. For example, in the case of --amend - let parsedCommitizenArgs = commitizenParser.parse(rawGitArgs); + let parsedCommitizenArgs = commitizenParser.parse(rawGitArgs) if (parsedCommitizenArgs.amend) { // console.log('override --amend in place'); - gitStrategy.default(rawGitArgs, environment); - return; + gitStrategy.default(rawGitArgs, environment) + return } // Now, if we've made it past overrides, proceed with the git-cz strategy - let parsedGitCzArgs = parse(rawGitArgs); + let parsedGitCzArgs = parse(rawGitArgs) // Determine if we need to process this commit as a retry instead of a // normal commit. - let retryLastCommit = rawGitArgs && rawGitArgs[0] === '--retry'; + let retryLastCommit = rawGitArgs && rawGitArgs[0] === '--retry' - let resolvedAdapterConfigPath = resolveAdapterPath(adapterConfig.path); - let resolvedAdapterRootPath = findRoot(resolvedAdapterConfigPath); - let prompter = getPrompter(adapterConfig.path); + let resolvedAdapterConfigPath = resolveAdapterPath(adapterConfig.path) + let resolvedAdapterRootPath = findRoot(resolvedAdapterConfigPath) + let prompter = getPrompter(adapterConfig.path) isClean(process.cwd(), function (error, stagingIsClean) { if (error) { - throw error; + throw error } if (stagingIsClean && !parsedGitCzArgs.includes('--allow-empty')) { - throw new Error('No files added to staging! Did you forget to run git add?'); + throw new Error('No files added to staging! Did you forget to run git add?') } // OH GOD IM SORRY FOR THIS SECTION - let adapterPackageJson = getParsedPackageJsonFromPath(resolvedAdapterRootPath); - let cliPackageJson = getParsedPackageJsonFromPath(environment.cliPath); - console.log(`cz-cli@${cliPackageJson.version}, ${adapterPackageJson.name}@${adapterPackageJson.version}\n`); + let adapterPackageJson = getParsedPackageJsonFromPath(resolvedAdapterRootPath) + let cliPackageJson = getParsedPackageJsonFromPath(environment.cliPath) + console.log(`cz-cli@${cliPackageJson.version}, ${adapterPackageJson.name}@${adapterPackageJson.version}\n`) commit(sh, inquirer, process.cwd(), prompter, { args: parsedGitCzArgs, disableAppendPaths: true, @@ -60,9 +59,8 @@ function gitCz (rawGitArgs, environment, adapterConfig) { retryLastCommit }, function (error) { if (error) { - throw error; + throw error } - }); - }); - + }) + }) } diff --git a/src/cli/strategies/git.js b/src/cli/strategies/git.js index fff0f167..da10d317 100644 --- a/src/cli/strategies/git.js +++ b/src/cli/strategies/git.js @@ -1,22 +1,22 @@ -import childProcess from 'child_process'; +import childProcess from 'child_process' -export default git; +export default git // We don't have a config, so either we use raw args to try to commit // or if debug is enabled then we do a strict check for a config file. function git (rawGitArgs, environment) { if (environment.debug === true) { - console.error('COMMITIZEN DEBUG: No git-cz friendly config was detected. I looked for .czrc, .cz.json, or czConfig in package.json.'); + console.error('COMMITIZEN DEBUG: No git-cz friendly config was detected. I looked for .czrc, .cz.json, or czConfig in package.json.') } else { - var vanillaGitArgs = ["commit"].concat(rawGitArgs); + var vanillaGitArgs = ['commit'].concat(rawGitArgs) var child = childProcess.spawn('git', vanillaGitArgs, { stdio: 'inherit' - }); + }) child.on('error', function (e, code) { - console.error(e); - throw e; - }); + console.error(e) + throw e + }) } } diff --git a/src/commitizen.js b/src/commitizen.js index 254ce4ba..8d6c77bf 100644 --- a/src/commitizen.js +++ b/src/commitizen.js @@ -1,9 +1,9 @@ -import * as adapter from './commitizen/adapter'; -import * as cache from './commitizen/cache'; -import commit from './commitizen/commit'; -import * as configLoader from './commitizen/configLoader'; -import init from './commitizen/init'; -import * as staging from './commitizen/staging'; +import * as adapter from './commitizen/adapter' +import * as cache from './commitizen/cache' +import commit from './commitizen/commit' +import * as configLoader from './commitizen/configLoader' +import init from './commitizen/init' +import * as staging from './commitizen/staging' export { adapter, @@ -12,4 +12,4 @@ export { configLoader, init, staging -}; +} diff --git a/src/commitizen/adapter.js b/src/commitizen/adapter.js index 68789467..84c162ad 100644 --- a/src/commitizen/adapter.js +++ b/src/commitizen/adapter.js @@ -1,11 +1,11 @@ -import path from 'path'; -import fs from 'fs'; -import findNodeModules from 'find-node-modules'; -import _ from 'lodash'; -import detectIndent from 'detect-indent'; -import sh from 'shelljs'; +import path from 'path' +import fs from 'fs' +import findNodeModules from 'find-node-modules' +import _ from 'lodash' +import detectIndent from 'detect-indent' +import sh from 'shelljs' -import { isFunction } from '../common/util'; +import { isFunction } from '../common/util' export { addPathToAdapterConfig, @@ -16,8 +16,8 @@ export { generateNpmInstallAdapterCommand, resolveAdapterPath, getYarnAddStringMappings, - generateYarnAddAdapterCommand, -}; + generateYarnAddAdapterCommand +} /** * ADAPTER @@ -33,76 +33,72 @@ export { * Must be passed an absolute path to the cli's root */ function addPathToAdapterConfig (sh, cliPath, repoPath, adapterNpmName) { - let commitizenAdapterConfig = { config: { commitizen: { path: `./node_modules/${adapterNpmName}` } } - }; + } - let packageJsonPath = path.join(getNearestProjectRootDirectory(), 'package.json'); - let packageJsonString = fs.readFileSync(packageJsonPath, 'utf-8'); + let packageJsonPath = path.join(getNearestProjectRootDirectory(), 'package.json') + let packageJsonString = fs.readFileSync(packageJsonPath, 'utf-8') // tries to detect the indentation and falls back to a default if it can't - let indent = detectIndent(packageJsonString).indent || ' '; - let packageJsonContent = JSON.parse(packageJsonString); - let newPackageJsonContent = ''; + let indent = detectIndent(packageJsonString).indent || ' ' + let packageJsonContent = JSON.parse(packageJsonString) + let newPackageJsonContent = '' if (_.get(packageJsonContent, 'config.commitizen.path') !== adapterNpmName) { - newPackageJsonContent = _.merge(packageJsonContent, commitizenAdapterConfig); + newPackageJsonContent = _.merge(packageJsonContent, commitizenAdapterConfig) } - fs.writeFileSync(packageJsonPath, JSON.stringify(newPackageJsonContent, null, indent) + '\n'); + fs.writeFileSync(packageJsonPath, JSON.stringify(newPackageJsonContent, null, indent) + '\n') } /** * Generates an npm install command given a map of strings and a package name */ function generateNpmInstallAdapterCommand (stringMappings, adapterNpmName) { - // Start with an initial npm install command - let installAdapterCommand = `npm install ${adapterNpmName}`; + let installAdapterCommand = `npm install ${adapterNpmName}` // Append the neccesary arguments to it based on user preferences for (let value of stringMappings.values()) { if (value) { - installAdapterCommand = installAdapterCommand + ' ' + value; + installAdapterCommand = installAdapterCommand + ' ' + value } } - return installAdapterCommand; + return installAdapterCommand } /** * Generates an yarn add command given a map of strings and a package name */ function generateYarnAddAdapterCommand (stringMappings, adapterNpmName) { - // Start with an initial yarn add command - let installAdapterCommand = `yarn add ${adapterNpmName}`; + let installAdapterCommand = `yarn add ${adapterNpmName}` // Append the necessary arguments to it based on user preferences for (let value of stringMappings.values()) { if (value) { - installAdapterCommand = installAdapterCommand + ' ' + value; + installAdapterCommand = installAdapterCommand + ' ' + value } } - return installAdapterCommand; + return installAdapterCommand } /** * Gets the nearest npm_modules directory */ function getNearestNodeModulesDirectory (options) { - // Get the nearest node_modules directories to the current working directory - let nodeModulesDirectories = findNodeModules(options); + let nodeModulesDirectories = findNodeModules(options) // Make sure we find a node_modules folder /* istanbul ignore else */ if (nodeModulesDirectories && nodeModulesDirectories.length > 0) { - return nodeModulesDirectories[0]; + return nodeModulesDirectories[0] } else { console.error(`Error: Could not locate node_modules in your project's root directory. Did you forget to npm init or npm install?`) } @@ -112,7 +108,7 @@ function getNearestNodeModulesDirectory (options) { * Gets the nearest project root directory */ function getNearestProjectRootDirectory (options) { - return path.join(process.cwd(), getNearestNodeModulesDirectory(options), '/../'); + return path.join(process.cwd(), getNearestNodeModulesDirectory(options), '/../') } /** @@ -123,7 +119,7 @@ function getNpmInstallStringMappings (save, saveDev, saveExact, force) { .set('save', (save && !saveDev) ? '--save' : undefined) .set('saveDev', saveDev ? '--save-dev' : undefined) .set('saveExact', saveExact ? '--save-exact' : undefined) - .set('force', force ? '--force' : undefined); + .set('force', force ? '--force' : undefined) } /** @@ -133,7 +129,7 @@ function getYarnAddStringMappings (dev, exact, force) { return new Map() .set('dev', dev ? '--dev' : undefined) .set('exact', exact ? '--exact' : undefined) - .set('force', force ? '--force' : undefined); + .set('force', force ? '--force' : undefined) } /** @@ -141,18 +137,18 @@ function getYarnAddStringMappings (dev, exact, force) { */ function getPrompter (adapterPath) { // Resolve the adapter path - let resolvedAdapterPath = resolveAdapterPath(adapterPath); + let resolvedAdapterPath = resolveAdapterPath(adapterPath) // Load the adapter - let adapter = require(resolvedAdapterPath); + let adapter = require(resolvedAdapterPath) /* istanbul ignore next */ if (adapter && adapter.prompter && isFunction(adapter.prompter)) { - return adapter.prompter; + return adapter.prompter } else if (adapter && adapter.default && adapter.default.prompter && isFunction(adapter.default.prompter)) { - return adapter.default.prompter; + return adapter.default.prompter } else { - throw new Error(`Could not find prompter method in the provided adapter module: ${adapterPath}`); + throw new Error(`Could not find prompter method in the provided adapter module: ${adapterPath}`) } } @@ -162,23 +158,23 @@ function getPrompter (adapterPath) { */ function resolveAdapterPath (inboundAdapterPath) { // Check if inboundAdapterPath is a path or node module name - let parsed = path.parse(inboundAdapterPath); - let isPath = parsed.dir.length > 0 && parsed.dir.charAt(0) !== "@"; + let parsed = path.parse(inboundAdapterPath) + let isPath = parsed.dir.length > 0 && parsed.dir.charAt(0) !== '@' // Resolve from the root of the git repo if inboundAdapterPath is a path - let absoluteAdapterPath = isPath ? - path.resolve(getGitRootPath(), inboundAdapterPath) : - inboundAdapterPath; + let absoluteAdapterPath = isPath + ? path.resolve(getGitRootPath(), inboundAdapterPath) + : inboundAdapterPath try { // try to resolve the given path - return require.resolve(absoluteAdapterPath); + return require.resolve(absoluteAdapterPath) } catch (error) { - error.message = "Could not resolve " + absoluteAdapterPath + ". " + error.message; - throw error; + error.message = 'Could not resolve ' + absoluteAdapterPath + '. ' + error.message + throw error } } function getGitRootPath () { - return sh.exec('git rev-parse --show-toplevel', { silent: true }).stdout.trim(); + return sh.exec('git rev-parse --show-toplevel', { silent: true }).stdout.trim() } diff --git a/src/commitizen/cache.js b/src/commitizen/cache.js index fa791a41..cb476cf3 100644 --- a/src/commitizen/cache.js +++ b/src/commitizen/cache.js @@ -1,34 +1,34 @@ -import fs from 'fs'; -import _ from 'lodash'; +import fs from 'fs' +import _ from 'lodash' export { getCacheValueSync, readCacheSync, - setCacheValueSync, -}; + setCacheValueSync +} /** * Reads the entire cache */ function readCacheSync (cachePath) { - return JSON.parse(fs.readFileSync(cachePath, 'utf8')); + return JSON.parse(fs.readFileSync(cachePath, 'utf8')) } /** * Sets a cache value and writes the file to disk */ function setCacheValueSync (cachePath, key, value) { - var originalCache; + var originalCache try { - originalCache = readCacheSync(cachePath); + originalCache = readCacheSync(cachePath) } catch (e) { - originalCache = {}; + originalCache = {} } var newCache = _.assign(originalCache, { [key]: value - }); - fs.writeFileSync(cachePath, JSON.stringify(newCache, null, ' ')); - return newCache; + }) + fs.writeFileSync(cachePath, JSON.stringify(newCache, null, ' ')) + return newCache } /** @@ -36,8 +36,8 @@ function setCacheValueSync (cachePath, key, value) { */ function getCacheValueSync (cachePath, repoPath) { try { - let cache = readCacheSync(cachePath); - return cache[repoPath]; + let cache = readCacheSync(cachePath) + return cache[repoPath] } catch (e) { } diff --git a/src/commitizen/commit.js b/src/commitizen/commit.js index 6dac0552..2cffddf4 100644 --- a/src/commitizen/commit.js +++ b/src/commitizen/commit.js @@ -1,37 +1,36 @@ -import path from 'path'; +import path from 'path' -import cacheDir from 'cachedir'; -import { ensureDir } from 'fs-extra'; -import { commit as gitCommit } from '../git'; -import * as cache from './cache'; +import cacheDir from 'cachedir' +import { ensureDir } from 'fs-extra' +import { commit as gitCommit } from '../git' +import * as cache from './cache' -export default commit; +export default commit /** * Takes all of the final inputs needed in order to make dispatch a git commit */ function dispatchGitCommit (sh, repoPath, template, options, overrideOptions, done) { - // Commit the user input -- side effect that we'll test - gitCommit(sh, repoPath, template, { ...options, ...overrideOptions }, function (error) { - done(error, template); - }); + // Commit the user input -- side effect that we'll test + gitCommit(sh, repoPath, template, { ...options, ...overrideOptions }, function (error) { + done(error, template) + }) } - /** +/** * Asynchronously commits files using commitizen */ function commit (sh, inquirer, repoPath, prompter, options, done) { - var cacheDirectory = cacheDir('commitizen'); - var cachePath = path.join(cacheDirectory, 'commitizen.json'); + var cacheDirectory = cacheDir('commitizen') + var cachePath = path.join(cacheDirectory, 'commitizen.json') ensureDir(cacheDirectory, function (error) { if (error) { - console.error("Couldn't create commitizen cache directory: ", error); + console.error("Couldn't create commitizen cache directory: ", error) // TODO: properly handle error? } else { if (options.retryLastCommit) { - - console.log('Retrying last commit attempt.'); + console.log('Retrying last commit attempt.') // We want to use the last commit instead of the current commit, // so lets override some options using the values from cache. @@ -39,30 +38,28 @@ function commit (sh, inquirer, repoPath, prompter, options, done) { options: retryOptions, overrideOptions: retryOverrideOptions, template: retryTemplate - } = cache.getCacheValueSync(cachePath, repoPath); - dispatchGitCommit(sh, repoPath, retryTemplate, retryOptions, retryOverrideOptions, done); - + } = cache.getCacheValueSync(cachePath, repoPath) + dispatchGitCommit(sh, repoPath, retryTemplate, retryOptions, retryOverrideOptions, done) } else { // Get user input -- side effect that is hard to test prompter(inquirer, function (error, template, overrideOptions) { // Allow adapters to error out // (error: Error?, template: String, overrideOptions: Object) if (!(error instanceof Error)) { - overrideOptions = template; - template = error; - error = null; + overrideOptions = template + template = error + error = null } if (error) { - return done(error); + return done(error) } // We don't want to add retries to the cache, only actual commands - cache.setCacheValueSync(cachePath, repoPath, { template, options, overrideOptions }); - dispatchGitCommit(sh, repoPath, template, options, overrideOptions, done); - }); + cache.setCacheValueSync(cachePath, repoPath, { template, options, overrideOptions }) + dispatchGitCommit(sh, repoPath, template, options, overrideOptions, done) + }) } } - }); - + }) } diff --git a/src/commitizen/configLoader.js b/src/commitizen/configLoader.js index 02355d78..f959ad86 100644 --- a/src/commitizen/configLoader.js +++ b/src/commitizen/configLoader.js @@ -1,10 +1,10 @@ -import { loader } from '../configLoader'; +import { loader } from '../configLoader' -export { load }; +export { load } // Configuration sources in priority order. -var configs = ['.czrc', '.cz.json', 'package.json']; +var configs = ['.czrc', '.cz.json', 'package.json'] function load (config, cwd) { - return loader(configs, config, cwd); + return loader(configs, config, cwd) } diff --git a/src/commitizen/init.js b/src/commitizen/init.js index c7f8ecd2..26663784 100644 --- a/src/commitizen/init.js +++ b/src/commitizen/init.js @@ -1,19 +1,19 @@ -import path from 'path'; -import * as configLoader from './configLoader'; -import { executeShellCommand } from '../common/util'; -import * as adapter from './adapter'; +import path from 'path' +import * as configLoader from './configLoader' +import { executeShellCommand } from '../common/util' +import * as adapter from './adapter' let { addPathToAdapterConfig, generateNpmInstallAdapterCommand, getNpmInstallStringMappings, generateYarnAddAdapterCommand, - getYarnAddStringMappings, -} = adapter; + getYarnAddStringMappings +} = adapter -export default init; +export default init -const CLI_PATH = path.normalize(path.join(__dirname, '../../')); +const CLI_PATH = path.normalize(path.join(__dirname, '../../')) /** * CZ INIT @@ -42,8 +42,8 @@ const defaultInitOptions = { // @see https://github.com/commitizen/cz-cli/issues/527#issuecomment-392653897 yarn: false, dev: true, - exact: false, // should add trailing comma, thus next developer doesn't got blamed for this line -}; + exact: false // should add trailing comma, thus next developer doesn't got blamed for this line +} /** * Runs npm install for the adapter then modifies the config.commitizen as needed @@ -55,23 +55,22 @@ function init (sh, repoPath, adapterNpmName, { force = false, yarn = false, dev = false, - exact = false, + exact = false } = defaultInitOptions) { - // Don't let things move forward if required args are missing - checkRequiredArguments(sh, repoPath, adapterNpmName); + checkRequiredArguments(sh, repoPath, adapterNpmName) // Move to the correct directory so we can run commands - sh.cd(repoPath); + sh.cd(repoPath) // Load the current adapter config - let adapterConfig = loadAdapterConfig(); + let adapterConfig = loadAdapterConfig() // Get the npm string mappings based on the arguments provided - let stringMappings = yarn ? getYarnAddStringMappings(dev, exact, force) : getNpmInstallStringMappings(save, saveDev, saveExact, force); + let stringMappings = yarn ? getYarnAddStringMappings(dev, exact, force) : getNpmInstallStringMappings(save, saveDev, saveExact, force) // Generate a string that represents the npm install command - let installAdapterCommand = yarn ? generateYarnAddAdapterCommand(stringMappings, adapterNpmName) : generateNpmInstallAdapterCommand(stringMappings, adapterNpmName); + let installAdapterCommand = yarn ? generateYarnAddAdapterCommand(stringMappings, adapterNpmName) : generateNpmInstallAdapterCommand(stringMappings, adapterNpmName) // Check for previously installed adapters if (adapterConfig && adapterConfig.path && adapterConfig.path.length > 0 && !force) { @@ -81,14 +80,14 @@ function init (sh, repoPath, adapterNpmName, { CLI_PATH: ${CLI_PATH} installAdapterCommand: ${installAdapterCommand} adapterNpmName: ${adapterNpmName} - `); + `) } try { - executeShellCommand(sh, repoPath, installAdapterCommand); - addPathToAdapterConfig(sh, CLI_PATH, repoPath, adapterNpmName); + executeShellCommand(sh, repoPath, installAdapterCommand) + addPathToAdapterConfig(sh, CLI_PATH, repoPath, adapterNpmName) } catch (e) { - console.error(e); + console.error(e) } } @@ -98,13 +97,13 @@ function init (sh, repoPath, adapterNpmName, { */ function checkRequiredArguments (sh, path, adapterNpmName) { if (!sh) { - throw new Error("You must pass an instance of shelljs when running init."); + throw new Error('You must pass an instance of shelljs when running init.') } if (!path) { - throw new Error("Path is required when running init."); + throw new Error('Path is required when running init.') } if (!adapterNpmName) { - throw new Error("The adapter's npm name is required when running init."); + throw new Error("The adapter's npm name is required when running init.") } } @@ -113,9 +112,9 @@ function checkRequiredArguments (sh, path, adapterNpmName) { * Loads and returns the adapter config at key config.commitizen, if it exists */ function loadAdapterConfig () { - let config = configLoader.load(); + let config = configLoader.load() if (config) { - return config; + return config } else { } diff --git a/src/commitizen/staging.js b/src/commitizen/staging.js index 70fc15b5..4be004bb 100644 --- a/src/commitizen/staging.js +++ b/src/commitizen/staging.js @@ -1,6 +1,6 @@ -import { exec } from 'child_process'; +import { exec } from 'child_process' -export { isClean }; +export { isClean } /** * Asynchrounously determines if the staging area is clean @@ -11,9 +11,9 @@ function isClean (repoPath, done) { cwd: repoPath || process.cwd() }, function (error, stdout) { if (error) { - return done(error); + return done(error) } - let output = stdout || ''; - done(null, output.trim().length === 0); - }); + let output = stdout || '' + done(null, output.trim().length === 0) + }) } diff --git a/src/common/util.js b/src/common/util.js index db652bb0..79d7b322 100644 --- a/src/common/util.js +++ b/src/common/util.js @@ -1,5 +1,5 @@ -import fs from 'fs'; -import path from 'path'; +import fs from 'fs' +import path from 'path' export { executeShellCommand, @@ -16,8 +16,8 @@ export { * using the instance of shelljs passed in */ function executeShellCommand (sh, path, installCommand) { - sh.cd(path); - sh.exec(installCommand); + sh.cd(path) + sh.exec(installCommand) } /** @@ -25,10 +25,10 @@ function executeShellCommand (sh, path, installCommand) { */ function getParsedJsonFromFile (filePath, fileName, encoding = 'utf8') { try { - var packageJsonContents = fs.readFileSync(path.join(filePath, fileName), encoding); - return JSON.parse(packageJsonContents); + var packageJsonContents = fs.readFileSync(path.join(filePath, fileName), encoding) + return JSON.parse(packageJsonContents) } catch (e) { - console.error(e); + console.error(e) } } @@ -36,20 +36,19 @@ function getParsedJsonFromFile (filePath, fileName, encoding = 'utf8') { * A helper method for getting the contents of package.json at a given path */ function getParsedPackageJsonFromPath (path) { - return getParsedJsonFromFile(path, 'package.json'); + return getParsedJsonFromFile(path, 'package.json') } /** * Test if the passed argument is an array */ function isArray (arr) { - if (typeof arr === "undefined") - { - return false; + if (typeof arr === 'undefined') { + return false } else if (arr === null) { - return false; + return false } else { - return arr.constructor === Array; + return arr.constructor === Array } } @@ -57,14 +56,13 @@ function isArray (arr) { * Test if the passed argument is a function */ function isFunction (functionToCheck) { - if (typeof functionToCheck === "undefined") - { - return false; + if (typeof functionToCheck === 'undefined') { + return false } else if (functionToCheck === null) { - return false; + return false } else { - var getType = {}; - return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; + var getType = {} + return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]' } } @@ -72,16 +70,15 @@ function isFunction (functionToCheck) { * Test if the passed argument is a string */ function isString (str) { - if (typeof str === "undefined") - { - return false; + if (typeof str === 'undefined') { + return false } else if (str === null) { - return false; + return false } else { - return Object.prototype.toString.call(str) === '[object String]'; + return Object.prototype.toString.call(str) === '[object String]' } } function isInTest () { - return typeof global.it === 'function'; + return typeof global.it === 'function' } diff --git a/src/configLoader.js b/src/configLoader.js index e11d5fe3..1f8f4065 100644 --- a/src/configLoader.js +++ b/src/configLoader.js @@ -1,11 +1,11 @@ -import findup from './configLoader/findup'; -import getContent from './configLoader/getContent'; -import getNormalizedConfig from './configLoader/getNormalizedConfig'; -import loader from './configLoader/loader'; +import findup from './configLoader/findup' +import getContent from './configLoader/getContent' +import getNormalizedConfig from './configLoader/getNormalizedConfig' +import loader from './configLoader/loader' export { findup, getContent, getNormalizedConfig, loader -}; +} diff --git a/src/configLoader/findup.js b/src/configLoader/findup.js index e79a61a2..51435be1 100644 --- a/src/configLoader/findup.js +++ b/src/configLoader/findup.js @@ -1,34 +1,34 @@ -import path from 'path'; -import glob from 'glob'; +import path from 'path' +import glob from 'glob' -export default findup; +export default findup // Before, "findup-sync" package was used, // but it does not provide filter callback function findup (patterns, options, fn) { - /* jshint -W083 */ + /* jshint -W083 */ - var lastpath; - var file; + var lastpath + var file - options = Object.create(options); - options.maxDepth = 1; - options.cwd = path.resolve(options.cwd); + options = Object.create(options) + options.maxDepth = 1 + options.cwd = path.resolve(options.cwd) - do { - file = patterns.filter(function (pattern) { - var configPath = glob.sync(pattern, options)[0]; + do { + file = patterns.filter(function (pattern) { + var configPath = glob.sync(pattern, options)[0] - if (configPath) { - return fn(path.join(options.cwd, configPath)); - } - })[0]; + if (configPath) { + return fn(path.join(options.cwd, configPath)) + } + })[0] - if (file) { - return path.join(options.cwd, file); - } + if (file) { + return path.join(options.cwd, file) + } - lastpath = options.cwd; - options.cwd = path.resolve(options.cwd, '..'); - } while (options.cwd !== lastpath); + lastpath = options.cwd + options.cwd = path.resolve(options.cwd, '..') + } while (options.cwd !== lastpath) } diff --git a/src/configLoader/getContent.js b/src/configLoader/getContent.js index a24cabfe..ea3926a5 100644 --- a/src/configLoader/getContent.js +++ b/src/configLoader/getContent.js @@ -1,11 +1,11 @@ -import fs from 'fs'; -import path from 'path'; +import fs from 'fs' +import path from 'path' -import stripJSONComments from 'strip-json-comments'; +import stripJSONComments from 'strip-json-comments' -import { getNormalizedConfig } from '../configLoader'; +import { getNormalizedConfig } from '../configLoader' -export default getConfigContent; +export default getConfigContent /** * Read the content of a configuration file @@ -15,29 +15,29 @@ export default getConfigContent; * @return {Object} */ function readConfigContent (configPath) { - const parsedPath = path.parse(configPath) - const isRcFile = parsedPath.ext !== '.js' && parsedPath.ext !== '.json'; - const jsonString = fs.readFileSync(configPath, 'utf-8'); - const parse = isRcFile ? - (contents) => JSON.parse(stripJSONComments(contents)) : - (contents) => JSON.parse(contents); - - try { - const parsed = parse(jsonString); - - Object.defineProperty(parsed, 'configPath', { - value: configPath - }); - - return parsed; - } catch (error) { - error.message = [ - `Parsing JSON at ${configPath} for commitizen config failed:`, - error.mesasge - ].join('\n'); - - throw error; - } + const parsedPath = path.parse(configPath) + const isRcFile = parsedPath.ext !== '.js' && parsedPath.ext !== '.json' + const jsonString = fs.readFileSync(configPath, 'utf-8') + const parse = isRcFile + ? (contents) => JSON.parse(stripJSONComments(contents)) + : (contents) => JSON.parse(contents) + + try { + const parsed = parse(jsonString) + + Object.defineProperty(parsed, 'configPath', { + value: configPath + }) + + return parsed + } catch (error) { + error.message = [ + `Parsing JSON at ${configPath} for commitizen config failed:`, + error.mesasge + ].join('\n') + + throw error + } } /** @@ -47,17 +47,17 @@ function readConfigContent (configPath) { * @return {Object} */ function getConfigContent (configPath, baseDirectory) { - if (!configPath) { - return; - } + if (!configPath) { + return + } - const resolvedPath = path.resolve(baseDirectory, configPath); - const configBasename = path.basename(resolvedPath); + const resolvedPath = path.resolve(baseDirectory, configPath) + const configBasename = path.basename(resolvedPath) - if (!fs.existsSync(resolvedPath)) { - return getNormalizedConfig(resolvedPath); - } + if (!fs.existsSync(resolvedPath)) { + return getNormalizedConfig(resolvedPath) + } - const content = readConfigContent(resolvedPath); - return getNormalizedConfig(configBasename, content); + const content = readConfigContent(resolvedPath) + return getNormalizedConfig(configBasename, content) }; diff --git a/src/configLoader/getNormalizedConfig.js b/src/configLoader/getNormalizedConfig.js index e5588146..00f40845 100644 --- a/src/configLoader/getNormalizedConfig.js +++ b/src/configLoader/getNormalizedConfig.js @@ -1,28 +1,25 @@ -export default getNormalizedConfig; +export default getNormalizedConfig // Given a config and content, plucks the actual // settings that we're interested in function getNormalizedConfig (config, content) { - if (content && (config === 'package.json')) { - // PACKAGE.JSON // Use the npm config key, be good citizens if (content.config && content.config.commitizen) { - return content.config.commitizen; - } else if (content.czConfig) { // Old method, will be deprecated in 3.0.0 + return content.config.commitizen + } else if (content.czConfig) { + // Old method, will be deprecated in 3.0.0 // Suppress during test - if (typeof global.it !== 'function') - { - console.error("\n********\nWARNING: This repository's package.json is using czConfig. czConfig will be deprecated in Commitizen 3. \nPlease use this instead:\n{\n \"config\": {\n \"commitizen\": {\n \"path\": \"./path/to/adapter\"\n }\n }\n}\nFor more information, see: http://commitizen.github.io/cz-cli/\n********\n"); + if (typeof global.it !== 'function') { + console.error("\n********\nWARNING: This repository's package.json is using czConfig. czConfig will be deprecated in Commitizen 3. \nPlease use this instead:\n{\n \"config\": {\n \"commitizen\": {\n \"path\": \"./path/to/adapter\"\n }\n }\n}\nFor more information, see: http://commitizen.github.io/cz-cli/\n********\n") } - return content.czConfig; + return content.czConfig } } else { // .cz.json or .czrc - return content; + return content } - } diff --git a/src/configLoader/loader.js b/src/configLoader/loader.js index e4472d8e..aefa7012 100644 --- a/src/configLoader/loader.js +++ b/src/configLoader/loader.js @@ -1,9 +1,9 @@ -import path from 'path'; +import path from 'path' -import { findup, getContent } from '../configLoader'; -import { isInTest } from '../common/util.js'; +import { findup, getContent } from '../configLoader' +import { isInTest } from '../common/util.js' -export default loader; +export default loader /** * Command line config helpers @@ -18,43 +18,43 @@ export default loader; * @return {Object|undefined} */ function loader (configs, config, cwd) { - var content; - var directory = cwd || process.cwd(); - - // If config option is given, attempt to load it - if (config) { - return getContent(config, directory); - } + var content + var directory = cwd || process.cwd() + + // If config option is given, attempt to load it + if (config) { + return getContent(config, directory) + } + + content = getContent( + findup(configs, { nocase: true, cwd: directory }, function (configPath) { + if (path.basename(configPath) === 'package.json') { + // return !!this.getContent(configPath); + } - content = getContent( - findup(configs, { nocase: true, cwd: directory }, function (configPath) { - if (path.basename(configPath) === 'package.json') { - // return !!this.getContent(configPath); - } + return true + }) + ) + + if (content) { + return content + } + /* istanbul ignore if */ + if (!isInTest()) { + // Try to load standard configs from home dir + var directoryArr = [process.env.USERPROFILE, process.env.HOMEPATH, process.env.HOME] + for (var i = 0, dirLen = directoryArr.length; i < dirLen; i++) { + if (!directoryArr[i]) { + continue + } - return true; - }) - ); + for (var j = 0, len = configs.length; j < len; j++) { + content = getContent(configs[j], directoryArr[i]) - if (content) { - return content; - } - /* istanbul ignore if */ - if (!isInTest()) { - // Try to load standard configs from home dir - var directoryArr = [process.env.USERPROFILE, process.env.HOMEPATH, process.env.HOME]; - for (var i = 0, dirLen = directoryArr.length; i < dirLen; i++) { - if (!directoryArr[i]) { - continue; - } - - for (var j = 0, len = configs.length; j < len; j++) { - content = getContent(configs[j], directoryArr[i]); - - if (content) { - return content; - } - } + if (content) { + return content + } } } + } } diff --git a/src/git.js b/src/git.js index 3cd49b50..e8aa9ee0 100644 --- a/src/git.js +++ b/src/git.js @@ -1,8 +1,8 @@ -import { addPath, addFile } from './git/add'; -import { commit } from './git/commit'; -import { init } from './git/init'; -import { log } from './git/log'; -import { whatChanged } from './git/whatChanged'; +import { addPath, addFile } from './git/add' +import { commit } from './git/commit' +import { init } from './git/init' +import { log } from './git/log' +import { whatChanged } from './git/whatChanged' export { addPath, @@ -11,4 +11,4 @@ export { init, log, whatChanged -}; +} diff --git a/src/git/add.js b/src/git/add.js index 09ce9c37..1e39ca21 100644 --- a/src/git/add.js +++ b/src/git/add.js @@ -7,14 +7,14 @@ export { * Synchronously adds a path to git staging */ function addPath (sh, repoPath) { - sh.cd(repoPath); - sh.exec('git add .'); + sh.cd(repoPath) + sh.exec('git add .') } /** * Synchronously adds a file to git staging */ function addFile (sh, repoPath, filename) { - sh.cd(repoPath); + sh.cd(repoPath) sh.exec('git add ' + filename) } diff --git a/src/git/commit.js b/src/git/commit.js index 32cf6d5f..2bc24cc6 100644 --- a/src/git/commit.js +++ b/src/git/commit.js @@ -1,30 +1,30 @@ -import { spawn } from 'child_process'; +import { spawn } from 'child_process' -import dedent from 'dedent'; +import dedent from 'dedent' -export { commit }; +export { commit } /** * Asynchronously git commit at a given path with a message */ function commit (sh, repoPath, message, options, done) { - let called = false; - let args = ['commit', '-m', dedent(message), ...(options.args || [])]; + let called = false + let args = ['commit', '-m', dedent(message), ...(options.args || [])] let child = spawn('git', args, { cwd: repoPath, stdio: options.quiet ? 'ignore' : 'inherit' - }); + }) child.on('error', function (err) { - if (called) return; - called = true; + if (called) return + called = true - done(err); - }); + done(err) + }) child.on('exit', function (code, signal) { - if (called) return; - called = true; + if (called) return + called = true if (code) { if (code === 128) { @@ -35,9 +35,9 @@ function commit (sh, repoPath, message, options, done) { git config --global user.name "Your Name" `) } - done(Object.assign(new Error(`git exited with error code ${code}`), { code, signal })); + done(Object.assign(new Error(`git exited with error code ${code}`), { code, signal })) } else { - done(null); + done(null) } - }); + }) } diff --git a/src/git/init.js b/src/git/init.js index 43b4c1fe..0670af83 100644 --- a/src/git/init.js +++ b/src/git/init.js @@ -1,9 +1,9 @@ -export { init }; +export { init } /** * Synchronously creates a new git repo at a path */ function init (sh, repoPath) { - sh.cd(repoPath); - sh.exec('git init'); + sh.cd(repoPath) + sh.exec('git init') } diff --git a/src/git/log.js b/src/git/log.js index e2add57d..d3bf6f12 100644 --- a/src/git/log.js +++ b/src/git/log.js @@ -1,6 +1,6 @@ -import { exec } from 'child_process'; +import { exec } from 'child_process' -export { log }; +export { log } /** * Asynchronously gets the git log output @@ -11,8 +11,8 @@ function log (repoPath, done) { cwd: repoPath }, function (error, stdout, stderr) { if (error) { - throw error; + throw error } - done(stdout); - }); + done(stdout) + }) } diff --git a/src/git/whatChanged.js b/src/git/whatChanged.js index daad344d..5b455774 100644 --- a/src/git/whatChanged.js +++ b/src/git/whatChanged.js @@ -1,6 +1,6 @@ -import { exec } from 'child_process'; +import { exec } from 'child_process' -export { whatChanged }; +export { whatChanged } /** * Asynchronously gets the git whatchanged output @@ -11,8 +11,8 @@ function whatChanged (repoPath, done) { cwd: repoPath }, function (error, stdout, stderr) { if (error) { - throw error; + throw error } - done(stdout); - }); + done(stdout) + }) } diff --git a/src/index.js b/src/index.js index 9a91d912..a0ae7ac8 100644 --- a/src/index.js +++ b/src/index.js @@ -1,2 +1,2 @@ -var commitizen = require('./commitizen'); -module.exports = commitizen; +var commitizen = require('./commitizen') +module.exports = commitizen diff --git a/test/config.js b/test/config.js index d46c69f2..25209713 100644 --- a/test/config.js +++ b/test/config.js @@ -1,4 +1,4 @@ -import path from 'path'; +import path from 'path' /** * Modify the testConfig to your liking @@ -60,6 +60,6 @@ let config = { * it. Use at your own risk. */ preserve: 1 -}; +} -export { config }; +export { config } diff --git a/test/tester.js b/test/tester.js index e8f50a3f..c696727f 100644 --- a/test/tester.js +++ b/test/tester.js @@ -1,18 +1,17 @@ -import * as repo from './tools/repo'; -import * as clean from './tools/clean'; -import * as files from './tools/files'; -import * as util from '../src/common/util'; -import { config as userConfig } from './config'; -import * as sh from 'shelljs'; // local instance -import _ from 'lodash'; +import * as repo from './tools/repo' +import * as clean from './tools/clean' +import * as files from './tools/files' +import * as util from '../src/common/util' +import { config as userConfig } from './config' +import * as sh from 'shelljs' // local instance +import _ from 'lodash' // Clone the user's config so we don't get caught w/our pants down -let patchedConfig = _.cloneDeep(userConfig); +let patchedConfig = _.cloneDeep(userConfig) function bootstrap () { - // Patch any shelljs specific config settings - sh.config.silent = patchedConfig.silent || true; + sh.config.silent = patchedConfig.silent || true // Return the patched config and shelljs instance return { @@ -27,4 +26,4 @@ function bootstrap () { export { bootstrap -}; +} diff --git a/test/tests/adapter.js b/test/tests/adapter.js index c716a532..87bc7aad 100644 --- a/test/tests/adapter.js +++ b/test/tests/adapter.js @@ -1,37 +1,35 @@ /* eslint-env mocha */ /* eslint-disable no-unused-expressions */ -import { expect } from 'chai'; -import path from 'path'; +import { expect } from 'chai' +import path from 'path' // TODO: augment these tests with tests using the actual cli call // For now we're just using the library, which is probably fine // in the short term -import { adapter, init as commitizenInit } from '../../src/commitizen'; +import { adapter, init as commitizenInit } from '../../src/commitizen' -import { isFunction } from '../../src/common/util'; +import { isFunction } from '../../src/common/util' // Bootstrap our tester -import { bootstrap } from '../tester'; +import { bootstrap } from '../tester' // Destructure some things based on the bootstrap process -let { config, sh, repo, clean } = bootstrap(); +let { config, sh, repo, clean } = bootstrap() before(function () { // Creates the temp path - clean.before(sh, config.paths.tmp); -}); + clean.before(sh, config.paths.tmp) +}) beforeEach(function () { - this.timeout(config.maxTimeout); // this could take a while - repo.createEndUser(sh, config.paths.endUserRepo); -}); + this.timeout(config.maxTimeout) // this could take a while + repo.createEndUser(sh, config.paths.endUserRepo) +}) describe('adapter', function () { - it('resolves adapter paths', function () { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP @@ -40,39 +38,38 @@ describe('adapter', function () { path: config.paths.endUserRepo, files: { dummyfile: { - contents: `duck-duck-goose`, - filename: `mydummyfile.txt`, + contents: `duck-duck-goose`, + filename: `mydummyfile.txt` }, gitignore: { contents: `node_modules/`, filename: `.gitignore` } } - }; + } // Describe an adapter let adapterConfig = { path: path.join(repoConfig.path, '/node_modules/cz-conventional-changelog'), npmName: 'cz-conventional-changelog' - }; + } // Install an adapter - commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog'); + commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog') // TEST - expect(function () { adapter.resolveAdapterPath('IAMANIMPOSSIBLEPATH'); }).to.throw(Error); - expect(function () { adapter.resolveAdapterPath(adapterConfig.path); }).not.to.throw(Error); - expect(function () { adapter.resolveAdapterPath(path.join(adapterConfig.path, 'index.js')); }).not.to.throw(Error); + expect(function () { adapter.resolveAdapterPath('IAMANIMPOSSIBLEPATH') }).to.throw(Error) + expect(function () { adapter.resolveAdapterPath(adapterConfig.path) }).not.to.throw(Error) + expect(function () { adapter.resolveAdapterPath(path.join(adapterConfig.path, 'index.js')) }).not.to.throw(Error) // This line is only here to make sure that cz-conventional-changelog // was installed for the purposes of running tests, it is not needed // for testing any other adapters. - expect(function () { adapter.resolveAdapterPath('cz-conventional-changelog'); }).not.to.throw(Error); - }); + expect(function () { adapter.resolveAdapterPath('cz-conventional-changelog') }).not.to.throw(Error) + }) it('resolves scoped adapter paths', function () { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP @@ -81,34 +78,33 @@ describe('adapter', function () { path: config.paths.endUserRepo, files: { dummyfile: { - contents: `duck-duck-goose`, - filename: `mydummyfile.txt`, + contents: `duck-duck-goose`, + filename: `mydummyfile.txt` }, gitignore: { contents: `node_modules/`, filename: `.gitignore` } } - }; + } // Describe an adapter let adapterConfig = { path: path.join(repoConfig.path, '/node_modules/@commitizen/cz-conventional-changelog'), npmName: '@commitizen/cz-conventional-changelog' - }; + } // Install an adapter - commitizenInit(sh, config.paths.endUserRepo, '@commitizen/cz-conventional-changelog'); + commitizenInit(sh, config.paths.endUserRepo, '@commitizen/cz-conventional-changelog') // TEST - expect(function () { adapter.resolveAdapterPath('IAMANIMPOSSIBLEPATH'); }).to.throw(Error); - expect(function () { adapter.resolveAdapterPath(adapterConfig.path); }).not.to.throw(Error); - expect(function () { adapter.resolveAdapterPath(path.join(adapterConfig.path, 'index.js')); }).not.to.throw(Error); - }); + expect(function () { adapter.resolveAdapterPath('IAMANIMPOSSIBLEPATH') }).to.throw(Error) + expect(function () { adapter.resolveAdapterPath(adapterConfig.path) }).not.to.throw(Error) + expect(function () { adapter.resolveAdapterPath(path.join(adapterConfig.path, 'index.js')) }).not.to.throw(Error) + }) it('gets adapter prompter functions', function () { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP @@ -117,34 +113,33 @@ describe('adapter', function () { path: config.paths.endUserRepo, files: { dummyfile: { - contents: `duck-duck-goose`, - filename: `mydummyfile.txt`, + contents: `duck-duck-goose`, + filename: `mydummyfile.txt` }, gitignore: { contents: `node_modules/`, filename: `.gitignore` } } - }; + } // Describe an adapter let adapterConfig = { path: path.join(repoConfig.path, '/node_modules/cz-conventional-changelog'), npmName: 'cz-conventional-changelog' - }; + } // Install an adapter - commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog'); + commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog') // TEST - expect(function () { adapter.getPrompter('IAMANIMPOSSIBLEPATH'); }).to.throw(Error); - expect(function () { adapter.getPrompter(adapterConfig.path); }).not.to.throw(Error); - expect(isFunction(adapter.getPrompter(adapterConfig.path))).to.be.true; - }); + expect(function () { adapter.getPrompter('IAMANIMPOSSIBLEPATH') }).to.throw(Error) + expect(function () { adapter.getPrompter(adapterConfig.path) }).not.to.throw(Error) + expect(isFunction(adapter.getPrompter(adapterConfig.path))).to.be.true + }) it('gets adapter prompter functions for default export adapters', function () { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP @@ -153,42 +148,41 @@ describe('adapter', function () { path: config.paths.endUserRepo, files: { dummyfile: { - contents: `duck-duck-goose`, - filename: `mydummyfile.txt`, + contents: `duck-duck-goose`, + filename: `mydummyfile.txt` }, gitignore: { contents: `node_modules/`, filename: `.gitignore` } } - }; + } // Describe an adapter let adapterConfig = { path: path.join(repoConfig.path, '/node_modules/cz-conventional-changelog-default-export'), npmName: 'cz-conventional-changelog-default-export' - }; + } // Install an adapter - commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog-default-export'); + commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog-default-export') // TEST - expect(function () { adapter.getPrompter('IAMANIMPOSSIBLEPATH'); }).to.throw(Error); - expect(function () { adapter.getPrompter(adapterConfig.path); }).not.to.throw(Error); - expect(isFunction(adapter.getPrompter(adapterConfig.path))).to.be.true; - }); - -}); + expect(function () { adapter.getPrompter('IAMANIMPOSSIBLEPATH') }).to.throw(Error) + expect(function () { adapter.getPrompter(adapterConfig.path) }).not.to.throw(Error) + expect(isFunction(adapter.getPrompter(adapterConfig.path))).to.be.true + }) +}) afterEach(function () { - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // All this should do is archive the tmp path to the artifacts - clean.afterEach(sh, config.paths.tmp, config.preserve); -}); + clean.afterEach(sh, config.paths.tmp, config.preserve) +}) after(function () { - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // Once everything is done, the artifacts should be cleaned up based on // the preserve setting in the config - clean.after(sh, config.paths.tmp, config.preserve); -}); + clean.after(sh, config.paths.tmp, config.preserve) +}) diff --git a/test/tests/cli.js b/test/tests/cli.js index dbb65bf9..5f8bc17e 100644 --- a/test/tests/cli.js +++ b/test/tests/cli.js @@ -1,12 +1,12 @@ /* eslint-env mocha */ -import { expect } from 'chai'; -import proxyquire from 'proxyquire'; -import sinon from 'sinon'; +import { expect } from 'chai' +import proxyquire from 'proxyquire' +import sinon from 'sinon' describe('git-cz', () => { - let bootstrap; - let fakeStrategies, fakeCommitizen; + let bootstrap + let fakeStrategies, fakeCommitizen beforeEach(() => { fakeStrategies = { @@ -23,39 +23,38 @@ describe('git-cz', () => { bootstrap = proxyquire('../../src/cli/git-cz', { './strategies': fakeStrategies, '../commitizen': fakeCommitizen - }).bootstrap; - }); + }).bootstrap + }) describe('bootstrap', () => { describe('when config is provided', () => { it('passes config to useGitCzStrategy', () => { - const config = sinon.spy(); + const config = sinon.spy() - bootstrap({ config }); + bootstrap({ config }) - expect(fakeStrategies.gitCz.args[0][2]).to.equal(config); - }); - }); + expect(fakeStrategies.gitCz.args[0][2]).to.equal(config) + }) + }) describe('when config is not provided', () => { - describe('and the config is returned from configLoader.load', () => { it('uses config from configLoader.load()', () => { - const config = sinon.stub(); - fakeCommitizen.configLoader.load.returns(config); + const config = sinon.stub() + fakeCommitizen.configLoader.load.returns(config) - bootstrap({}); + bootstrap({}) - expect(fakeStrategies.gitCz.args[0][2]).to.equal(config); - }); - }); + expect(fakeStrategies.gitCz.args[0][2]).to.equal(config) + }) + }) describe('and the config is not returned from configLoader.load', () => { it('tells commitizen to use the git strategy', () => { - bootstrap({}); - expect(fakeStrategies.git.called).to.equal(true); - }); - }); - }); - }); -}); + bootstrap({}) + expect(fakeStrategies.git.called).to.equal(true) + }) + }) + }) + }) +}) diff --git a/test/tests/commit.js b/test/tests/commit.js index 4f5adf04..2f636ac1 100644 --- a/test/tests/commit.js +++ b/test/tests/commit.js @@ -1,126 +1,120 @@ /* eslint-env mocha */ -import { expect } from 'chai'; -import os from 'os'; -import path from 'path'; +import { expect } from 'chai' +import os from 'os' +import path from 'path' -import inquirer from 'inquirer'; +import inquirer from 'inquirer' // Bootstrap our tester -import { bootstrap } from '../tester'; +import { bootstrap } from '../tester' // Get our source files -import { addFile as gitAddFile, init as gitInit, log, whatChanged } from '../../src/git'; -import { commit as commitizenCommit, init as commitizenInit } from '../../src/commitizen'; +import { addFile as gitAddFile, init as gitInit, log, whatChanged } from '../../src/git' +import { commit as commitizenCommit, init as commitizenInit } from '../../src/commitizen' // Destructure some things for cleaner tests -let { config, sh, repo, clean, files } = bootstrap(); -let { writeFilesToPath } = files; +let { config, sh, repo, clean, files } = bootstrap() +let { writeFilesToPath } = files before(function () { // Creates the temp path - clean.before(sh, config.paths.tmp); -}); + clean.before(sh, config.paths.tmp) +}) beforeEach(function () { - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while /* istanbul ignore next */ - repo.createEndUser(sh, config.paths.endUserRepo); -}); + repo.createEndUser(sh, config.paths.endUserRepo) +}) describe('commit', function () { - it('should commit simple messages', function (done) { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP - let dummyCommitMessage = `sip sip sippin on some sizzurp`; + let dummyCommitMessage = `sip sip sippin on some sizzurp` // Describe a repo and some files to add and commit let repoConfig = { path: config.paths.endUserRepo, files: { dummyfile: { - contents: `duck-duck-goose`, - filename: `mydummyfile.txt`, + contents: `duck-duck-goose`, + filename: `mydummyfile.txt` }, gitignore: { contents: `node_modules/`, filename: `.gitignore` } } - }; + } // Describe an adapter let adapterConfig = { path: path.join(repoConfig.path, '/node_modules/cz-jira-smart-commit'), npmName: 'cz-jira-smart-commit' - }; + } // Quick setup the repos, adapter, and grab a simple prompter - let prompter = quickPrompterSetup(sh, repoConfig, adapterConfig, dummyCommitMessage); + let prompter = quickPrompterSetup(sh, repoConfig, adapterConfig, dummyCommitMessage) // TEST // Pass in inquirer but it never gets used since we've mocked out a different // version of prompter. commitizenCommit(sh, inquirer, repoConfig.path, prompter, { disableAppendPaths: true, quiet: true, emitData: true }, function () { log(repoConfig.path, function (logOutput) { - expect(logOutput).to.have.string(dummyCommitMessage); - done(); - }); - }); - - }); + expect(logOutput).to.have.string(dummyCommitMessage) + done() + }) + }) + }) it('should commit message with quotes', function (done) { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP - let dummyCommitMessage = `sip \`sip\` sippin' on some "sizzurp"`; + let dummyCommitMessage = `sip \`sip\` sippin' on some "sizzurp"` // Describe a repo and some files to add and commit let repoConfig = { path: config.paths.endUserRepo, files: { dummyfile: { - contents: `duck-duck-goose`, - filename: `mydummyfile.txt`, + contents: `duck-duck-goose`, + filename: `mydummyfile.txt` }, gitignore: { contents: `node_modules/`, filename: `.gitignore` } } - }; + } // Describe an adapter let adapterConfig = { path: path.join(repoConfig.path, '/node_modules/cz-jira-smart-commit'), npmName: 'cz-jira-smart-commit' - }; + } // Quick setup the repos, adapter, and grab a simple prompter - let prompter = quickPrompterSetup(sh, repoConfig, adapterConfig, dummyCommitMessage); + let prompter = quickPrompterSetup(sh, repoConfig, adapterConfig, dummyCommitMessage) // TEST // Pass in inquirer but it never gets used since we've mocked out a different // version of prompter. commitizenCommit(sh, inquirer, repoConfig.path, prompter, { disableAppendPaths: true, quiet: true, emitData: true }, function () { log(repoConfig.path, function (logOutput) { - expect(logOutput).to.have.string(dummyCommitMessage); - done(); - }); - }); - - }); + expect(logOutput).to.have.string(dummyCommitMessage) + done() + }) + }) + }) it('should commit multiline messages', function (done) { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP @@ -129,195 +123,188 @@ describe('commit', function () { let dummyCommitMessage = `sip sip sippin on jnkjnkjn ${(os.platform === 'win32') ? '' : ' '} - some sizzurp`; + some sizzurp` // Describe a repo and some files to add and commit let repoConfig = { path: config.paths.endUserRepo, files: { dummyfile: { - contents: `duck-duck-goose`, - filename: `mydummyfile.txt`, + contents: `duck-duck-goose`, + filename: `mydummyfile.txt` }, gitignore: { contents: `node_modules/`, filename: `.gitignore` } } - }; + } // Describe an adapter let adapterConfig = { path: path.join(repoConfig.path, '/node_modules/cz-conventional-changelog'), npmName: 'cz-conventional-changelog' - }; + } // Quick setup the repos, adapter, and grab a simple prompter - let prompter = quickPrompterSetup(sh, repoConfig, adapterConfig, dummyCommitMessage); + let prompter = quickPrompterSetup(sh, repoConfig, adapterConfig, dummyCommitMessage) // TEST // Pass in inquirer but it never gets used since we've mocked out a different // version of prompter. commitizenCommit(sh, inquirer, repoConfig.path, prompter, { disableAppendPaths: true, quiet: true }, function () { log(repoConfig.path, function (logOutput) { - expect(logOutput).to.have.string(dummyCommitMessage); - done(); - }); - }); - - }); + expect(logOutput).to.have.string(dummyCommitMessage) + done() + }) + }) + }) it('should allow to override git commit options', function (done) { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP - let dummyCommitMessage = `sip sip sippin on some sizzurp`; - let author = `A U Thor `; + let dummyCommitMessage = `sip sip sippin on some sizzurp` + let author = `A U Thor ` // Describe a repo and some files to add and commit let repoConfig = { path: config.paths.endUserRepo, files: { dummyfile: { - contents: `duck-duck-goose`, - filename: `mydummyfile.txt`, + contents: `duck-duck-goose`, + filename: `mydummyfile.txt` }, gitignore: { contents: `node_modules/`, filename: `.gitignore` } } - }; + } // Describe an adapter let adapterConfig = { path: path.join(repoConfig.path, '/node_modules/cz-jira-smart-commit'), npmName: 'cz-jira-smart-commit' - }; + } let options = { args: [`--author="${author}"`, '--no-edit'] - }; + } // Quick setup the repos, adapter, and grab a simple prompter - let prompter = quickPrompterSetup(sh, repoConfig, adapterConfig, dummyCommitMessage, options); + let prompter = quickPrompterSetup(sh, repoConfig, adapterConfig, dummyCommitMessage, options) // TEST // Pass in inquirer but it never gets used since we've mocked out a different // version of prompter. commitizenCommit(sh, inquirer, repoConfig.path, prompter, { disableAppendPaths: true, quiet: true, emitData: true }, function () { log(repoConfig.path, function (logOutput) { - expect(logOutput).to.have.string(author); - expect(logOutput).to.have.string(dummyCommitMessage); - done(); - }); - }); - - }); + expect(logOutput).to.have.string(author) + expect(logOutput).to.have.string(dummyCommitMessage) + done() + }) + }) + }) it('should respect original behavior of -a option', function (done) { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP - let dummyCommitMessage = `sip sip sippin on some sizzurp`; + let dummyCommitMessage = `sip sip sippin on some sizzurp` // Describe a repo and some files to add and commit let repoConfig = { path: config.paths.endUserRepo, files: { dummyfile: { - contents: `duck-duck-goose`, - filename: `mydummyfile.txt`, + contents: `duck-duck-goose`, + filename: `mydummyfile.txt` }, dummyfilecopy: { contents: `duck-duck-goose`, filename: `mydummyfilecopy.txt`, - add: false, + add: false }, gitignore: { contents: `node_modules/`, filename: `.gitignore` } } - }; + } // Describe an adapter let adapterConfig = { path: path.join(repoConfig.path, '/node_modules/cz-jira-smart-commit'), npmName: 'cz-jira-smart-commit' - }; + } let options = { args: ['-a'] - }; + } // Quick setup the repos, adapter, and grab a simple prompter - let prompter = quickPrompterSetup(sh, repoConfig, adapterConfig, dummyCommitMessage, options); + let prompter = quickPrompterSetup(sh, repoConfig, adapterConfig, dummyCommitMessage, options) // TEST // Pass in inquirer but it never gets used since we've mocked out a different // version of prompter. commitizenCommit(sh, inquirer, repoConfig.path, prompter, { disableAppendPaths: true, quiet: true, emitData: true }, function () { log(repoConfig.path, function (logOutput) { - expect(logOutput).to.have.string(dummyCommitMessage); - }); + expect(logOutput).to.have.string(dummyCommitMessage) + }) whatChanged(repoConfig.path, function (whatChangedOutput) { - expect(whatChangedOutput).to.have.string('A\t' + repoConfig.files.dummyfile.filename); - expect(whatChangedOutput).to.not.have.string('A\t' + repoConfig.files.dummyfilecopy.filename); - done(); - }); - }); - - }); - -}); + expect(whatChangedOutput).to.have.string('A\t' + repoConfig.files.dummyfile.filename) + expect(whatChangedOutput).to.not.have.string('A\t' + repoConfig.files.dummyfilecopy.filename) + done() + }) + }) + }) +}) afterEach(function () { - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // All this should do is archive the tmp path to the artifacts - clean.afterEach(sh, config.paths.tmp, config.preserve); -}); + clean.afterEach(sh, config.paths.tmp, config.preserve) +}) after(function () { - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // Once everything is done, the artifacts should be cleaned up based on // the preserve setting in the config - clean.after(sh, config.paths.tmp, config.preserve); -}); + clean.after(sh, config.paths.tmp, config.preserve) +}) /** * This is just a helper for testing. NOTE that prompter * prompter is overriden for testing purposes. */ function quickPrompterSetup (sh, repoConfig, adapterConfig, commitMessage, options = {}) { - - commitizenInit(sh, repoConfig.path, adapterConfig.npmName); + commitizenInit(sh, repoConfig.path, adapterConfig.npmName) // NOTE: // In our real code we'd use this here but since we're testing, // we'll provide prompter. We'd normally use: // let prompter = getPrompter(adapterConfig.path); let prompter = function (cz, commit) { - commit(commitMessage, options); + commit(commitMessage, options) } - gitInit(sh, repoConfig.path); + gitInit(sh, repoConfig.path) - writeFilesToPath(repoConfig.files, repoConfig.path); + writeFilesToPath(repoConfig.files, repoConfig.path) for (let key in repoConfig.files) { - let file = repoConfig.files[key]; + let file = repoConfig.files[key] if (file.add !== false) { - gitAddFile(sh, repoConfig.path, file.filename); + gitAddFile(sh, repoConfig.path, file.filename) } } // NOTE: In the real world we would not be returning // this we would instead be just making the commented // out getPrompter() call to get user input (above). - return prompter; + return prompter } diff --git a/test/tests/configLoader.js b/test/tests/configLoader.js index 0a33e684..57bdef45 100644 --- a/test/tests/configLoader.js +++ b/test/tests/configLoader.js @@ -1,66 +1,58 @@ /* eslint-env mocha */ -import path from 'path'; -import { expect } from 'chai'; -import { getContent, getNormalizedConfig } from '../../src/configLoader'; +import path from 'path' +import { expect } from 'chai' +import { getContent, getNormalizedConfig } from '../../src/configLoader' -const fixturesPath = path.resolve(__dirname, '..', 'fixtures'); +const fixturesPath = path.resolve(__dirname, '..', 'fixtures') describe('configLoader', function () { - it('errors appropriately for invalid json', function () { expect(() => getContent('invalid-json.json', fixturesPath)) - .to.throw(/parsing json at/i); + .to.throw(/parsing json at/i) expect(() => getContent('invalid-json-rc', fixturesPath)) - .to.throw(/parsing json at/i); - }); + .to.throw(/parsing json at/i) + }) it('parses json files with comments', function () { expect(getContent('valid-json-rc', fixturesPath)) - .to.deep.equal({ 'some': 'json' }); - }); + .to.deep.equal({ 'some': 'json' }) + }) it('normalizes package.json configs', function () { - - let config = 'package.json'; + let config = 'package.json' let npmStyleConfig = { config: { commitizen: 'myNpmConfig' } - }; + } let oldStyleConfig = { czConfig: 'myOldConfig' - }; + } - expect(getNormalizedConfig(config, npmStyleConfig)).to.equal('myNpmConfig'); - expect(getNormalizedConfig(config, oldStyleConfig)).to.equal('myOldConfig'); - - }); + expect(getNormalizedConfig(config, npmStyleConfig)).to.equal('myNpmConfig') + expect(getNormalizedConfig(config, oldStyleConfig)).to.equal('myOldConfig') + }) it('normalizes .cz.json configs', function () { - - let config = '.cz.json'; + let config = '.cz.json' let czJsonStyleConfig = { path: './path/to/adapter' - }; + } - expect(getNormalizedConfig(config, czJsonStyleConfig)).to.deep.equal({ path: './path/to/adapter' }); - - }); + expect(getNormalizedConfig(config, czJsonStyleConfig)).to.deep.equal({ path: './path/to/adapter' }) + }) it('normalizes .czrc configs', function () { - - let config = '.czrc'; + let config = '.czrc' let czrcStyleConfig = { path: './path/to/adapter' - }; - - expect(getNormalizedConfig(config, czrcStyleConfig)).to.deep.equal({ path: './path/to/adapter' }); - - }); + } -}); + expect(getNormalizedConfig(config, czrcStyleConfig)).to.deep.equal({ path: './path/to/adapter' }) + }) +}) diff --git a/test/tests/index.js b/test/tests/index.js index 146478c4..d4364ec9 100644 --- a/test/tests/index.js +++ b/test/tests/index.js @@ -1,8 +1,8 @@ -import './adapter'; -import './cli'; -import './commit'; -import './configLoader'; -import './init'; -import './parsers'; -import './staging'; -import './util'; +import './adapter' +import './cli' +import './commit' +import './configLoader' +import './init' +import './parsers' +import './staging' +import './util' diff --git a/test/tests/init.js b/test/tests/init.js index 1e7269f9..b4211b31 100644 --- a/test/tests/init.js +++ b/test/tests/init.js @@ -1,304 +1,280 @@ /* eslint-env mocha */ -import { expect } from 'chai'; -import semver from 'semver'; +import { expect } from 'chai' +import semver from 'semver' // TODO: augment these tests with tests using the actual cli call // For now we're just using the library, which is probably fine // in the short term -import { init as commitizenInit } from '../../src/commitizen'; +import { init as commitizenInit } from '../../src/commitizen' // Bootstrap our tester -import { bootstrap } from '../tester'; +import { bootstrap } from '../tester' // Destructure some things based on the bootstrap process -let { config, sh, repo, clean, util } = bootstrap(); +let { config, sh, repo, clean, util } = bootstrap() before(function () { // Creates the temp path - clean.before(sh, config.paths.tmp); -}); + clean.before(sh, config.paths.tmp) +}) beforeEach(function () { - this.timeout(config.maxTimeout); // this could take a while - repo.createEndUser(sh, config.paths.endUserRepo); -}); + this.timeout(config.maxTimeout) // this could take a while + repo.createEndUser(sh, config.paths.endUserRepo) +}) describe('init', function () { - it('installs an adapter with --save-dev', function () { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP // Install an adapter - commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog'); + commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog') // TEST // Check resulting json - let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo); - expect(packageJson).to.have.nested.property('devDependencies.cz-conventional-changelog'); - - }); + let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo) + expect(packageJson).to.have.nested.property('devDependencies.cz-conventional-changelog') + }) it('installs an adapter with --save', function () { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP // Install an adapter - commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { save: true, saveDev: false }); + commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { save: true, saveDev: false }) // TEST // Check resulting json - let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo); - expect(packageJson).to.have.nested.property('dependencies.cz-conventional-changelog'); - - }); + let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo) + expect(packageJson).to.have.nested.property('dependencies.cz-conventional-changelog') + }) it('errors on previously installed adapter', function () { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP // Add a first adapter - sh.cd(config.paths.endUserRepo); - commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { saveDev: true }); + sh.cd(config.paths.endUserRepo) + commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { saveDev: true }) // TEST - sh.cd(config.paths.endUserRepo); + sh.cd(config.paths.endUserRepo) // Adding a second adapter expect(function () { - commitizenInit(sh, config.paths.endUserRepo, 'cz-jira-smart-commit', { saveDev: true }); - }).to.throw(/already configured/); + commitizenInit(sh, config.paths.endUserRepo, 'cz-jira-smart-commit', { saveDev: true }) + }).to.throw(/already configured/) // Check resulting json - let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo); - expect(packageJson).not.to.have.nested.property('devDependencies', 'cz-jira-smart-commit'); - expect(packageJson).to.have.nested.property('config.commitizen.path', './node_modules/cz-conventional-changelog'); + let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo) + expect(packageJson).not.to.have.nested.property('devDependencies', 'cz-jira-smart-commit') + expect(packageJson).to.have.nested.property('config.commitizen.path', './node_modules/cz-conventional-changelog') // TODO: Eventually may need to offer both path and package keys. package = npm package name // Path for local development - }); + }) it('succeeds if force is true', function () { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP // Add a first adapter - sh.cd(config.paths.endUserRepo); - commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { saveDev: true }); + sh.cd(config.paths.endUserRepo) + commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { saveDev: true }) // TEST // Adding a second adapter expect(function () { - commitizenInit(sh, config.paths.endUserRepo, 'cz-jira-smart-commit', { saveDev: true, force: true }); - }).to.not.throw(); - - let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo); - expect(packageJson.devDependencies).to.have.property('cz-jira-smart-commit'); - expect(packageJson).to.have.nested.property('config.commitizen.path', './node_modules/cz-jira-smart-commit'); + commitizenInit(sh, config.paths.endUserRepo, 'cz-jira-smart-commit', { saveDev: true, force: true }) + }).to.not.throw() - }); + let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo) + expect(packageJson.devDependencies).to.have.property('cz-jira-smart-commit') + expect(packageJson).to.have.nested.property('config.commitizen.path', './node_modules/cz-jira-smart-commit') + }) it('installs an adapter without --save-exact', function () { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP // Add a first adapter - sh.cd(config.paths.endUserRepo); - commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog'); - let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo); + sh.cd(config.paths.endUserRepo) + commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog') + let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo) // TEST - expect(packageJson.devDependencies).to.have.property('cz-conventional-changelog'); - let range = packageJson.devDependencies['cz-conventional-changelog']; + expect(packageJson.devDependencies).to.have.property('cz-conventional-changelog') + let range = packageJson.devDependencies['cz-conventional-changelog'] // It should satisfy the requirements of a range - expect(semver.validRange(range)).to.not.equal(null); + expect(semver.validRange(range)).to.not.equal(null) // // But you CAN NOT increment a range // expect(semver.inc(range, 'major')).to.equal(null); // TODO: We need to figure out how to check if the repo has save exact set // in the config before we can re-enable this. The --save-exact setting // in our package.json breaks this test - - }); + }) it('installs an adapter with --save-exact', function () { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP // Add a first adapter - sh.cd(config.paths.endUserRepo); - commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { saveExact: true }); - let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo); + sh.cd(config.paths.endUserRepo) + commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { saveExact: true }) + let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo) // TEST - expect(packageJson.devDependencies).to.have.property('cz-conventional-changelog'); - let range = packageJson.devDependencies['cz-conventional-changelog']; + expect(packageJson.devDependencies).to.have.property('cz-conventional-changelog') + let range = packageJson.devDependencies['cz-conventional-changelog'] // It should satisfy the requirements of a range - expect(semver.validRange(range)).to.not.equal(null); + expect(semver.validRange(range)).to.not.equal(null) // But you CAN increment a single version - expect(semver.inc(range, 'major')).not.to.equal(null); - - }); + expect(semver.inc(range, 'major')).not.to.equal(null) + }) it('installs an adapter with --yarn', function () { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP // Install an adapter - commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { yarn: true }); + commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { yarn: true }) // TEST // Check resulting json - let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo); - expect(packageJson).to.have.nested.property('dependencies.cz-conventional-changelog'); - - }); + let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo) + expect(packageJson).to.have.nested.property('dependencies.cz-conventional-changelog') + }) it('installs an adapter with --yarn --dev', function () { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP // Install an adapter - commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { yarn: true, dev: true }); + commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { yarn: true, dev: true }) // TEST // Check resulting json - let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo); - expect(packageJson).to.have.nested.property('devDependencies.cz-conventional-changelog'); - - }); + let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo) + expect(packageJson).to.have.nested.property('devDependencies.cz-conventional-changelog') + }) it('errors (with --yarn) on previously installed adapter', function () { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP // Add a first adapter - sh.cd(config.paths.endUserRepo); - commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { yarn: true, dev: true }); + sh.cd(config.paths.endUserRepo) + commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { yarn: true, dev: true }) // TEST - sh.cd(config.paths.endUserRepo); + sh.cd(config.paths.endUserRepo) // Adding a second adapter expect(function () { - commitizenInit(sh, config.paths.endUserRepo, 'cz-jira-smart-commit', { yarn: true, dev: true }); - }).to.throw(/already configured/); + commitizenInit(sh, config.paths.endUserRepo, 'cz-jira-smart-commit', { yarn: true, dev: true }) + }).to.throw(/already configured/) // Check resulting json - let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo); - expect(packageJson).not.to.have.nested.property('devDependencies', 'cz-jira-smart-commit'); - expect(packageJson).to.have.nested.property('config.commitizen.path', './node_modules/cz-conventional-changelog'); + let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo) + expect(packageJson).not.to.have.nested.property('devDependencies', 'cz-jira-smart-commit') + expect(packageJson).to.have.nested.property('config.commitizen.path', './node_modules/cz-conventional-changelog') // TODO: Eventually may need to offer both path and package keys. package = npm package name // Path for local development - }); + }) it('succeeds (with --yarn) if force is true', function () { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP // Add a first adapter - sh.cd(config.paths.endUserRepo); - commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { yarn: true, dev: true }); + sh.cd(config.paths.endUserRepo) + commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { yarn: true, dev: true }) // TEST // Adding a second adapter expect(function () { - commitizenInit(sh, config.paths.endUserRepo, 'cz-jira-smart-commit', { yarn: true, dev: true, force: true }); - }).to.not.throw(); + commitizenInit(sh, config.paths.endUserRepo, 'cz-jira-smart-commit', { yarn: true, dev: true, force: true }) + }).to.not.throw() - let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo); - expect(packageJson.devDependencies).to.have.property('cz-jira-smart-commit'); - expect(packageJson).to.have.nested.property('config.commitizen.path', './node_modules/cz-jira-smart-commit'); - - }); + let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo) + expect(packageJson.devDependencies).to.have.property('cz-jira-smart-commit') + expect(packageJson).to.have.nested.property('config.commitizen.path', './node_modules/cz-jira-smart-commit') + }) it('installs (with --yarn) an adapter without --save-exact', function () { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP // Add a first adapter - sh.cd(config.paths.endUserRepo); - commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { yarn: true, dev: true }); - let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo); + sh.cd(config.paths.endUserRepo) + commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { yarn: true, dev: true }) + let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo) // TEST - expect(packageJson.devDependencies).to.have.property('cz-conventional-changelog'); - let range = packageJson.devDependencies['cz-conventional-changelog']; + expect(packageJson.devDependencies).to.have.property('cz-conventional-changelog') + let range = packageJson.devDependencies['cz-conventional-changelog'] // It should satisfy the requirements of a range - expect(semver.validRange(range)).to.not.equal(null); + expect(semver.validRange(range)).to.not.equal(null) // // But you CAN NOT increment a range // expect(semver.inc(range, 'major')).to.equal(null); // TODO: We need to figure out how to check if the repo has save exact set // in the config before we can re-enable this. The --save-exact setting // in our package.json breaks this test - - }); + }) it('installs an adapter with --yarn --exact', function () { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP // Add a first adapter - sh.cd(config.paths.endUserRepo); - commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { yarn: true, dev: true, exact: true }); - let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo); + sh.cd(config.paths.endUserRepo) + commitizenInit(sh, config.paths.endUserRepo, 'cz-conventional-changelog', { yarn: true, dev: true, exact: true }) + let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo) // TEST - expect(packageJson.devDependencies).to.have.property('cz-conventional-changelog'); - let range = packageJson.devDependencies['cz-conventional-changelog']; + expect(packageJson.devDependencies).to.have.property('cz-conventional-changelog') + let range = packageJson.devDependencies['cz-conventional-changelog'] // It should satisfy the requirements of a range - expect(semver.validRange(range)).to.not.equal(null); + expect(semver.validRange(range)).to.not.equal(null) // But you CAN increment a single version - expect(semver.inc(range, 'major')).not.to.equal(null); - - }); - -}); + expect(semver.inc(range, 'major')).not.to.equal(null) + }) +}) afterEach(function () { - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // All this should do is archive the tmp path to the artifacts - clean.afterEach(sh, config.paths.tmp, config.preserve); -}); + clean.afterEach(sh, config.paths.tmp, config.preserve) +}) after(function () { - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // Once everything is done, the artifacts should be cleaned up based on // the preserve setting in the config - clean.after(sh, config.paths.tmp, config.preserve); -}); + clean.after(sh, config.paths.tmp, config.preserve) +}) diff --git a/test/tests/parsers.js b/test/tests/parsers.js index fa6fbaed..a348e8ff 100644 --- a/test/tests/parsers.js +++ b/test/tests/parsers.js @@ -1,36 +1,36 @@ /* eslint-env mocha */ -import { expect } from 'chai'; -import { parse } from '../../src/cli/parsers/git-cz'; +import { expect } from 'chai' +import { parse } from '../../src/cli/parsers/git-cz' describe('parsers', () => { describe('git-cz', () => { it('should parse --message "Hello, World!"', () => { - expect(parse(['--amend', '--message', 'Hello, World!'])).to.deep.equal(['--amend']); - }); + expect(parse(['--amend', '--message', 'Hello, World!'])).to.deep.equal(['--amend']) + }) it('should parse --message="Hello, World!"', () => { - expect(parse(['--amend', '--message=Hello, World!'])).to.deep.equal(['--amend']); - }); + expect(parse(['--amend', '--message=Hello, World!'])).to.deep.equal(['--amend']) + }) it('should parse -amwip', () => { - expect(parse(['-amwip'])).to.deep.equal(['-a']); - }); + expect(parse(['-amwip'])).to.deep.equal(['-a']) + }) it('should parse -am=wip', () => { - expect(parse(['-am=wip'])).to.deep.equal(['-a']); - }); + expect(parse(['-am=wip'])).to.deep.equal(['-a']) + }) it('should parse -am wip', () => { - expect(parse(['-am', 'wip'])).to.deep.equal(['-a']); - }); + expect(parse(['-am', 'wip'])).to.deep.equal(['-a']) + }) it('should parse -a -m wip -n', () => { - expect(parse(['-a', '-m', 'wip', '-n'])).to.deep.equal(['-a', '-n']); - }); + expect(parse(['-a', '-m', 'wip', '-n'])).to.deep.equal(['-a', '-n']) + }) it('should parse -a -m=wip -n', () => { - expect(parse(['-a', '-m=wip', '-n'])).to.deep.equal(['-a', '-n']); - }); - }); -}); + expect(parse(['-a', '-m=wip', '-n'])).to.deep.equal(['-a', '-n']) + }) + }) +}) diff --git a/test/tests/staging.js b/test/tests/staging.js index 6bdef21b..5cf78f27 100644 --- a/test/tests/staging.js +++ b/test/tests/staging.js @@ -1,34 +1,32 @@ /* eslint-env mocha */ /* eslint-disable no-unused-expressions */ -import { expect } from 'chai'; +import { expect } from 'chai' // Bootstrap our tester -import { bootstrap } from '../tester'; +import { bootstrap } from '../tester' // Get our source files -import { init as gitInit, addPath as gitAdd } from '../../src/git'; -import { staging } from '../../src/commitizen'; +import { init as gitInit, addPath as gitAdd } from '../../src/git' +import { staging } from '../../src/commitizen' // Destructure some things for cleaner tests -let { config, sh, repo, clean, files } = bootstrap(); -let { writeFilesToPath } = files; +let { config, sh, repo, clean, files } = bootstrap() +let { writeFilesToPath } = files before(function () { // Creates the temp path - clean.before(sh, config.paths.tmp); -}); + clean.before(sh, config.paths.tmp) +}) beforeEach(function () { - this.timeout(config.maxTimeout); // this could take a while - repo.createEndUser(sh, config.paths.endUserRepo); -}); + this.timeout(config.maxTimeout) // this could take a while + repo.createEndUser(sh, config.paths.endUserRepo) +}) describe('staging', function () { - it('should determine if a repo is clean', function (done) { - - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // SETUP @@ -37,61 +35,60 @@ describe('staging', function () { path: config.paths.endUserRepo, files: { dummyfile: { - contents: `duck-duck-goose`, - filename: `mydummyfile.txt`, + contents: `duck-duck-goose`, + filename: `mydummyfile.txt` }, gitignore: { contents: `node_modules/`, filename: `.gitignore` } } - }; + } - gitInit(sh, repoConfig.path); + gitInit(sh, repoConfig.path) staging.isClean('./@this-actually-does-not-exist', function (stagingError) { - expect(stagingError).to.be.an.instanceof(Error); + expect(stagingError).to.be.an.instanceof(Error) staging.isClean(repoConfig.path, function (stagingIsCleanError, stagingIsClean) { - expect(stagingIsCleanError).to.be.null; - expect(stagingIsClean).to.be.true; + expect(stagingIsCleanError).to.be.null + expect(stagingIsClean).to.be.true - writeFilesToPath(repoConfig.files, repoConfig.path); + writeFilesToPath(repoConfig.files, repoConfig.path) - gitAdd(sh, repoConfig.path); + gitAdd(sh, repoConfig.path) staging.isClean(repoConfig.path, function (afterWriteStagingIsCleanError, afterWriteStagingIsClean) { - expect(afterWriteStagingIsCleanError).to.be.null; - expect(afterWriteStagingIsClean).to.be.false; + expect(afterWriteStagingIsCleanError).to.be.null + expect(afterWriteStagingIsClean).to.be.false writeFilesToPath({ dummymodified: { contents: repoConfig.files.dummyfile.contents + '-modified', - filename: repoConfig.files.dummyfile.filename, + filename: repoConfig.files.dummyfile.filename } - }, repoConfig.path); + }, repoConfig.path) staging.isClean(repoConfig.path, function (afterWriteStagingIsCleanError, afterWriteStagingIsClean) { - expect(afterWriteStagingIsCleanError).to.be.null; - expect(afterWriteStagingIsClean).to.be.false; - done(); - }); - }); - }); - }); - }); - -}); + expect(afterWriteStagingIsCleanError).to.be.null + expect(afterWriteStagingIsClean).to.be.false + done() + }) + }) + }) + }) + }) +}) afterEach(function () { - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // All this should do is archive the tmp path to the artifacts - clean.afterEach(sh, config.paths.tmp, config.preserve); -}); + clean.afterEach(sh, config.paths.tmp, config.preserve) +}) after(function () { - this.timeout(config.maxTimeout); // this could take a while + this.timeout(config.maxTimeout) // this could take a while // Once everything is done, the artifacts should be cleaned up based on // the preserve setting in the config - clean.after(sh, config.paths.tmp, config.preserve); -}); + clean.after(sh, config.paths.tmp, config.preserve) +}) diff --git a/test/tests/util.js b/test/tests/util.js index 5af675c3..d710c9a9 100644 --- a/test/tests/util.js +++ b/test/tests/util.js @@ -1,77 +1,70 @@ /* eslint-env mocha */ /* eslint-disable no-unused-expressions */ -import { expect } from 'chai'; -import { isArray, isFunction, isString } from '../../src/common/util'; +import { expect } from 'chai' +import { isArray, isFunction, isString } from '../../src/common/util' describe('common util', function () { - it('isArray determines if array is passed', function () { - // Truthies - expect(isArray([])).to.be.true; - expect(isArray([1, 2, 3])).to.be.true; + expect(isArray([])).to.be.true + expect(isArray([1, 2, 3])).to.be.true // eslint-disable-next-line no-sparse-arrays - expect(isArray([1, , 3])).to.be.true; + expect(isArray([1, , 3])).to.be.true // eslint-disable-next-line no-array-constructor - expect(isArray(new Array())).to.be.true; + expect(isArray(new Array())).to.be.true // Falsies - expect(isArray(undefined)).to.be.false; - expect(isArray(null)).to.be.false; - expect(isArray(49)).to.be.false; - expect(isArray(function () {})).to.be.false; - expect(isArray({})).to.be.false; - expect(isArray("asdf")).to.be.false; - expect(isArray(true)).to.be.false; - expect(isArray(false)).to.be.false; - expect(isArray(Symbol('test'))).to.be.false; - - }); + expect(isArray(undefined)).to.be.false + expect(isArray(null)).to.be.false + expect(isArray(49)).to.be.false + expect(isArray(function () {})).to.be.false + expect(isArray({})).to.be.false + expect(isArray('asdf')).to.be.false + expect(isArray(true)).to.be.false + expect(isArray(false)).to.be.false + expect(isArray(Symbol('test'))).to.be.false + }) it('isFunction determines if a function is passed', function () { - // Truthies - expect(isFunction(function () {})).to.be.true; + expect(isFunction(function () {})).to.be.true // eslint-disable-next-line no-new-func - expect(isFunction(new Function())).to.be.true; + expect(isFunction(new Function())).to.be.true // Falsies - expect(isFunction(undefined)).to.be.false; - expect(isFunction(null)).to.be.false; - expect(isFunction(49)).to.be.false; - expect(isFunction([])).to.be.false; - expect(isFunction({})).to.be.false; - expect(isFunction("asdf")).to.be.false; - expect(isFunction(true)).to.be.false; - expect(isFunction(false)).to.be.false; - expect(isFunction(Symbol('test'))).to.be.false; - - }); + expect(isFunction(undefined)).to.be.false + expect(isFunction(null)).to.be.false + expect(isFunction(49)).to.be.false + expect(isFunction([])).to.be.false + expect(isFunction({})).to.be.false + expect(isFunction('asdf')).to.be.false + expect(isFunction(true)).to.be.false + expect(isFunction(false)).to.be.false + expect(isFunction(Symbol('test'))).to.be.false + }) it('isString determines if string is passed', function () { - // Truthies - expect(isString('a single quoted string')).to.be.true; - expect(isString("a double quoted string")).to.be.true; + expect(isString('a single quoted string')).to.be.true + expect(isString('a double quoted string')).to.be.true expect(isString(` a multi line string` - )).to.be.true; + )).to.be.true // eslint-disable-next-line no-new-wrappers - expect(isString(new String())).to.be.true; + expect(isString(new String())).to.be.true // Falsies - expect(isString(function () {})).to.be.false; - expect(isString(undefined)).to.be.false; - expect(isString(null)).to.be.false; - expect(isString(49)).to.be.false; - expect(isString([])).to.be.false; - expect(isString({})).to.be.false; - expect(isString(true)).to.be.false; - expect(isString(false)).to.be.false; - expect(isString(Symbol('test'))).to.be.false; - - }); -}); + expect(isString(function () {})).to.be.false + expect(isString(undefined)).to.be.false + expect(isString(null)).to.be.false + expect(isString(49)).to.be.false + expect(isString([])).to.be.false + expect(isString({})).to.be.false + expect(isString(true)).to.be.false + expect(isString(false)).to.be.false + expect(isString(Symbol('test'))).to.be.false + }) +}) diff --git a/test/tools/clean.js b/test/tools/clean.js index f8bef3db..5737cef9 100644 --- a/test/tools/clean.js +++ b/test/tools/clean.js @@ -1,33 +1,33 @@ -import * as path from 'path'; -import fs from 'fs-extra'; -import uuid from 'node-uuid'; +import * as path from 'path' +import fs from 'fs-extra' +import uuid from 'node-uuid' export { before, after, afterEach -}; +} // Unique id for each 'run' of the entire test suite -let testSuiteRunId = uuid.v4(); +let testSuiteRunId = uuid.v4() // At the beginning of a run purge .tmp function before (sh, tmpPath) { - cleanPath(sh, tmpPath); + cleanPath(sh, tmpPath) // clean(sh, tmpPath, 'all'); } function afterEach (sh, tmpPath, preserve) { if (preserve !== false) { - archive(sh, tmpPath, testSuiteRunId); + archive(sh, tmpPath, testSuiteRunId) } - cleanPath(sh, tmpPath); + cleanPath(sh, tmpPath) } // After should listen to the user via the config // Before should always purge .tmp irregardless of config function after (sh, tmpPath, preserve) { - clean(sh, tmpPath, preserve); + clean(sh, tmpPath, preserve) } /** @@ -37,9 +37,9 @@ function after (sh, tmpPath, preserve) { * Generally should be run in afterEach() */ function archive (sh, tmpPath, testSuiteRunId) { - let destinationPath = path.resolve(tmpPath + '/../artifacts/' + testSuiteRunId + '/' + uuid.v4()); - sh.mkdir('-p', destinationPath); - sh.cp('-Rf', tmpPath + '/*', destinationPath); + let destinationPath = path.resolve(tmpPath + '/../artifacts/' + testSuiteRunId + '/' + uuid.v4()) + sh.mkdir('-p', destinationPath) + sh.cp('-Rf', tmpPath + '/*', destinationPath) } /** @@ -48,24 +48,20 @@ function archive (sh, tmpPath, testSuiteRunId) { * Generally called in after() */ function clean (sh, tmpPath, preserve) { - /** * If preserve is a normal integer over 0 thats how many results to keep. * If string 'all' then keep all * Else: don't preserve anything */ if (preserve === 'all') { - /** * Preserve all artifacts * Don't purge any artifacts * * BEWARE: this can fill the disk up over time */ - return; - + return } else if (isNormalNonZeroInteger(preserve)) { - /** * Preserve a specific number of artifacts * @@ -74,31 +70,30 @@ function clean (sh, tmpPath, preserve) { */ // Set the path - let artifactsBasePath = path.resolve(tmpPath + '/../artifacts'); + let artifactsBasePath = path.resolve(tmpPath + '/../artifacts') // The the files in this path - let artifactFolders = fs.readdirSync(artifactsBasePath); + let artifactFolders = fs.readdirSync(artifactsBasePath) // Reverse chronologially sort the files artifactFolders.sort(function (a, b) { - return fs.statSync(path.resolve(artifactsBasePath, b)).mtime.getTime() - fs.statSync(path.resolve(artifactsBasePath, a)).mtime.getTime(); - }); + return fs.statSync(path.resolve(artifactsBasePath, b)).mtime.getTime() - fs.statSync(path.resolve(artifactsBasePath, a)).mtime.getTime() + }) // Keep only the number of files defined in the config setting 'preserve'. - keep(sh, artifactsBasePath, artifactFolders, preserve); + keep(sh, artifactsBasePath, artifactFolders, preserve) } // Always purge tmp, it needs to be empty for next run - cleanPath(sh, tmpPath); + cleanPath(sh, tmpPath) } function isNormalNonZeroInteger (str) { - if (Number.isInteger(str) && str > 0) { // Check for integers above 0 - return str; + return str } else { // Check for strings that cast to ints that are above 0 - var n = ~~Number(str); - return String(n) === str && n > 0; + var n = ~~Number(str) + return String(n) === str && n > 0 } } @@ -109,13 +104,12 @@ function isNormalNonZeroInteger (str) { * n is the (1 indexed) count of files to keep. */ function keep (sh, basePath, paths, n) { - for (let i = paths.length; i > n; i--) { - fs.removeSync(path.resolve(basePath, paths[i - 1])); + fs.removeSync(path.resolve(basePath, paths[i - 1])) } } function cleanPath (sh, tmpPath) { - sh.rm('-rf', tmpPath + '/*'); - sh.mkdir(tmpPath); + sh.rm('-rf', tmpPath + '/*') + sh.mkdir(tmpPath) } diff --git a/test/tools/files.js b/test/tools/files.js index de627570..afb0767d 100644 --- a/test/tools/files.js +++ b/test/tools/files.js @@ -1,10 +1,10 @@ -import fs from 'fs'; -import path from 'path'; -import _ from 'lodash'; +import fs from 'fs' +import path from 'path' +import _ from 'lodash' export { writeFilesToPath -}; +} /** * Opinionated writing of files to a path. @@ -14,6 +14,6 @@ export { */ function writeFilesToPath (files, directoryPath) { _.forOwn(files, function (key, value) { - fs.writeFileSync(path.resolve(directoryPath, files[value].filename), files[value].contents); - }); + fs.writeFileSync(path.resolve(directoryPath, files[value].filename), files[value].contents) + }) } diff --git a/test/tools/repo.js b/test/tools/repo.js index 88ab2e8f..f4c4d1fa 100644 --- a/test/tools/repo.js +++ b/test/tools/repo.js @@ -1,20 +1,20 @@ export { createEmpty, createEndUser -}; +} /** * Create an empty repo */ function createEmpty (sh, path) { - sh.mkdir(path); - sh.cd(path); - sh.exec('npm init --force --yes'); + sh.mkdir(path) + sh.cd(path) + sh.exec('npm init --force --yes') } /** * Create a new repo to hold an end user app */ function createEndUser (sh, path) { - createEmpty(sh, path); + createEmpty(sh, path) }