From 336123fe05e7f80d79fc8522b4ff21a60fffe77c Mon Sep 17 00:00:00 2001 From: Nick Merwin Date: Wed, 20 Nov 2019 17:05:48 -0800 Subject: ES6 * remove unused variables * move `require`s at the top * check for prototype built-ins * run in strict mode * always check for error values in tests * make style consistent * mark Node.js 6 as the minimum supported version in package.json * Use the arrow return syntax * logger.js: use `Boolean` to make the intention clearer. * Use the rest params instead of arguments. * test/getOptions.js: beautify git data. * Update logger.js Remove `hasDebugEnvVariable` function; it's just a `process.env` check * Create .jshintrc --- .jshintrc | 16 + bin/coveralls.js | 24 +- index.js | 29 +- lib/convertLcovToCoveralls.js | 102 +++--- lib/detectLocalGit.js | 68 ++-- lib/fetchGitData.js | 84 +++-- lib/getOptions.js | 108 +++--- lib/handleInput.js | 34 +- lib/logger.js | 18 +- lib/sendToCoveralls.js | 23 +- package.json | 2 +- test/convertLcovToCoveralls.js | 177 +++++----- test/detectLocalGit.js | 90 +++-- test/fetchGitData.js | 204 +++++------ test/getOptions.js | 744 +++++++++++++++++++++++------------------ test/handleInput.js | 110 +++--- test/logger.js | 25 +- test/sendToCoveralls.js | 67 ++-- 18 files changed, 1060 insertions(+), 865 deletions(-) create mode 100644 .jshintrc diff --git a/.jshintrc b/.jshintrc new file mode 100644 index 0000000..1d18bc6 --- /dev/null +++ b/.jshintrc @@ -0,0 +1,16 @@ +{ + "curly": true, + "debug": true, + "eqeqeq": true, + "esversion": 6, + "forin": true, + "latedef": false, + "mocha": true, + "noarg": true, + "nocomma": true, + "node": true, + "nonbsp": true, + "strict": "global", + "undef": true, + "unused": true +} \ No newline at end of file diff --git a/bin/coveralls.js b/bin/coveralls.js index 324ec6d..7d92ad2 100755 --- a/bin/coveralls.js +++ b/bin/coveralls.js @@ -1,22 +1,22 @@ #!/usr/bin/env node -var handleInput = require('../lib/handleInput'); -var logger = require('../lib/logger'); +'use strict'; + +const { handleInput } = require('..'); process.stdin.resume(); process.stdin.setEncoding('utf8'); -var input = ''; +let input = ''; -process.stdin.on('data', function(chunk) { - input += chunk; +process.stdin.on('data', chunk => { + input += chunk; }); -process.stdin.on('end', function() { - handleInput(input, function(err) { - if (err) { - throw err; - } - }); +process.stdin.on('end', () => { + handleInput(input, err => { + if (err) { + throw err; + } + }); }); - diff --git a/index.js b/index.js index e1103a0..44f878d 100644 --- a/index.js +++ b/index.js @@ -1,16 +1,23 @@ -var minimist = require('minimist'); +'use strict'; + +const minimist = require('minimist'); // this needs to go before the other require()s so that // the other files can already use index.options -exports.options = minimist(process.argv.slice(2), { - boolean: ['verbose', 'stdout'], - alias: { 'v': 'verbose', 's': 'stdout' } +module.exports.options = minimist(process.argv.slice(2), { + boolean: [ + 'verbose', + 'stdout' + ], + alias: { + 'v': 'verbose', + 's': 'stdout' + } }); -var dir = './lib/'; -exports.convertLcovToCoveralls = require(dir + 'convertLcovToCoveralls'); -exports.sendToCoveralls = require(dir + 'sendToCoveralls'); -exports.getBaseOptions = require(dir + 'getOptions').getBaseOptions; -exports.getOptions = require(dir + 'getOptions').getOptions; -exports.handleInput = require(dir + 'handleInput'); -exports.logger = require(dir + 'logger'); +module.exports.convertLcovToCoveralls = require('./lib/convertLcovToCoveralls'); +module.exports.sendToCoveralls = require('./lib/sendToCoveralls'); +module.exports.getBaseOptions = require('./lib/getOptions').getBaseOptions; +module.exports.getOptions = require('./lib/getOptions').getOptions; +module.exports.handleInput = require('./lib/handleInput'); +module.exports.logger = require('./lib/logger'); diff --git a/lib/convertLcovToCoveralls.js b/lib/convertLcovToCoveralls.js index 521e749..a6d5665 100644 --- a/lib/convertLcovToCoveralls.js +++ b/lib/convertLcovToCoveralls.js @@ -1,90 +1,104 @@ -var TRAVIS_JOB_ID = process.env.TRAVIS_JOB_ID || 'unknown'; -var fs = require('fs'); -var lcovParse = require('lcov-parse'); -var path = require('path'); -var logger = require('./logger')(); - -var detailsToCoverage = function(length, details){ - var coverage = new Array(length); - details.forEach(function(obj){ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const lcovParse = require('lcov-parse'); +const logger = require('./logger')(); + +const detailsToCoverage = (length, details) => { + const coverage = new Array(length); + details.forEach(obj => { coverage[obj.line - 1] = obj.hit; }); return coverage; }; -var detailsToBranches = function(details){ - var branches = []; - details.forEach(function(obj){ - ['line','block','branch','taken'].forEach(function(key){ +const detailsToBranches = details => { + const branches = []; + details.forEach(obj => { + ['line', 'block', 'branch', 'taken'].forEach(key => { branches.push(obj[key] || 0); }); }); return branches; }; -var convertLcovFileObject = function(file, filepath){ - var rootpath = filepath; +const convertLcovFileObject = (file, filepath) => { + const rootpath = filepath; filepath = path.resolve(rootpath, file.file); - var source = fs.readFileSync(filepath, 'utf8'); - var lines = source.split("\n"); - var coverage = detailsToCoverage(lines.length, file.lines.details); - var branches = detailsToBranches(file.branches.details); - return { name : path.relative(rootpath, path.resolve(rootpath, file.file)).split( path.sep ).join( "/" ), - source : source, - coverage : coverage, - branches : branches }; + const source = fs.readFileSync(filepath, 'utf8'); + const lines = source.split('\n'); + const coverage = detailsToCoverage(lines.length, file.lines.details); + const branches = detailsToBranches(file.branches.details); + + return { + name: path.relative(rootpath, path.resolve(rootpath, file.file)).split(path.sep).join('/'), + source, + coverage, + branches + }; }; -var cleanFilePath = function(file) { - if (file.indexOf('!') > -1) { - var regex = /^(.*!)(.*)$/g; - var matches = regex.exec(file); - return matches[matches.length-1]; +const cleanFilePath = file => { + if (file.includes('!')) { + const regex = /^(.*!)(.*)$/g; + const matches = regex.exec(file); + return matches[matches.length - 1]; } return file; }; -var convertLcovToCoveralls = function(input, options, cb){ - var filepath = options.filepath || ''; - logger.debug("in: ", filepath); +const convertLcovToCoveralls = (input, options, cb) => { + let filepath = options.filepath || ''; + logger.debug('in: ', filepath); filepath = path.resolve(process.cwd(), filepath); - lcovParse(input, function(err, parsed){ - if (err){ - logger.error("error from lcovParse: ", err); - logger.error("input: ", input); + lcovParse(input, (err, parsed) => { + if (err) { + logger.error('error from lcovParse: ', err); + logger.error('input: ', input); return cb(err); } - var postJson = { - source_files : [] + + const postJson = { + source_files: [] }; - if (options.git){ + + if (options.git) { postJson.git = options.git; } - if (options.run_at){ + + if (options.run_at) { postJson.run_at = options.run_at; } - if (options.service_name){ + + if (options.service_name) { postJson.service_name = options.service_name; } - if (options.service_job_id){ + + if (options.service_job_id) { postJson.service_job_id = options.service_job_id; } + if (options.service_pull_request) { postJson.service_pull_request = options.service_pull_request; } + if (options.repo_token) { postJson.repo_token = options.repo_token; } + if (options.parallel) { postJson.parallel = options.parallel; } + if (options.service_pull_request) { postJson.service_pull_request = options.service_pull_request; } - parsed.forEach(function(file){ + + parsed.forEach(file => { file.file = cleanFilePath(file.file); - var currentFilePath = path.resolve(filepath, file.file); + const currentFilePath = path.resolve(filepath, file.file); if (fs.existsSync(currentFilePath)) { postJson.source_files.push(convertLcovFileObject(file, filepath)); } @@ -97,7 +111,6 @@ module.exports = convertLcovToCoveralls; /* example coveralls json file - { "service_job_id": "1234567890", "service_name": "travis-ci", @@ -115,7 +128,6 @@ module.exports = convertLcovToCoveralls; ] } - example output from lcov parser: [ diff --git a/lib/detectLocalGit.js b/lib/detectLocalGit.js index 46a9e67..89133ff 100644 --- a/lib/detectLocalGit.js +++ b/lib/detectLocalGit.js @@ -1,47 +1,59 @@ -var fs = require('fs'); -var path = require('path'); +'use strict'; + +const fs = require('fs'); +const path = require('path'); // branch naming only has a few excluded characters, see git-check-ref-format(1) -var REGEX_BRANCH = /^ref: refs\/heads\/([^?*\[\\~^:]+)$/; +const REGEX_BRANCH = /^ref: refs\/heads\/([^?*[\\~^:]+)$/; + +function detectLocalGit() { + let dir = process.cwd(); + let gitDir; -module.exports = function detectLocalGit() { - var dir = process.cwd(), gitDir; while (path.resolve('/') !== dir) { gitDir = path.join(dir, '.git'); - var existsSync = fs.existsSync || path.existsSync; - if (existsSync(path.join(gitDir, 'HEAD'))) + const existsSync = fs.existsSync || path.existsSync; + if (existsSync(path.join(gitDir, 'HEAD'))) { break; + } dir = path.dirname(dir); } - if (path.resolve('/') === dir) + if (path.resolve('/') === dir) { return; + } - var head = fs.readFileSync(path.join(dir, '.git', 'HEAD'), 'utf-8').trim(); - var branch = (head.match(REGEX_BRANCH) || [])[1]; - if (!branch) + const head = fs.readFileSync(path.join(dir, '.git', 'HEAD'), 'utf-8').trim(); + const branch = (head.match(REGEX_BRANCH) || [])[1]; + if (!branch) { return { git_commit: head }; + } - var commit = _parseCommitHashFromRef(dir, branch); + const commit = _parseCommitHashFromRef(dir, branch); - return { git_commit: commit, git_branch: branch }; -}; + return { + git_commit: commit, + git_branch: branch + }; +} function _parseCommitHashFromRef(dir, branch) { - var ref = path.join(dir, '.git', 'refs', 'heads', branch); - if (fs.existsSync(ref)) { - return fs.readFileSync(ref, 'utf-8').trim(); - } else { - // ref does not exist; get it from packed-refs - var commit = ''; - var packedRefs = path.join(dir, '.git', 'packed-refs'); - var packedRefsText = fs.readFileSync(packedRefs, 'utf-8'); - packedRefsText.split('\n').forEach(function (line) { - if (line.match('refs/heads/'+branch)) { - commit = line.split(' ')[0]; - } - }); - return commit; + const ref = path.join(dir, '.git', 'refs', 'heads', branch); + if (fs.existsSync(ref)) { + return fs.readFileSync(ref, 'utf-8').trim(); + } + + // ref does not exist; get it from packed-refs + let commit = ''; + const packedRefs = path.join(dir, '.git', 'packed-refs'); + const packedRefsText = fs.readFileSync(packedRefs, 'utf-8'); + packedRefsText.split('\n').forEach(line => { + if (line.match(`refs/heads/${branch}`)) { + commit = line.split(' ')[0]; } + }); + return commit; } + +module.exports = detectLocalGit; diff --git a/lib/fetchGitData.js b/lib/fetchGitData.js index f04720e..ee69246 100644 --- a/lib/fetchGitData.js +++ b/lib/fetchGitData.js @@ -1,47 +1,53 @@ -var exec = require('child_process').exec; -var logger = require('./logger')(); +'use strict'; + +const { exec } = require('child_process'); +require('./logger')(); function fetchGitData(git, cb) { - if (!cb){ - throw new Error("fetchGitData requires a callback"); + if (!cb) { + throw new Error('fetchGitData requires a callback'); } //-- Malformed/undefined git object - if ('undefined' === typeof git) { + if (typeof git === 'undefined') { return cb(new Error('No options passed')); } - if (!git.hasOwnProperty('head')) { + + if (!Object.prototype.hasOwnProperty.call(git, 'head')) { return cb(new Error('You must provide the head')); } - if (!git.head.hasOwnProperty('id')) { + + if (!Object.prototype.hasOwnProperty.call(git.head, 'id')) { return cb(new Error('You must provide the head.id')); } //-- Set required properties of git if they weren"t provided - if (!git.hasOwnProperty("branch")) { - git.branch = ""; + if (!Object.prototype.hasOwnProperty.call(git, 'branch')) { + git.branch = ''; } - if (!git.hasOwnProperty("remotes")) { + + if (!Object.prototype.hasOwnProperty.call(git, 'remotes')) { git.remotes = []; } //-- Assert the property types - if ("string" !== typeof git.branch) { - git.branch = ""; + if (typeof git.branch !== 'string') { + git.branch = ''; } - if (!(git.remotes instanceof Array)) { + + if (!(Array.isArray(git.remotes))) { git.remotes = []; } //-- Use git? - exec("git rev-parse --verify " + git.head.id, function(err, response){ - if (err){ + exec(`git rev-parse --verify ${git.head.id}`, err => { + if (err) { // git is not available... - git.head.author_name = git.head.author_name || "Unknown Author"; - git.head.author_email = git.head.author_email || ""; - git.head.committer_name = git.head.committer_name || "Unknown Committer"; - git.head.committer_email = git.head.committer_email || ""; - git.head.message = git.head.message || "Unknown Commit Message"; + git.head.author_name = git.head.author_name || 'Unknown Author'; + git.head.author_email = git.head.author_email || ''; + git.head.committer_name = git.head.committer_name || 'Unknown Committer'; + git.head.committer_email = git.head.committer_email || ''; + git.head.message = git.head.message || 'Unknown Commit Message'; return cb(null, git); } @@ -50,25 +56,27 @@ function fetchGitData(git, cb) { } function fetchBranch(git, cb) { - exec("git branch", function(err, branches){ - if (err) + exec('git branch', (err, branches) => { + if (err) { return cb(err); + } git.branch = (branches.match(/^\* (\w+)/) || [])[1]; fetchRemotes(git, cb); }); } -var REGEX_COMMIT_DETAILS = /\nauthor (.+?) <([^>]*)>.+\ncommitter (.+?) <([^>]*)>.+[\S\s]*?\n\n(.*)/m; +const REGEX_COMMIT_DETAILS = /\nauthor (.+?) <([^>]*)>.+\ncommitter (.+?) <([^>]*)>.+[\S\s]*?\n\n(.*)/m; function fetchHeadDetails(git, cb) { - exec('git cat-file -p ' + git.head.id, function(err, response) { - if (err) + exec(`git cat-file -p ${git.head.id}`, (err, response) => { + if (err) { return cb(err); + } - var items = response.match(REGEX_COMMIT_DETAILS).slice(1); - var fields = ['author_name', 'author_email', 'committer_name', 'committer_email', 'message']; - fields.forEach(function(field, index) { + const items = response.match(REGEX_COMMIT_DETAILS).slice(1); + const fields = ['author_name', 'author_email', 'committer_name', 'committer_email', 'message']; + fields.forEach((field, index) => { git.head[field] = items[index]; }); @@ -81,14 +89,17 @@ function fetchHeadDetails(git, cb) { } function fetchRemotes(git, cb) { - exec("git remote -v", function(err, remotes){ - if (err) + exec('git remote -v', (err, remotes) => { + if (err) { return cb(err); + } - var processed = {}; - remotes.split("\n").forEach(function(remote) { - if (!/\s\(push\)$/.test(remote)) + const processed = {}; + remotes.split('\n').forEach(remote => { + if (!/\s\(push\)$/.test(remote)) { return; + } + remote = remote.split(/\s+/); saveRemote(processed, git, remote[0], remote[1]); }); @@ -97,12 +108,13 @@ function fetchRemotes(git, cb) { } function saveRemote(processed, git, name, url) { - var key = name + "-" + url; - if (processed.hasOwnProperty(key)) + const key = `${name}-${url}`; + if (Object.prototype.hasOwnProperty.call(processed, key)) { return; + } processed[key] = true; - git.remotes.push({ name: name, url: url }); + git.remotes.push({ name, url }); } module.exports = fetchGitData; diff --git a/lib/getOptions.js b/lib/getOptions.js index aa24f43..8a0305f 100644 --- a/lib/getOptions.js +++ b/lib/getOptions.js @@ -1,23 +1,28 @@ -var fs = require('fs'); -var path = require('path'); -var yaml = require('js-yaml'); -var index = require('../index'); -var logger = require('./logger')(); -var fetchGitData = require('./fetchGitData'); - -var getBaseOptions = function(cb){ - var options = {}; - var git_commit = process.env.COVERALLS_GIT_COMMIT; - var git_branch = process.env.COVERALLS_GIT_BRANCH; - var git_committer_name, git_committer_email, git_message; - - var match = (process.env.CI_PULL_REQUEST || "").match(/(\d+)$/); +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const yaml = require('js-yaml'); +const logger = require('./logger')(); +const fetchGitData = require('./fetchGitData'); +const detectLocalGit = require('./detectLocalGit'); +const index = require('..'); + +const getBaseOptions = cb => { + const options = {}; + let git_commit = process.env.COVERALLS_GIT_COMMIT; + let git_branch = process.env.COVERALLS_GIT_BRANCH; + let git_committer_name; + let git_committer_email; + let git_message; + + const match = (process.env.CI_PULL_REQUEST || '').match(/(\d+)$/); if (match) { options.service_pull_request = match[1]; } - if (process.env.TRAVIS){ + if (process.env.TRAVIS) { options.service_name = 'travis-ci'; options.service_job_id = process.env.TRAVIS_JOB_ID; options.service_pull_request = process.env.TRAVIS_PULL_REQUEST; @@ -25,7 +30,7 @@ var getBaseOptions = function(cb){ git_branch = process.env.TRAVIS_BRANCH; } - if (process.env.DRONE){ + if (process.env.DRONE) { options.service_name = 'drone'; options.service_job_id = process.env.DRONE_BUILD_NUMBER; options.service_pull_request = process.env.DRONE_PULL_REQUEST; @@ -36,7 +41,7 @@ var getBaseOptions = function(cb){ git_message = process.env.DRONE_COMMIT_MESSAGE; } - if (process.env.JENKINS_URL || process.env.JENKINS_HOME){ + if (process.env.JENKINS_URL || process.env.JENKINS_HOME) { options.service_name = 'jenkins'; options.service_job_id = process.env.BUILD_ID; options.service_pull_request = process.env.CHANGE_ID || process.env.ghprbPullId; @@ -46,19 +51,20 @@ var getBaseOptions = function(cb){ git_branch = process.env.CHANGE_BRANCH || process.env.GIT_BRANCH || process.env.BRANCH_NAME; } - if (process.env.CIRCLECI){ + if (process.env.CIRCLECI) { options.service_name = 'circleci'; options.service_job_id = process.env.CIRCLE_BUILD_NUM; if (process.env.CI_PULL_REQUEST) { - var pr = process.env.CI_PULL_REQUEST.split('/pull/'); + const pr = process.env.CI_PULL_REQUEST.split('/pull/'); options.service_pull_request = pr[1]; } + git_commit = process.env.CIRCLE_SHA1; git_branch = process.env.CIRCLE_BRANCH; } - if (process.env.CI_NAME && process.env.CI_NAME === 'codeship'){ + if (process.env.CI_NAME && process.env.CI_NAME === 'codeship') { options.service_name = 'codeship'; options.service_job_id = process.env.CI_BUILD_NUMBER; git_commit = process.env.CI_COMMIT_ID; @@ -68,14 +74,14 @@ var getBaseOptions = function(cb){ git_message = process.env.CI_COMMIT_MESSAGE; } - if (process.env.WERCKER){ + if (process.env.WERCKER) { options.service_name = 'wercker'; options.service_job_id = process.env.WERCKER_BUILD_ID; git_commit = process.env.WERCKER_GIT_COMMIT; git_branch = process.env.WERCKER_GIT_BRANCH; } - if (process.env.GITLAB_CI){ + if (process.env.GITLAB_CI) { options.service_name = 'gitlab-ci'; options.service_job_number = process.env.CI_BUILD_NAME; options.service_job_id = process.env.CI_BUILD_ID; @@ -83,20 +89,22 @@ var getBaseOptions = function(cb){ git_commit = process.env.CI_BUILD_REF; git_branch = process.env.CI_BUILD_REF_NAME; } - if(process.env.APPVEYOR){ + + if (process.env.APPVEYOR) { options.service_name = 'appveyor'; options.service_job_number = process.env.APPVEYOR_BUILD_NUMBER; options.service_job_id = process.env.APPVEYOR_BUILD_ID; git_commit = process.env.APPVEYOR_REPO_COMMIT; git_branch = process.env.APPVEYOR_REPO_BRANCH; } - if(process.env.SURF_SHA1){ + + if (process.env.SURF_SHA1) { options.service_name = 'surf'; git_commit = process.env.SURF_SHA1; git_branch = process.env.SURF_REF; } - if(process.env.BUILDKITE){ + if (process.env.BUILDKITE) { options.service_name = 'buildkite'; options.service_job_number = process.env.BUILDKITE_BUILD_NUMBER; options.service_job_id = process.env.BUILDKITE_BUILD_ID; @@ -108,14 +116,14 @@ var getBaseOptions = function(cb){ git_message = process.env.BUILDKITE_MESSAGE; } - if(process.env.SEMAPHORE){ + if (process.env.SEMAPHORE) { options.service_name = 'semaphore'; options.service_job_id = process.env.SEMAPHORE_BUILD_NUMBER; git_commit = process.env.REVISION; git_branch = process.env.BRANCH_NAME; } - if(process.env.TF_BUILD){ + if (process.env.TF_BUILD) { options.service_name = 'Azure Pipelines'; options.service_job_id = process.env.BUILD_BUILDID; options.service_pull_request = process.env.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER; @@ -124,15 +132,16 @@ var getBaseOptions = function(cb){ } options.run_at = process.env.COVERALLS_RUN_AT || JSON.stringify(new Date()).slice(1, -1); - if (process.env.COVERALLS_SERVICE_NAME){ + if (process.env.COVERALLS_SERVICE_NAME) { options.service_name = process.env.COVERALLS_SERVICE_NAME; } - if (process.env.COVERALLS_SERVICE_JOB_ID){ + + if (process.env.COVERALLS_SERVICE_JOB_ID) { options.service_job_id = process.env.COVERALLS_SERVICE_JOB_ID; } if (!git_commit || !git_branch) { - var data = require('./detectLocalGit')(); + const data = detectLocalGit(); if (data) { git_commit = git_commit || data.git_commit; git_branch = git_branch || data.git_branch; @@ -148,18 +157,18 @@ var getBaseOptions = function(cb){ options.repo_token = process.env.COVERALLS_REPO_TOKEN; } else { // try to get the repo token from a .coveralls.yml file - var yml = path.join(process.cwd(), '.coveralls.yml'); + const yml = path.join(process.cwd(), '.coveralls.yml'); try { if (fs.statSync(yml).isFile()) { - var coveralls_yaml_conf = yaml.safeLoad(fs.readFileSync(yml, 'utf8')); + const coveralls_yaml_conf = yaml.safeLoad(fs.readFileSync(yml, 'utf8')); options.repo_token = coveralls_yaml_conf.repo_token; - if(coveralls_yaml_conf.service_name) { + if (coveralls_yaml_conf.service_name) { options.service_name = coveralls_yaml_conf.service_name; } } - } catch(ex){ - logger.warn("Repo token could not be determined. Continuing without it." + - "This is necessary for private repos only, so may not be an issue at all."); + } catch (_) { + logger.warn('Repo token could not be determined. Continuing without it. ' + + 'This is necessary for private repos only, so may not be an issue at all.'); } } @@ -167,7 +176,7 @@ var getBaseOptions = function(cb){ options.flag_name = process.env.COVERALLS_FLAG_NAME; } - if (git_commit){ + if (git_commit) { fetchGitData({ head: { id: git_commit, @@ -176,12 +185,13 @@ var getBaseOptions = function(cb){ message: git_message }, branch: git_branch - }, function(err, git){ - if (err){ + }, (err, git) => { + if (err) { logger.warn('there was an error getting git data: ', err); } else { options.git = git; } + return cb(err, options); }); } else { @@ -189,24 +199,28 @@ var getBaseOptions = function(cb){ } }; -var getOptions = function(cb, _userOptions){ - if (!cb){ +const getOptions = (cb, _userOptions) => { + if (!cb) { throw new Error('getOptions requires a callback'); } - var userOptions = _userOptions || {}; + const userOptions = _userOptions || {}; - getBaseOptions(function(err, options){ + getBaseOptions((err, options) => { // minimist populates options._ with non-option command line arguments - var firstNonOptionArgument = index.options._[0]; + const firstNonOptionArgument = index.options._[0]; - if (firstNonOptionArgument) + if (firstNonOptionArgument) { options.filepath = firstNonOptionArgument; + } // lodash or else would be better, but no need for the extra dependency - for (var option in userOptions) { - options[option] = userOptions[option]; + for (const option in userOptions) { + if (Object.prototype.hasOwnProperty.call(userOptions, option)) { + options[option] = userOptions[option]; + } } + cb(err, options); }); }; diff --git a/lib/handleInput.js b/lib/handleInput.js index 326671e..e7da536 100644 --- a/lib/handleInput.js +++ b/lib/handleInput.js @@ -1,33 +1,39 @@ -var index = require('../index'); -var logger = require('./logger')(); +'use strict'; + +const logger = require('./logger')(); +const index = require('..'); function handleInput(input, cb, userOptions) { logger.debug(input); - logger.debug('user options ' + userOptions); - index.getOptions(function(err, options){ - if (err){ - logger.error("error from getOptions"); + logger.debug(`user options ${userOptions}`); + index.getOptions((err, options) => { + if (err) { + logger.error('error from getOptions'); cb(err); return; } + logger.debug(options); - index.convertLcovToCoveralls(input, options, function(err, postData){ - if (err){ - logger.error("error from convertLcovToCoveralls"); + index.convertLcovToCoveralls(input, options, (err, postData) => { + if (err) { + logger.error('error from convertLcovToCoveralls'); cb(err); return; } - logger.info("sending this to coveralls.io: ", JSON.stringify(postData)); - index.sendToCoveralls(postData, function(err, response, body){ - if (err){ + + logger.info('sending this to coveralls.io: ', JSON.stringify(postData)); + index.sendToCoveralls(postData, (err, response, body) => { + if (err) { cb(err); return; } - if (response.statusCode >= 400){ - cb("Bad response: " + response.statusCode + " " + body); + + if (response.statusCode >= 400) { + cb(`Bad response: ${response.statusCode} ${body}`); return; } + logger.debug(response.statusCode); logger.debug(body); cb(null, body); diff --git a/lib/logger.js b/lib/logger.js index 1c2ba68..4f71d74 100644 --- a/lib/logger.js +++ b/lib/logger.js @@ -1,16 +1,14 @@ -var index = require('../index'); +'use strict'; -module.exports = function(){ - return require('log-driver')({level : getLogLevel()}); -}; +const logDriver = require('log-driver'); +const index = require('..'); -function getLogLevel(){ - if (index.options.verbose || hasDebugEnvVariable()) { +module.exports = () => logDriver({ level: getLogLevel() }); + +function getLogLevel() { + if (index.options.verbose || Boolean(process.env.NODE_COVERALLS_DEBUG)) { return 'debug'; } - return 'error'; -} -function hasDebugEnvVariable(){ - return process.env.NODE_COVERALLS_DEBUG == 1; + return 'error'; } diff --git a/lib/sendToCoveralls.js b/lib/sendToCoveralls.js index fcf63a8..0421556 100644 --- a/lib/sendToCoveralls.js +++ b/lib/sendToCoveralls.js @@ -1,20 +1,27 @@ -var request = require('request'); -var index = require('../index'); +'use strict'; -var sendToCoveralls = function(obj, cb){ - var urlBase = 'https://coveralls.io'; +const request = require('request'); +const index = require('..'); + +const sendToCoveralls = (obj, cb) => { + let urlBase = 'https://coveralls.io'; if (process.env.COVERALLS_ENDPOINT) { urlBase = process.env.COVERALLS_ENDPOINT; } - var str = JSON.stringify(obj); - var url = urlBase + '/api/v1/jobs'; - + const str = JSON.stringify(obj); + const url = `${urlBase}/api/v1/jobs`; + if (index.options.stdout) { process.stdout.write(str); cb(null, { statusCode: 200 }, ''); } else { - request.post({url : url, form : { json : str}}, function(err, response, body){ + request.post({ + url, + form: { + json: str + } + }, (err, response, body) => { cb(err, response, body); }); } diff --git a/package.json b/package.json index 10bd072..51532c9 100644 --- a/package.json +++ b/package.json @@ -56,7 +56,7 @@ "snyk": "^1.250.0" }, "engines": { - "node": ">=4.0.0" + "node": ">=6" }, "main": "index.js", "directories": { diff --git a/test/convertLcovToCoveralls.js b/test/convertLcovToCoveralls.js index 7ab6d18..2cfc856 100644 --- a/test/convertLcovToCoveralls.js +++ b/test/convertLcovToCoveralls.js @@ -1,142 +1,146 @@ -var convertLcovToCoveralls = require('../index').convertLcovToCoveralls; -var getOptions = require('../index').getOptions; -var should = require('should'); -var fs = require('fs'); -var logger = require('../lib/logger'); -var path = require('path'); -logger = require('log-driver')({level : false}); - -describe("convertLcovToCoveralls", function(){ - it ("should convert a simple lcov file", function(done){ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const should = require('should'); +const logDriver = require('log-driver'); +const { convertLcovToCoveralls, getOptions } = require('..'); + +logDriver({ level: false }); + +describe('convertLcovToCoveralls', () => { + it('should convert a simple lcov file', done => { delete process.env.TRAVIS; - var lcovpath = path.join(__dirname, "/../fixtures/onefile.lcov"); - var input = fs.readFileSync(lcovpath, "utf8"); - var libpath = path.join(__dirname, "/../fixtures/lib"); - convertLcovToCoveralls(input, {filepath: libpath}, function(err, output){ + const lcovpath = path.join(__dirname, '/../fixtures/onefile.lcov'); + const input = fs.readFileSync(lcovpath, 'utf8'); + const libpath = path.join(__dirname, '/../fixtures/lib'); + convertLcovToCoveralls(input, { filepath: libpath }, (err, output) => { should.not.exist(err); - output.source_files[0].name.should.equal("index.js"); - output.source_files[0].source.split("\n").length.should.equal(173); + output.source_files[0].name.should.equal('index.js'); + output.source_files[0].source.split('\n').length.should.equal(173); output.source_files[0].coverage[54].should.equal(0); output.source_files[0].coverage[60].should.equal(0); done(); }); }); - it ("should pass on all appropriate parameters from the environment", function(done){ + it('should pass on all appropriate parameters from the environment', done => { delete process.env.TRAVIS; - process.env.COVERALLS_GIT_COMMIT = "GIT_HASH"; - process.env.COVERALLS_GIT_BRANCH = "master"; - process.env.COVERALLS_SERVICE_NAME = "SERVICE_NAME"; - process.env.COVERALLS_SERVICE_JOB_ID = "SERVICE_JOB_ID"; - process.env.COVERALLS_REPO_TOKEN = "REPO_TOKEN"; - process.env.CI_PULL_REQUEST = "https://github.com/fake/fake/pulls/123"; - process.env.COVERALLS_PARALLEL = "true"; - - getOptions(function(err, options){ - var lcovpath = path.join(__dirname, "/../fixtures/onefile.lcov"); - var input = fs.readFileSync(lcovpath, "utf8"); - var libpath = "fixtures/lib"; + process.env.COVERALLS_GIT_COMMIT = 'GIT_HASH'; + process.env.COVERALLS_GIT_BRANCH = 'master'; + process.env.COVERALLS_SERVICE_NAME = 'SERVICE_NAME'; + process.env.COVERALLS_SERVICE_JOB_ID = 'SERVICE_JOB_ID'; + process.env.COVERALLS_REPO_TOKEN = 'REPO_TOKEN'; + process.env.CI_PULL_REQUEST = 'https://github.com/fake/fake/pulls/123'; + process.env.COVERALLS_PARALLEL = 'true'; + + getOptions((err, options) => { + const lcovpath = path.join(__dirname, '/../fixtures/onefile.lcov'); + const input = fs.readFileSync(lcovpath, 'utf8'); + const libpath = 'fixtures/lib'; + + should.not.exist(err); options.filepath = libpath; - convertLcovToCoveralls(input, options, function(err, output){ + convertLcovToCoveralls(input, options, (err, output) => { should.not.exist(err); - output.service_pull_request.should.equal("123"); + output.service_pull_request.should.equal('123'); output.parallel.should.equal(true); //output.git.should.equal("GIT_HASH"); done(); }); }); }); - it ("should work with a relative path as well", function(done){ + it('should work with a relative path as well', done => { delete process.env.TRAVIS; - var lcovpath = path.join(__dirname, "/../fixtures/onefile.lcov"); - var input = fs.readFileSync(lcovpath, "utf8"); - var libpath = "fixtures/lib"; - convertLcovToCoveralls(input, {filepath: libpath}, function(err, output){ + const lcovpath = path.join(__dirname, '/../fixtures/onefile.lcov'); + const input = fs.readFileSync(lcovpath, 'utf8'); + const libpath = 'fixtures/lib'; + convertLcovToCoveralls(input, { filepath: libpath }, (err, output) => { should.not.exist(err); - output.source_files[0].name.should.equal("index.js"); - output.source_files[0].source.split("\n").length.should.equal(173); + output.source_files[0].name.should.equal('index.js'); + output.source_files[0].source.split('\n').length.should.equal(173); done(); }); }); - it ("should convert absolute input paths to relative", function(done){ + it('should convert absolute input paths to relative', done => { delete process.env.TRAVIS; - var lcovpath = path.join(__dirname, "/../fixtures/istanbul.lcov"); - var input = fs.readFileSync(lcovpath, "utf8"); - var libpath = "/Users/deepsweet/Dropbox/projects/svgo/lib"; - var sourcepath = path.resolve(libpath, "svgo/config.js"); + const lcovpath = path.join(__dirname, '/../fixtures/istanbul.lcov'); + const input = fs.readFileSync(lcovpath, 'utf8'); + const libpath = '/Users/deepsweet/Dropbox/projects/svgo/lib'; + const sourcepath = path.resolve(libpath, 'svgo/config.js'); - var originalReadFileSync = fs.readFileSync; - fs.readFileSync = function(filepath) { + const originalReadFileSync = fs.readFileSync; + fs.readFileSync = (filepath, ...args) => { if (filepath === sourcepath) { return ''; } - return originalReadFileSync.apply(fs, arguments); + return originalReadFileSync.apply(fs, args); }; - var originalExistsSync = fs.existsSync; - fs.existsSync = function () { return true; }; + const originalExistsSync = fs.existsSync; + fs.existsSync = () => true; - convertLcovToCoveralls(input, {filepath: libpath}, function(err, output){ + convertLcovToCoveralls(input, { filepath: libpath }, (err, output) => { fs.readFileSync = originalReadFileSync; fs.existsSync = originalExistsSync; should.not.exist(err); - output.source_files[0].name.should.equal(path.posix.join("svgo", "config.js")); + output.source_files[0].name.should.equal(path.join("svgo", "config.js")); done(); }); }); - it ("should handle branch coverage data", function(done){ + it('should handle branch coverage data', done => { process.env.TRAVIS_JOB_ID = -1; - var lcovpath = path.join(__dirname, "/../fixtures/istanbul.lcov"); - var input = fs.readFileSync(lcovpath, "utf8"); - var libpath = "/Users/deepsweet/Dropbox/projects/svgo/lib"; - var sourcepath = path.resolve(libpath, "svgo/config.js"); + const lcovpath = path.join(__dirname, '/../fixtures/istanbul.lcov'); + const input = fs.readFileSync(lcovpath, 'utf8'); + const libpath = '/Users/deepsweet/Dropbox/projects/svgo/lib'; + const sourcepath = path.resolve(libpath, 'svgo/config.js'); - var originalReadFileSync = fs.readFileSync; - fs.readFileSync = function(filepath) { + const originalReadFileSync = fs.readFileSync; + fs.readFileSync = (filepath, ...args) => { if (filepath === sourcepath) { return ''; } - return originalReadFileSync.apply(fs, arguments); + return originalReadFileSync.apply(fs, args); }; - var originalExistsSync = fs.existsSync; - fs.existsSync = function () { return true; }; + const originalExistsSync = fs.existsSync; + fs.existsSync = () => true; - convertLcovToCoveralls(input, {filepath: libpath}, function(err, output){ + convertLcovToCoveralls(input, { filepath: libpath }, (err, output) => { fs.readFileSync = originalReadFileSync; fs.existsSync = originalExistsSync; - + should.not.exist(err); - output.source_files[0].branches.slice(0,8).should.eql([18,1,0,85,18,1,1,2]); + output.source_files[0].branches.slice(0, 8).should.eql([18, 1, 0, 85, 18, 1, 1, 2]); done(); }); }); - it ("should ignore files that do not exists", function(done){ + it('should ignore files that do not exists', done => { delete process.env.TRAVIS; - var lcovpath = path.join(__dirname, "/../fixtures/istanbul.lcov"); - var input = fs.readFileSync(lcovpath, "utf8"); - var libpath = "/Users/deepsweet/Dropbox/projects/svgo/lib"; - var sourcepath = path.resolve(libpath, "svgo/config.js"); + const lcovpath = path.join(__dirname, '/../fixtures/istanbul.lcov'); + const input = fs.readFileSync(lcovpath, 'utf8'); + const libpath = '/Users/deepsweet/Dropbox/projects/svgo/lib'; + const sourcepath = path.resolve(libpath, 'svgo/config.js'); - var originalReadFileSync = fs.readFileSync; - fs.readFileSync = function(filepath) { + const originalReadFileSync = fs.readFileSync; + fs.readFileSync = (filepath, ...args) => { if (filepath === sourcepath) { return ''; } - return originalReadFileSync.apply(fs, arguments); + return originalReadFileSync.apply(fs, args); }; - var originalExistsSync = fs.existsSync; - fs.existsSync = function () { return false; }; + const originalExistsSync = fs.existsSync; + fs.existsSync = () => false; - convertLcovToCoveralls(input, {filepath: libpath}, function(err, output){ + convertLcovToCoveralls(input, { filepath: libpath }, (err, output) => { fs.readFileSync = originalReadFileSync; fs.existsSync = originalExistsSync; @@ -146,33 +150,32 @@ describe("convertLcovToCoveralls", function(){ }); }); - it ("should parse file paths concatenated by typescript and ng 2", function(done) { + it('should parse file paths concatenated by typescript and ng 2', done => { process.env.TRAVIS_JOB_ID = -1; - var lcovpath = path.join(__dirname, "/../fixtures/istanbul.remap.lcov"); - var input = fs.readFileSync(lcovpath, "utf8"); - var libpath = "/Users/deepsweet/Dropbox/projects/svgo/lib"; - var sourcepath = path.resolve(libpath, "svgo/config.js"); + const lcovpath = path.join(__dirname, '/../fixtures/istanbul.remap.lcov'); + const input = fs.readFileSync(lcovpath, 'utf8'); + const libpath = '/Users/deepsweet/Dropbox/projects/svgo/lib'; + const sourcepath = path.resolve(libpath, 'svgo/config.js'); - var originalReadFileSync = fs.readFileSync; - fs.readFileSync = function(filepath) { + const originalReadFileSync = fs.readFileSync; + fs.readFileSync = (filepath, ...args) => { if (filepath === sourcepath) { return ''; } - return originalReadFileSync.apply(fs, arguments); + return originalReadFileSync.apply(fs, args); }; - var originalExistsSync = fs.existsSync; - fs.existsSync = function () { return true; }; + const originalExistsSync = fs.existsSync; + fs.existsSync = () => true; - convertLcovToCoveralls(input, {filepath: libpath}, function(err, output){ + convertLcovToCoveralls(input, { filepath: libpath }, (err, output) => { fs.readFileSync = originalReadFileSync; fs.existsSync = originalExistsSync; should.not.exist(err); - output.source_files[0].name.should.equal(path.posix.join("svgo", "config.js")); + output.source_files[0].name.should.equal(path.join('svgo', 'config.js')); done(); }); }); - }); diff --git a/test/detectLocalGit.js b/test/detectLocalGit.js index bc3158c..5a6fc7d 100644 --- a/test/detectLocalGit.js +++ b/test/detectLocalGit.js @@ -1,71 +1,67 @@ -var should = require('should'); -var fs = require('fs'); -var path = require('path'); +'use strict'; -var detectLocalGit = require('../lib/detectLocalGit'); +const fs = require('fs'); +const path = require('path'); +const should = require('should'); -var ORIGINAL_CWD = process.cwd(); -var TEST_DIR = path.resolve(__dirname); -var TEMP_GIT_DIR = path.join(TEST_DIR, '.git'); +const detectLocalGit = require('../lib/detectLocalGit'); -describe("detectLocalGit", function() { +const ORIGINAL_CWD = process.cwd(); +const TEST_DIR = path.resolve(__dirname); +const TEMP_GIT_DIR = path.join(TEST_DIR, '.git'); - before(function() { - _makeTempGitDir(); - process.chdir(TEST_DIR); - }); - - after(function() { - _cleanTempGitDir(); - process.chdir(ORIGINAL_CWD); - }); +describe('detectLocalGit', () => { + before(() => { + _makeTempGitDir(); + process.chdir(TEST_DIR); + }); - it('should get commit hash from packed-refs when refs/heads/master does not exist', function() { - var results = detectLocalGit(); - should.exist(results); - (results).should.deepEqual({ - git_commit: '0000000000000000ffffffffffffffffffffffff', - git_branch: 'master' - }); + after(() => { + _cleanTempGitDir(); + process.chdir(ORIGINAL_CWD); + }); + + it('should get commit hash from packed-refs when refs/heads/master does not exist', () => { + const results = detectLocalGit(); + should.exist(results); + (results).should.deepEqual({ + git_commit: '0000000000000000ffffffffffffffffffffffff', + git_branch: 'master' }); - + }); }); function _makeTempGitDir() { + _cleanTempGitDir(); - _cleanTempGitDir(); - - var dir = TEMP_GIT_DIR; - - fs.mkdirSync(dir); + const dir = TEMP_GIT_DIR; - var HEAD = path.join(dir, 'HEAD'); - var packedRefs = path.join(dir, 'packed-refs'); + fs.mkdirSync(dir); - fs.writeFileSync(HEAD, 'ref: refs/heads/master'); - fs.writeFileSync(packedRefs, "" + -"# pack-refs with: peeled fully-peeled\n" + -"0000000000000000000000000000000000000000 refs/heads/other/ref\n" + -"0000000000000000ffffffffffffffffffffffff refs/heads/master\n" + -"ffffffffffffffffffffffffffffffffffffffff refs/remotes/origin/other\n"); + const HEAD = path.join(dir, 'HEAD'); + const packedRefs = path.join(dir, 'packed-refs'); + fs.writeFileSync(HEAD, 'ref: refs/heads/master'); + fs.writeFileSync(packedRefs, '' + +'# pack-refs with: peeled fully-peeled\n' + +'0000000000000000000000000000000000000000 refs/heads/other/ref\n' + +'0000000000000000ffffffffffffffffffffffff refs/heads/master\n' + +'ffffffffffffffffffffffffffffffffffffffff refs/remotes/origin/other\n'); } function _cleanTempGitDir() { - _deleteFolderRecursive(TEMP_GIT_DIR); + _deleteFolderRecursive(TEMP_GIT_DIR); } function _deleteFolderRecursive(dir) { - - if (!dir.includes(path.normalize('node-coveralls/test'))) { - throw new Error('Tried to clean a temp git directory that did not match path: ' + path.normalize('node-coveralls/test')); + if (!dir.match('node-coveralls/test')) { + throw new Error('Tried to clean a temp git directory that did not match path: node-coveralls/test'); } - if(fs.existsSync(dir)) { - - fs.readdirSync(dir).forEach(function(file,index){ - var curPath = path.join(dir, file); - if(fs.lstatSync(curPath).isDirectory()) { // recurse + if (fs.existsSync(dir)) { + fs.readdirSync(dir).forEach(file => { + const curPath = path.join(dir, file); + if (fs.lstatSync(curPath).isDirectory()) { // recurse _deleteFolderRecursive(curPath); } else { // delete file fs.unlinkSync(curPath); diff --git a/test/fetchGitData.js b/test/fetchGitData.js index 012e129..f15b179 100644 --- a/test/fetchGitData.js +++ b/test/fetchGitData.js @@ -1,179 +1,189 @@ -var should = require('should'); -var fetchGitData = require('../lib/fetchGitData'); -var getOptions = require('../index').getOptions; +'use strict'; -describe("fetchGitData", function(){ - beforeEach(function(){ - process.env = {PATH: process.env.PATH}; +const should = require('should'); +const fetchGitData = require('../lib/fetchGitData'); +const { getOptions } = require('..'); + +describe('fetchGitData', () => { + beforeEach(() => { + process.env = { PATH: process.env.PATH }; }); - it("should throw an error when no data is passed", function() { + it('should throw an error when no data is passed', () => { fetchGitData.should.throw(/fetchGitData requires a callback/); }); - it('should throw an error when no git context is provided', function(done) { - fetchGitData(undefined, function(err){ + it('should throw an error when no git context is provided', done => { + fetchGitData(undefined, err => { err.should.match(/No options passed/); done(); }); }); - it("should throw an error if no head is provided", function(done) { + it('should throw an error if no head is provided', done => { fetchGitData({ - }, function(err){ + }, err => { err.should.match(/You must provide the head/); done(); }); }); - it("should throw an error if no head.id is provided", function(done) { + it('should throw an error if no head.id is provided', done => { fetchGitData({ head: {} - }, function(err){ + }, err => { err.should.match(/You must provide the head.id/); done(); }); }); - it("should return default values", function(done) { - var options = fetchGitData({ + it('should return default values', done => { + fetchGitData({ head: { - id: "COMMIT_HASH" + id: 'COMMIT_HASH' } - }, function(err, options){ + }, (err, options) => { + should.not.exist(err); options.should.eql({ - "head": { - "id": "COMMIT_HASH", - "author_name": "Unknown Author", - "author_email": "", - "committer_name": "Unknown Committer", - "committer_email": "", - "message": "Unknown Commit Message" + 'head': { + 'id': 'COMMIT_HASH', + 'author_name': 'Unknown Author', + 'author_email': '', + 'committer_name': 'Unknown Committer', + 'committer_email': '', + 'message': 'Unknown Commit Message' }, - "branch": "", - "remotes": [] + 'branch': '', + 'remotes': [] }); done(); }); }); - it("should override default values", function(done) { - var options = fetchGitData({ - "head": { - "id": "COMMIT_HASH", - "author_name": "MY AUTHOR", - "author_email": "", - "committer_name": "MY COMMITTER", - "committer_email": "", - "message": "MY COMMIT MESSAGE" + it('should override default values', done => { + fetchGitData({ + 'head': { + 'id': 'COMMIT_HASH', + 'author_name': 'MY AUTHOR', + 'author_email': '', + 'committer_name': 'MY COMMITTER', + 'committer_email': '', + 'message': 'MY COMMIT MESSAGE' }, - "branch": "TEST", - "remotes": [ + 'branch': 'TEST', + 'remotes': [ { - "name": "TEST", - "url": "test-url" + 'name': 'TEST', + 'url': 'test-url' } ] - }, function(err, options){ + }, (err, options) => { + should.not.exist(err); options.should.eql({ - "head": { - "id": "COMMIT_HASH", - "author_name": "MY AUTHOR", - "author_email": "", - "committer_name": "MY COMMITTER", - "committer_email": "", - "message": "MY COMMIT MESSAGE" + 'head': { + 'id': 'COMMIT_HASH', + 'author_name': 'MY AUTHOR', + 'author_email': '', + 'committer_name': 'MY COMMITTER', + 'committer_email': '', + 'message': 'MY COMMIT MESSAGE' }, - "branch": "TEST", - "remotes": [ + 'branch': 'TEST', + 'remotes': [ { - "name": "TEST", - "url": "test-url" + 'name': 'TEST', + 'url': 'test-url' } ] }); done(); }); }); - it("should convert git.branch to a string", function(done) { + it('should convert git.branch to a string', done => { fetchGitData({ - "head": { - "id": "COMMIT_HASH" + 'head': { + 'id': 'COMMIT_HASH' }, - "branch": { - "covert": "to a string" + 'branch': { + 'covert': 'to a string' } - }, function(err, str){ + }, (err, str) => { + should.not.exist(err); str.branch.should.be.String(); fetchGitData({ - "head": { - "id": "COMMIT_HASH" + 'head': { + 'id': 'COMMIT_HASH' }, - "branch": ["convert", "to", "a", "string"] - }, function(err, str){ + 'branch': ['convert', 'to', 'a', 'string'] + }, (err, str) => { + should.not.exist(err); str.branch.should.be.String(); done(); }); }); }); - it("should convert git.remotes to an array", function(done) { + it('should convert git.remotes to an array', done => { fetchGitData({ - "head": { - "id": "COMMIT_HASH" + 'head': { + 'id': 'COMMIT_HASH' }, - "remotes": "convert from string to an array" - }, function(err, arr){ + 'remotes': 'convert from string to an array' + }, (err, arr) => { + should.not.exist(err); arr.remotes.should.be.instanceof(Array); fetchGitData({ - "head": { - "id": "COMMIT_HASH" + 'head': { + 'id': 'COMMIT_HASH' }, - "remotes": { - "convert": "from object to an array" + 'remotes': { + 'convert': 'from object to an array' } - }, function(err, arr){ + }, (err, arr) => { + should.not.exist(err); arr.remotes.should.be.instanceof(Array); done(); }); }); }); - it("should save passed remotes", function(done) { + it('should save passed remotes', done => { fetchGitData({ - "head": { - "id": "COMMIT_HASH" + 'head': { + 'id': 'COMMIT_HASH' }, - "remotes": [ + 'remotes': [ { - "name": "test", - "url": "https://my.test.url" + 'name': 'test', + 'url': 'https://my.test.url' } ] - }, function(err, options){ + }, (err, options) => { + should.not.exist(err); options.should.eql({ - "head": { - "id": "COMMIT_HASH", - "author_name": "Unknown Author", - "author_email": "", - "committer_name": "Unknown Committer", - "committer_email": "", - "message": "Unknown Commit Message" + 'head': { + 'id': 'COMMIT_HASH', + 'author_name': 'Unknown Author', + 'author_email': '', + 'committer_name': 'Unknown Committer', + 'committer_email': '', + 'message': 'Unknown Commit Message' }, - "branch": "", - "remotes": [ + 'branch': '', + 'remotes': [ { - "name": "test", - "url": "https://my.test.url" + 'name': 'test', + 'url': 'https://my.test.url' } ] }); done(); }); }); - it("should execute git commands when a valid commit hash is given", function(done) { - process.env.COVERALLS_GIT_COMMIT = "HEAD"; - process.env.COVERALLS_GIT_BRANCH = "master"; - getOptions(function(err, options){ + it('should execute git commands when a valid commit hash is given', done => { + process.env.COVERALLS_GIT_COMMIT = 'HEAD'; + process.env.COVERALLS_GIT_BRANCH = 'master'; + getOptions((err, options) => { + should.not.exist(err); options = options.git; options.head.should.be.Object(); - options.head.author_name.should.not.equal("Unknown Author"); - options.head.committer_name.should.not.equal("Unknown Committer"); - options.head.message.should.not.equal("Unknown Commit Message"); + options.head.author_name.should.not.equal('Unknown Author'); + options.head.committer_name.should.not.equal('Unknown Committer'); + options.head.message.should.not.equal('Unknown Commit Message'); options.branch.should.be.String(); - options.should.have.property("remotes"); + options.should.have.property('remotes'); options.remotes.should.be.instanceof(Array); options.remotes.length.should.be.above(0); done(); diff --git a/test/getOptions.js b/test/getOptions.js index e79abc7..8e9e758 100644 --- a/test/getOptions.js +++ b/test/getOptions.js @@ -1,608 +1,706 @@ -var should = require('should'); -var index = require('../index'); -var getOptions = index.getOptions; -var getBaseOptions = index.getBaseOptions; +'use strict'; -describe("getBaseOptions", function(){ - beforeEach(function(){ - process.env = {PATH: process.env.PATH}; +const fs = require('fs'); +const path = require('path'); +const should = require('should'); +const yaml = require('js-yaml'); +const index = require('..'); + +const { getOptions, getBaseOptions } = index; + +describe('getBaseOptions', () => { + beforeEach(() => { + process.env = { PATH: process.env.PATH }; }); - it ("should set service_job_id if it exists", function(done){ + it('should set service_job_id if it exists', done => { testServiceJobId(getBaseOptions, done); }); - it ("should set git hash if it exists", function(done){ + it('should set git hash if it exists', done => { testGitHash(getBaseOptions, done); }); - it ("should set git branch if it exists", function(done){ + it('should set git branch if it exists', done => { testGitBranch(getBaseOptions, done); }); - it ("should detect current git hash if not passed in", function(done) { + it('should detect current git hash if not passed in', done => { testGitHashDetection(getBaseOptions, done); }); - it ("should detect current git branch if not passed in", function(done) { + it('should detect current git branch if not passed in', done => { testGitBranchDetection(getBaseOptions, done); }); - it ("should detect detached git head if no hash passed in", function(done) { + it('should detect detached git head if no hash passed in', done => { testGitDetachedHeadDetection(getBaseOptions, done); }); - it ("should fail local Git detection if no .git directory", function(done) { + it('should fail local Git detection if no .git directory', done => { testNoLocalGit(getBaseOptions, done); }); - it ("should set repo_token if it exists", function(done){ + it('should set repo_token if it exists', done => { testRepoToken(getBaseOptions, done); }); - it ("should detect repo_token if not passed in", function(done){ + it('should detect repo_token if not passed in', done => { testRepoTokenDetection(getBaseOptions, done); }); - it ("should set service_name if it exists", function(done){ + it('should set service_name if it exists', done => { testServiceName(getBaseOptions, done); }); - it ("should set service_name and service_job_id if it's running on travis-ci", function(done){ + it('should set service_name and service_job_id if it\'s running on travis-ci', done => { testTravisCi(getBaseOptions, done); }); - it ("should set service_name and service_job_id if it's running on jenkins", function(done){ + it('should set service_name and service_job_id if it\'s running on jenkins', done => { testJenkins(getBaseOptions, done); }); - it ("should set service_name and service_job_id if it's running on circleci", function(done){ + it('should set service_name and service_job_id if it\'s running on circleci', done => { testCircleCi(getBaseOptions, done); }); - it ("should set service_name and service_job_id if it's running on codeship", function(done){ + it('should set service_name and service_job_id if it\'s running on codeship', done => { testCodeship(getBaseOptions, done); }); - it ("should set service_name and service_job_id if it's running on drone", function(done){ + it('should set service_name and service_job_id if it\'s running on drone', done => { testDrone(getBaseOptions, done); }); - it ("should set service_name and service_job_id if it's running on wercker", function(done){ + it('should set service_name and service_job_id if it\'s running on wercker', done => { testWercker(getBaseOptions, done); }); - it ("should set service_name and service_job_id if it's running on Buildkite", function(done){ + it('should set service_name and service_job_id if it\'s running on Buildkite', done => { testBuildkite(getBaseOptions, done); }); - it ("should set service_name and service_job_id if it's running on Azure Pipelines", function(done){ + it('should set service_name and service_job_id if it\'s running on Azure Pipelines', done => { testAzurePipelines(getBaseOptions, done); }); }); -describe("getOptions", function(){ - beforeEach(function(){ - process.env = {PATH: process.env.PATH}; +describe('getOptions', () => { + beforeEach(() => { + process.env = { PATH: process.env.PATH }; }); - it ("should require a callback", function(done) { - (function() { + it('should require a callback', done => { + ((() => { getOptions(); - }).should.throw(); + })).should.throw(); done(); }); - it ("should get a filepath if there is one", function(done){ - index.options._ = ["somepath"]; - getOptions(function(err, options){ - options.filepath.should.equal("somepath"); + it('should get a filepath if there is one', done => { + index.options._ = ['somepath']; + getOptions((err, options) => { + should.not.exist(err); + options.filepath.should.equal('somepath'); done(); }); - }); - it ("should get a filepath if there is one, even in verbose mode", function(done){ - index.options.verbose = "true"; - index.options._ = ["somepath"]; - getOptions(function(err, options){ - options.filepath.should.equal("somepath"); + it('should get a filepath if there is one, even in verbose mode', done => { + index.options.verbose = 'true'; + index.options._ = ['somepath']; + getOptions((err, options) => { + should.not.exist(err); + options.filepath.should.equal('somepath'); done(); }); }); - it ("should set service_job_id if it exists", function(done){ + it('should set service_job_id if it exists', done => { testServiceJobId(getOptions, done); }); - it ("should set git hash if it exists", function(done){ + it('should set git hash if it exists', done => { testGitHash(getOptions, done); }); - it ("should set git branch if it exists", function(done){ + it('should set git branch if it exists', done => { testGitBranch(getOptions, done); }); - it ("should detect current git hash if not passed in", function(done) { + it('should detect current git hash if not passed in', done => { testGitHashDetection(getOptions, done); }); - it ("should detect current git branch if not passed in", function(done) { + it('should detect current git branch if not passed in', done => { testGitBranchDetection(getOptions, done); }); - it ("should detect detached git head if no hash passed in", function(done) { + it('should detect detached git head if no hash passed in', done => { testGitDetachedHeadDetection(getOptions, done); }); - it ("should fail local Git detection if no .git directory", function(done) { + it('should fail local Git detection if no .git directory', done => { testNoLocalGit(getOptions, done); }); - it ("should set repo_token if it exists", function(done){ + it('should set repo_token if it exists', done => { testRepoToken(getOptions, done); }); - it ("should detect repo_token if not passed in", function(done){ + it('should detect repo_token if not passed in', done => { testRepoTokenDetection(getOptions, done); }); - it ("should set paralell if env var set", function(done){ + it('should set paralell if env let set', done => { testParallel(getOptions, done); }); - it ("should set flag_name if it exists", function(done) { + it('should set flag_name if it exists', done => { testFlagName(getOptions, done); }); - it ("should set service_name if it exists", function(done){ + it('should set service_name if it exists', done => { testServiceName(getOptions, done); }); - it("should set service_pull_request if it exists", function(done){ + it('should set service_pull_request if it exists', done => { testServicePullRequest(getOptions, done); }); - it ("should set service_name and service_job_id if it's running on travis-ci", function(done){ + it('should set service_name and service_job_id if it\'s running on travis-ci', done => { testTravisCi(getOptions, done); }); - it ("should set service_name and service_job_id if it's running on jenkins", function(done){ + it('should set service_name and service_job_id if it\'s running on jenkins', done => { testJenkins(getOptions, done); }); - it ("should set service_name and service_job_id if it's running on circleci", function(done){ + it('should set service_name and service_job_id if it\'s running on circleci', done => { testCircleCi(getOptions, done); }); - it ("should set service_name and service_job_id if it's running on codeship", function(done){ + it('should set service_name and service_job_id if it\'s running on codeship', done => { testCodeship(getOptions, done); }); - it ("should set service_name and service_job_id if it's running on drone", function(done){ + it('should set service_name and service_job_id if it\'s running on drone', done => { testDrone(getBaseOptions, done); }); - it ("should set service_name and service_job_id if it's running on wercker", function(done){ + it('should set service_name and service_job_id if it\'s running on wercker', done => { testWercker(getOptions, done); }); - it ("should set service_name and service_job_id if it's running on Gitlab", function(done){ + it('should set service_name and service_job_id if it\'s running on Gitlab', done => { testGitlab(getOptions, done); }); - it ("should set service_name and service_job_id if it's running via Surf", function(done){ + it('should set service_name and service_job_id if it\'s running via Surf', done => { testSurf(getOptions, done); }); - it ("should set service_name and service_job_id if it's running via Buildkite", function(done){ + it('should set service_name and service_job_id if it\'s running via Buildkite', done => { testBuildkite(getOptions, done); }); - it ("should set service_name and service_job_id if it's running via Semaphore", function(done){ + it('should set service_name and service_job_id if it\'s running via Semaphore', done => { testSemaphore(getOptions, done); }); - it ("should set service_name and service_job_id if it's running via Azure Pipelines", function(done){ + it('should set service_name and service_job_id if it\'s running via Azure Pipelines', done => { testAzurePipelines(getOptions, done); }); - it ("should override set options with user options", function(done){ - var userOptions = {service_name: 'OVERRIDDEN_SERVICE_NAME'}; - process.env.COVERALLS_SERVICE_NAME = "SERVICE_NAME"; - getOptions(function(err, options){ - options.service_name.should.equal("OVERRIDDEN_SERVICE_NAME"); + it('should override set options with user options', done => { + const userOptions = { service_name: 'OVERRIDDEN_SERVICE_NAME' }; + process.env.COVERALLS_SERVICE_NAME = 'SERVICE_NAME'; + getOptions((err, options) => { + should.not.exist(err); + options.service_name.should.equal('OVERRIDDEN_SERVICE_NAME'); done(); }, userOptions); }); }); -var testServiceJobId = function(sut, done){ - process.env.COVERALLS_SERVICE_JOB_ID = "SERVICE_JOB_ID"; - sut(function(err, options){ - options.service_job_id.should.equal("SERVICE_JOB_ID"); - done(); - }); +const testServiceJobId = (sut, done) => { + process.env.COVERALLS_SERVICE_JOB_ID = 'SERVICE_JOB_ID'; + sut((err, options) => { + should.not.exist(err); + options.service_job_id.should.equal('SERVICE_JOB_ID'); + done(); + }); }; -var testGitHash = function(sut, done){ - process.env.COVERALLS_GIT_COMMIT = "e3e3e3e3e3e3e3e3e"; - sut(function(err, options){ - options.git.head.id.should.equal("e3e3e3e3e3e3e3e3e"); +const testGitHash = (sut, done) => { + process.env.COVERALLS_GIT_COMMIT = 'e3e3e3e3e3e3e3e3e'; + sut((err, options) => { + should.not.exist(err); + options.git.head.id.should.equal('e3e3e3e3e3e3e3e3e'); done(); }); }; -var testGitDetachedHeadDetection = function(sut, done){ - var localGit = ensureLocalGitContext({ detached: true }); - sut(function(err, options) { +const testGitDetachedHeadDetection = (sut, done) => { + const localGit = ensureLocalGitContext({ detached: true }); + sut((err, options) => { + should.not.exist(err); options.git.head.id.should.equal(localGit.id); localGit.wrapUp(); done(); }); }; -var testGitHashDetection = function(sut, done){ - var localGit = ensureLocalGitContext(); - sut(function(err, options) { +const testGitHashDetection = (sut, done) => { + const localGit = ensureLocalGitContext(); + sut((err, options) => { + should.not.exist(err); options.git.head.id.should.equal(localGit.id); localGit.wrapUp(); done(); }); }; -var testGitBranch = function(sut, done){ - process.env.COVERALLS_GIT_COMMIT = "e3e3e3e3e3e3e3e3e"; - process.env.COVERALLS_GIT_BRANCH = "master"; - sut(function(err, options){ - options.git.branch.should.equal("master"); +const testGitBranch = (sut, done) => { + process.env.COVERALLS_GIT_COMMIT = 'e3e3e3e3e3e3e3e3e'; + process.env.COVERALLS_GIT_BRANCH = 'master'; + sut((err, options) => { + should.not.exist(err); + options.git.branch.should.equal('master'); done(); }); }; -var testGitBranchDetection = function(sut, done){ - var localGit = ensureLocalGitContext(); - sut(function(err, options) { - if (localGit.branch) +const testGitBranchDetection = (sut, done) => { + const localGit = ensureLocalGitContext(); + sut((err, options) => { + should.not.exist(err); + + if (localGit.branch) { options.git.branch.should.equal(localGit.branch); - else + } else { options.git.should.not.have.key('branch'); + } + localGit.wrapUp(); done(); }); }; -var testNoLocalGit = function(sut, done){ - var localGit = ensureLocalGitContext({ noGit: true }); - sut(function(err, options) { +const testNoLocalGit = (sut, done) => { + const localGit = ensureLocalGitContext({ noGit: true }); + sut((err, options) => { + should.not.exist(err); options.should.not.have.property('git'); localGit.wrapUp(); done(); }); }; -var testRepoToken = function(sut, done){ - process.env.COVERALLS_REPO_TOKEN = "REPO_TOKEN"; - sut(function(err, options){ - options.repo_token.should.equal("REPO_TOKEN"); +const testRepoToken = (sut, done) => { + process.env.COVERALLS_REPO_TOKEN = 'REPO_TOKEN'; + sut((err, options) => { + should.not.exist(err); + options.repo_token.should.equal('REPO_TOKEN'); done(); }); }; -var testParallel = function(sut, done){ - process.env.COVERALLS_PARALLEL = "true"; - sut(function(err, options){ +const testParallel = (sut, done) => { + process.env.COVERALLS_PARALLEL = 'true'; + sut((err, options) => { + should.not.exist(err); options.parallel.should.equal(true); done(); }); }; -var testFlagName = function(sut, done){ +const testFlagName = (sut, done) => { process.env.COVERALLS_FLAG_NAME = 'test flag'; - sut(function(err, options){ + sut((err, options) => { + should.not.exist(err); options.flag_name.should.equal('test flag'); done(); }); }; -var testRepoTokenDetection = function(sut, done) { - var fs = require('fs'); - var path = require('path'); +const testRepoTokenDetection = (sut, done) => { + const file = path.join(process.cwd(), '.coveralls.yml'); + let token; + let service_name; + let synthetic = false; - var file = path.join(process.cwd(), '.coveralls.yml'), token, service_name, synthetic = false; if (fs.existsSync(file)) { - var yaml = require('js-yaml'); - var coveralls_yml_doc = yaml.safeLoad(fs.readFileSync(yml, 'utf8')); - token = coveralls_yml_doc.repo_token; - if(coveralls_yml_doc.service_name) { - service_name = coveralls_yml_doc.service_name; + const coverallsYmlDoc = yaml.safeLoad(fs.readFileSync(file, 'utf8')); + token = coverallsYmlDoc.repo_token; + if (coverallsYmlDoc.service_name) { + service_name = coverallsYmlDoc.service_name; } } else { token = 'REPO_TOKEN'; service_name = 'travis-pro'; - fs.writeFileSync(file, 'repo_token: ' + token+'\nservice_name: ' + service_name); + fs.writeFileSync(file, `repo_token: ${token}\nservice_name: ${service_name}`); synthetic = true; } - sut(function(err, options) { + + sut((err, options) => { + should.not.exist(err); options.repo_token.should.equal(token); - if(service_name) { + + if (service_name) { options.service_name.should.equal(service_name); } - if (synthetic) + + if (synthetic) { fs.unlink(file, done); + } }); }; -var testServiceName = function(sut, done){ - process.env.COVERALLS_SERVICE_NAME = "SERVICE_NAME"; - sut(function(err, options){ - options.service_name.should.equal("SERVICE_NAME"); +const testServiceName = (sut, done) => { + process.env.COVERALLS_SERVICE_NAME = 'SERVICE_NAME'; + sut((err, options) => { + should.not.exist(err); + options.service_name.should.equal('SERVICE_NAME'); done(); }); }; -var testServicePullRequest = function(sut, done){ - process.env.CI_PULL_REQUEST = "https://github.com/fake/fake/pulls/123"; - sut(function(err, options){ - options.service_pull_request.should.equal("123"); +const testServicePullRequest = (sut, done) => { + process.env.CI_PULL_REQUEST = 'https://github.com/fake/fake/pulls/123'; + sut((err, options) => { + should.not.exist(err); + options.service_pull_request.should.equal('123'); done(); }); }; -var testTravisCi = function(sut, done){ - process.env.TRAVIS = "TRUE"; - process.env.TRAVIS_JOB_ID = "1234"; - process.env.TRAVIS_PULL_REQUEST = "123"; - sut(function(err, options){ - options.service_name.should.equal("travis-ci"); - options.service_job_id.should.equal("1234"); - options.service_pull_request.should.equal("123"); +const testTravisCi = (sut, done) => { + process.env.TRAVIS = 'TRUE'; + process.env.TRAVIS_JOB_ID = '1234'; + process.env.TRAVIS_PULL_REQUEST = '123'; + sut((err, options) => { + should.not.exist(err); + options.service_name.should.equal('travis-ci'); + options.service_job_id.should.equal('1234'); + options.service_pull_request.should.equal('123'); done(); }); }; -var testJenkins = function(sut, done){ - process.env.JENKINS_URL = "something"; - process.env.BUILD_ID = "1234"; - process.env.GIT_COMMIT = "a12s2d3df4f435g45g45g67h5g6"; - process.env.GIT_BRANCH = "master"; - sut(function(err, options){ - options.service_name.should.equal("jenkins"); - options.service_job_id.should.equal("1234"); - options.git.should.eql({ head: - { id: 'a12s2d3df4f435g45g45g67h5g6', - author_name: 'Unknown Author', - author_email: '', - committer_name: 'Unknown Committer', - committer_email: '', - message: 'Unknown Commit Message' }, - branch: 'master', - remotes: [] }); +const testJenkins = (sut, done) => { + process.env.JENKINS_URL = 'something'; + process.env.BUILD_ID = '1234'; + process.env.GIT_COMMIT = 'a12s2d3df4f435g45g45g67h5g6'; + process.env.GIT_BRANCH = 'master'; + + const git = { + head: { + id: 'a12s2d3df4f435g45g45g67h5g6', + author_name: 'Unknown Author', + author_email: '', + committer_name: 'Unknown Committer', + committer_email: '', + message: 'Unknown Commit Message' + }, + branch: 'master', + remotes: [] + }; + + sut((err, options) => { + should.not.exist(err); + options.service_name.should.equal('jenkins'); + options.service_job_id.should.equal('1234'); + options.git.should.eql(git); done(); }); }; -var testCircleCi = function(sut, done){ +const testCircleCi = (sut, done) => { process.env.CIRCLECI = true; - process.env.CIRCLE_BRANCH = "master"; - process.env.CIRCLE_BUILD_NUM = "1234"; - process.env.CIRCLE_SHA1 = "e3e3e3e3e3e3e3e3e"; + process.env.CIRCLE_BRANCH = 'master'; + process.env.CIRCLE_BUILD_NUM = '1234'; + process.env.CIRCLE_SHA1 = 'e3e3e3e3e3e3e3e3e'; process.env.CI_PULL_REQUEST = 'http://github.com/node-coveralls/pull/3'; - sut(function(err, options){ - options.service_name.should.equal("circleci"); - options.service_job_id.should.equal("1234"); + + const git = { + head: { + id: 'e3e3e3e3e3e3e3e3e', + author_name: 'Unknown Author', + author_email: '', + committer_name: 'Unknown Committer', + committer_email: '', + message: 'Unknown Commit Message' + }, + branch: 'master', + remotes: [] + }; + + sut((err, options) => { + should.not.exist(err); + options.service_name.should.equal('circleci'); + options.service_job_id.should.equal('1234'); options.service_pull_request.should.equal('3'); - options.git.should.eql({ head: - { id: 'e3e3e3e3e3e3e3e3e', - author_name: 'Unknown Author', - author_email: '', - committer_name: 'Unknown Committer', - committer_email: '', - message: 'Unknown Commit Message' }, - branch: 'master', - remotes: [] }); + options.git.should.eql(git); done(); }); }; -var testCodeship = function(sut, done) { +const testCodeship = (sut, done) => { process.env.CI_NAME = 'codeship'; process.env.CI_BUILD_NUMBER = '1234'; - process.env.CI_COMMIT_ID = "e3e3e3e3e3e3e3e3e"; - process.env.CI_BRANCH = "master"; - process.env.CI_COMMITTER_NAME = "John Doe"; - process.env.CI_COMMITTER_EMAIL = "jd@example.com"; - process.env.CI_COMMIT_MESSAGE = "adadadadadadadadadad"; - sut(function(err, options){ - options.service_name.should.equal("codeship"); - options.service_job_id.should.equal("1234"); - options.git.should.eql({ head: - { id: 'e3e3e3e3e3e3e3e3e', - author_name: 'Unknown Author', - author_email: '', - committer_name: 'John Doe', - committer_email: 'jd@example.com', - message: 'adadadadadadadadadad' }, - branch: 'master', - remotes: [] }); + process.env.CI_COMMIT_ID = 'e3e3e3e3e3e3e3e3e'; + process.env.CI_BRANCH = 'master'; + process.env.CI_COMMITTER_NAME = 'John Doe'; + process.env.CI_COMMITTER_EMAIL = 'jd@example.com'; + process.env.CI_COMMIT_MESSAGE = 'adadadadadadadadadad'; + + const git = { + head: { + id: 'e3e3e3e3e3e3e3e3e', + author_name: 'Unknown Author', + author_email: '', + committer_name: 'John Doe', + committer_email: 'jd@example.com', + message: 'adadadadadadadadadad' + }, + branch: 'master', + remotes: [] + }; + + sut((err, options) => { + should.not.exist(err); + options.service_name.should.equal('codeship'); + options.service_job_id.should.equal('1234'); + options.git.should.eql(git); done(); }); }; -var testDrone = function(sut, done) { +const testDrone = (sut, done) => { process.env.DRONE = true; process.env.DRONE_BUILD_NUMBER = '1234'; - process.env.DRONE_COMMIT = "e3e3e3e3e3e3e3e3e"; - process.env.DRONE_BRANCH = "master"; + process.env.DRONE_COMMIT = 'e3e3e3e3e3e3e3e3e'; + process.env.DRONE_BRANCH = 'master'; process.env.DRONE_PULL_REQUEST = '3'; process.env.DRONE_COMMIT_AUTHOR = 'john doe'; process.env.DRONE_COMMIT_AUTHOR_EMAIL = 'john@doe.com'; process.env.DRONE_COMMIT_MESSAGE = 'msgmsgmsg'; - sut(function(err, options){ - options.service_name.should.equal("drone"); - options.service_job_id.should.equal("1234"); - options.git.should.eql({ head: - { id: 'e3e3e3e3e3e3e3e3e', - author_name: 'Unknown Author', - author_email: '', - committer_name: 'john doe', - committer_email: 'john@doe.com', - message: 'msgmsgmsg' }, - branch: 'master', - remotes: [] }); + const git = { + head: { + id: 'e3e3e3e3e3e3e3e3e', + author_name: 'Unknown Author', + author_email: '', + committer_name: 'john doe', + committer_email: 'john@doe.com', + message: 'msgmsgmsg' + }, + branch: 'master', + remotes: [] + }; + + sut((err, options) => { + should.not.exist(err); + options.service_name.should.equal('drone'); + options.service_job_id.should.equal('1234'); + options.git.should.eql(git); done(); }); }; -var testWercker = function(sut, done) { +const testWercker = (sut, done) => { process.env.WERCKER = true; process.env.WERCKER_BUILD_ID = '1234'; - process.env.WERCKER_GIT_COMMIT = "e3e3e3e3e3e3e3e3e"; - process.env.WERCKER_GIT_BRANCH = "master"; - sut(function(err, options){ - options.service_name.should.equal("wercker"); - options.service_job_id.should.equal("1234"); - options.git.should.eql({ head: - { id: 'e3e3e3e3e3e3e3e3e', - author_name: 'Unknown Author', - author_email: '', - committer_name: 'Unknown Committer', - committer_email: '', - message: 'Unknown Commit Message' }, - branch: 'master', - remotes: [] }); + process.env.WERCKER_GIT_COMMIT = 'e3e3e3e3e3e3e3e3e'; + process.env.WERCKER_GIT_BRANCH = 'master'; + + const git = { + head: { + id: 'e3e3e3e3e3e3e3e3e', + author_name: 'Unknown Author', + author_email: '', + committer_name: 'Unknown Committer', + committer_email: '', + message: 'Unknown Commit Message' + }, + branch: 'master', + remotes: [] + }; + + sut((err, options) => { + should.not.exist(err); + options.service_name.should.equal('wercker'); + options.service_job_id.should.equal('1234'); + options.git.should.eql(git); done(); }); }; -var testGitlab = function(sut, done) { +const testGitlab = (sut, done) => { process.env.GITLAB_CI = true; process.env.CI_BUILD_NAME = 'spec:one'; - process.env.CI_BUILD_ID = "1234"; - process.env.CI_BUILD_REF = "e3e3e3e3e3e3e3e3e"; - process.env.CI_BUILD_REF_NAME = "feature"; - process.env.CI_MERGE_REQUEST_IID = "1"; - sut(function(err, options){ - options.service_name.should.equal("gitlab-ci"); - options.service_job_id.should.equal("1234"); - options.service_pull_request.should.equal("1"); - options.git.should.eql({ head: - { id: 'e3e3e3e3e3e3e3e3e', - author_name: 'Unknown Author', - author_email: '', - committer_name: 'Unknown Committer', - committer_email: '', - message: 'Unknown Commit Message' }, - branch: 'feature', - remotes: [] }); + process.env.CI_BUILD_ID = '1234'; + process.env.CI_BUILD_REF = 'e3e3e3e3e3e3e3e3e'; + process.env.CI_BUILD_REF_NAME = 'feature'; + process.env.CI_MERGE_REQUEST_IID = '1'; + + const git = { + head: { + id: 'e3e3e3e3e3e3e3e3e', + author_name: 'Unknown Author', + author_email: '', + committer_name: 'Unknown Committer', + committer_email: '', + message: 'Unknown Commit Message' + }, + branch: 'feature', + remotes: [] + }; + + sut((err, options) => { + should.not.exist(err); + options.service_name.should.equal('gitlab-ci'); + options.service_job_id.should.equal('1234'); + options.service_pull_request.should.equal('1'); + options.git.should.eql(git); done(); }); }; -var testSurf = function(sut, done) { +const testSurf = (sut, done) => { process.env.CI_NAME = 'surf'; - process.env.SURF_SHA1 = "e3e3e3e3e3e3e3e3e"; - process.env.SURF_REF = "feature"; - sut(function(err, options){ - options.service_name.should.equal("surf"); - options.git.should.eql({ head: - { id: 'e3e3e3e3e3e3e3e3e', - author_name: 'Unknown Author', - author_email: '', - committer_name: 'Unknown Committer', - committer_email: '', - message: 'Unknown Commit Message' }, - branch: 'feature', - remotes: [] }); + process.env.SURF_SHA1 = 'e3e3e3e3e3e3e3e3e'; + process.env.SURF_REF = 'feature'; + + const git = { + head: { + id: 'e3e3e3e3e3e3e3e3e', + author_name: 'Unknown Author', + author_email: '', + committer_name: 'Unknown Committer', + committer_email: '', + message: 'Unknown Commit Message' + }, + branch: 'feature', + remotes: [] + }; + + sut((err, options) => { + should.not.exist(err); + options.service_name.should.equal('surf'); + options.git.should.eql(git); done(); }); }; -var testBuildkite = function(sut, done) { +const testBuildkite = (sut, done) => { process.env.BUILDKITE = true; - process.env.BUILDKITE_BUILD_NUMBER = "1234"; - process.env.BUILDKITE_COMMIT = "e3e3e3e3e3e3e3e3e"; - process.env.BUILDKITE_BRANCH = "feature"; + process.env.BUILDKITE_BUILD_NUMBER = '1234'; + process.env.BUILDKITE_COMMIT = 'e3e3e3e3e3e3e3e3e'; + process.env.BUILDKITE_BRANCH = 'feature'; process.env.BUILDKITE_BUILD_CREATOR = 'john doe'; process.env.BUILDKITE_BUILD_CREATOR_EMAIL = 'john@doe.com'; process.env.BUILDKITE_MESSAGE = 'msgmsgmsg'; - sut(function(err, options){ - options.service_name.should.equal("buildkite"); - options.git.should.eql({ head: - { id: 'e3e3e3e3e3e3e3e3e', - author_name: 'Unknown Author', - author_email: '', - committer_name: 'john doe', - committer_email: 'john@doe.com', - message: 'msgmsgmsg' }, - branch: 'feature', - remotes: [] }); + + const git = { + head: { + id: 'e3e3e3e3e3e3e3e3e', + author_name: 'Unknown Author', + author_email: '', + committer_name: 'john doe', + committer_email: 'john@doe.com', + message: 'msgmsgmsg' + }, + branch: 'feature', + remotes: [] + }; + + sut((err, options) => { + should.not.exist(err); + options.service_name.should.equal('buildkite'); + options.git.should.eql(git); done(); }); }; - -var testSemaphore = function(sut, done) { +const testSemaphore = (sut, done) => { process.env.SEMAPHORE = true; process.env.SEMAPHORE_BUILD_NUMBER = '1234'; - process.env.REVISION = "e3e3e3e3e3e3e3e3e"; - process.env.BRANCH_NAME = "master"; - - sut(function(err, options){ - options.service_name.should.equal("semaphore"); - options.service_job_id.should.equal("1234"); - options.git.should.eql({ head: - { id: 'e3e3e3e3e3e3e3e3e', - author_name: 'Unknown Author', - author_email: '', - committer_name: 'Unknown Committer', - committer_email: '', - message: 'Unknown Commit Message' }, - branch: 'master', - remotes: [] }); + process.env.REVISION = 'e3e3e3e3e3e3e3e3e'; + process.env.BRANCH_NAME = 'master'; + + const git = { + head: { + id: 'e3e3e3e3e3e3e3e3e', + author_name: 'Unknown Author', + author_email: '', + committer_name: 'Unknown Committer', + committer_email: '', + message: 'Unknown Commit Message' + }, + branch: 'master', + remotes: [] + }; + + sut((err, options) => { + should.not.exist(err); + options.service_name.should.equal('semaphore'); + options.service_job_id.should.equal('1234'); + options.git.should.eql(git); done(); }); }; -var testAzurePipelines = function(sut, done){ - process.env.TF_BUILD = "true"; - process.env.BUILD_SOURCEBRANCHNAME = "hotfix"; - process.env.BUILD_SOURCEVERSION = "e3e3e3e3e3e3e3e3e"; - process.env.BUILD_BUILDID = "1234"; - process.env.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER = "123"; - - sut(function(err, options){ - options.service_name.should.equal("Azure Pipelines"); - options.service_job_id.should.equal("1234"); - options.service_pull_request.should.equal("123"); - - options.git.should.eql({ head: - { id: 'e3e3e3e3e3e3e3e3e', - author_name: 'Unknown Author', - author_email: '', - committer_name: 'Unknown Committer', - committer_email: '', - message: 'Unknown Commit Message' }, - branch: 'hotfix', - remotes: [] }); - +const testAzurePipelines = (sut, done) => { + process.env.TF_BUILD = 'true'; + process.env.BUILD_SOURCEBRANCHNAME = 'hotfix'; + process.env.BUILD_SOURCEVERSION = 'e3e3e3e3e3e3e3e3e'; + process.env.BUILD_BUILDID = '1234'; + process.env.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER = '123'; + + const git = { + head: { + id: 'e3e3e3e3e3e3e3e3e', + author_name: 'Unknown Author', + author_email: '', + committer_name: 'Unknown Committer', + committer_email: '', + message: 'Unknown Commit Message' + }, + branch: 'hotfix', + remotes: [] + }; + + sut((err, options) => { + should.not.exist(err); + options.service_name.should.equal('Azure Pipelines'); + options.service_job_id.should.equal('1234'); + options.service_pull_request.should.equal('123'); + options.git.should.eql(git); done(); }); }; - function ensureLocalGitContext(options) { - var path = require('path'); - var fs = require('fs'); + const baseDir = process.cwd(); + let dir = baseDir; + let gitDir; - var baseDir = process.cwd(), dir = baseDir, gitDir; while (path.resolve('/') !== dir) { gitDir = path.join(dir, '.git'); - var existsSync = fs.existsSync || path.existsSync; - if (existsSync(path.join(gitDir, 'HEAD'))) + const existsSync = fs.existsSync || path.existsSync; + if (existsSync(path.join(gitDir, 'HEAD'))) { break; + } dir = path.dirname(dir); } options = options || {}; - var synthetic = path.resolve('/') === dir; - var gitHead, content, branch, id, wrapUp = function() {}; + const synthetic = path.resolve('/') === dir; + let gitHead; + let content; + let branch; + let id; + let wrapUp = () => {}; if (synthetic) { branch = 'synthetic'; id = '424242424242424242'; gitHead = path.join('.git', 'HEAD'); - var gitBranch = path.join('.git', 'refs', 'heads', branch); + const gitBranch = path.join('.git', 'refs', 'heads', branch); fs.mkdirSync('.git'); if (options.detached) { fs.writeFileSync(gitHead, id, { encoding: 'utf8' }); } else { fs.mkdirSync(path.join('.git', 'refs')); fs.mkdirSync(path.join('.git', 'refs', 'heads')); - fs.writeFileSync(gitHead, "ref: refs/heads/" + branch, { encoding: 'utf8' }); + fs.writeFileSync(gitHead, `ref: refs/heads/${branch}`, { encoding: 'utf8' }); fs.writeFileSync(gitBranch, id, { encoding: 'utf8' }); } - wrapUp = function() { + + wrapUp = () => { fs.unlinkSync(gitHead); if (!options.detached) { fs.unlinkSync(gitBranch); fs.rmdirSync(path.join('.git', 'refs', 'heads')); fs.rmdirSync(path.join('.git', 'refs')); } + fs.rmdirSync('.git'); }; } else if (options.noGit) { - fs.renameSync(gitDir, gitDir + '.bak'); - wrapUp = function() { - fs.renameSync(gitDir + '.bak', gitDir); + fs.renameSync(gitDir, `${gitDir}.bak`); + wrapUp = () => { + fs.renameSync(`${gitDir}.bak`, gitDir); }; } else if (options.detached) { gitHead = path.join(gitDir, 'HEAD'); content = fs.readFileSync(gitHead, 'utf8').trim(); - var b = (content.match(/^ref: refs\/heads\/(\S+)$/) || [])[1]; + const b = (content.match(/^ref: refs\/heads\/(\S+)$/) || [])[1]; if (!b) { id = content; } else { id = fs.readFileSync(path.join(gitDir, 'refs', 'heads', b), 'utf8').trim(); fs.writeFileSync(gitHead, id, 'utf8'); - wrapUp = function() { + wrapUp = () => { fs.writeFileSync(gitHead, content, 'utf8'); }; } @@ -612,5 +710,9 @@ function ensureLocalGitContext(options) { id = branch ? fs.readFileSync(path.join(gitDir, 'refs', 'heads', branch), 'utf8').trim() : content; } - return { id: id, branch: branch, wrapUp: wrapUp }; + return { + id, + branch, + wrapUp + }; } diff --git a/test/handleInput.js b/test/handleInput.js index bca7b16..46cbe50 100644 --- a/test/handleInput.js +++ b/test/handleInput.js @@ -1,78 +1,72 @@ -var sysPath = require('path'); -var should = require('should'); -var sinon = require('sinon-restore'); -var index = require('../index'); -var fs = require('fs'); -logger = require('log-driver')({level : false}); +'use strict'; -describe("handleInput", function(){ - afterEach(function() { - sinon.restoreAll(); - }); - it ("returns an error when there's an error getting options", function(done){ - sinon.stub(index, 'getOptions', function(cb){ - return cb("some error", {}); - }); - var path = sysPath.join(__dirname, "/../fixtures/onefile.lcov"); - var input = fs.readFileSync(path, "utf8"); - index.handleInput(input, function(err){ - err.should.equal("some error"); +const fs = require('fs'); +const sysPath = require('path'); +const should = require('should'); +const sinon = require('sinon-restore'); +const logDriver = require('log-driver'); +const index = require('..'); + +logDriver({ level: false }); + +describe('handleInput', () => { + afterEach(() => { + sinon.restoreAll(); + }); + it('returns an error when there\'s an error getting options', done => { + sinon.stub(index, 'getOptions', cb => cb('some error', {})); + const path = sysPath.join(__dirname, '/../fixtures/onefile.lcov'); + const input = fs.readFileSync(path, 'utf8'); + index.handleInput(input, err => { + err.should.equal('some error'); done(); }); }); - it ("returns an error when there's an error converting", function(done){ - sinon.stub(index, 'getOptions', function(cb){ - return cb(null, {}); + it('returns an error when there\'s an error converting', done => { + sinon.stub(index, 'getOptions', cb => cb(null, {})); + sinon.stub(index, 'convertLcovToCoveralls', (input, options, cb) => { + cb('some error'); }); - sinon.stub(index, 'convertLcovToCoveralls', function(input, options, cb){ - cb("some error"); - }); - var path = sysPath.join(__dirname, "/../fixtures/onefile.lcov"); - var input = fs.readFileSync(path, "utf8"); - index.handleInput(input, function(err){ - err.should.equal("some error"); + const path = sysPath.join(__dirname, '/../fixtures/onefile.lcov'); + const input = fs.readFileSync(path, 'utf8'); + index.handleInput(input, err => { + err.should.equal('some error'); done(); }); }); - it ("returns an error when there's an error sending", function(done){ - sinon.stub(index, 'getOptions', function(cb){ - return cb(null, {}); - }); - sinon.stub(index, 'sendToCoveralls', function(postData, cb){ - cb("some error"); + it('returns an error when there\'s an error sending', done => { + sinon.stub(index, 'getOptions', cb => cb(null, {})); + sinon.stub(index, 'sendToCoveralls', (postData, cb) => { + cb('some error'); }); - var path = sysPath.join(__dirname, "/../fixtures/onefile.lcov"); - var input = fs.readFileSync(path, "utf8"); - index.handleInput(input, function(err){ - err.should.equal("some error"); + const path = sysPath.join(__dirname, '/../fixtures/onefile.lcov'); + const input = fs.readFileSync(path, 'utf8'); + index.handleInput(input, err => { + err.should.equal('some error'); done(); }); }); - it ("returns an error when there's a bad status code", function(done){ - sinon.stub(index, 'getOptions', function(cb){ - return cb(null, {}); + it('returns an error when there\'s a bad status code', done => { + sinon.stub(index, 'getOptions', cb => cb(null, {})); + sinon.stub(index, 'sendToCoveralls', (postData, cb) => { + cb(null, { statusCode: 500 }, 'body'); }); - sinon.stub(index, 'sendToCoveralls', function(postData, cb){ - cb(null, {statusCode : 500}, "body"); - }); - var path = sysPath.join(__dirname, "/../fixtures/onefile.lcov"); - var input = fs.readFileSync(path, "utf8"); - index.handleInput(input, function(err){ - err.should.equal("Bad response: 500 body"); + const path = sysPath.join(__dirname, '/../fixtures/onefile.lcov'); + const input = fs.readFileSync(path, 'utf8'); + index.handleInput(input, err => { + err.should.equal('Bad response: 500 body'); done(); }); }); - it ("completes successfully when there are no errors", function(done){ - sinon.stub(index, 'getOptions', function(cb){ - return cb(null, {}); - }); - sinon.stub(index, 'sendToCoveralls', function(postData, cb){ - cb(null, {statusCode : 200}, "body"); + it('completes successfully when there are no errors', done => { + sinon.stub(index, 'getOptions', cb => cb(null, {})); + sinon.stub(index, 'sendToCoveralls', (postData, cb) => { + cb(null, { statusCode: 200 }, 'body'); }); - var path = sysPath.join(__dirname, "/../fixtures/onefile.lcov"); - var input = fs.readFileSync(path, "utf8"); - index.handleInput(input, function(err, body){ - (err === null).should.equal(true); + const path = sysPath.join(__dirname, '/../fixtures/onefile.lcov'); + const input = fs.readFileSync(path, 'utf8'); + index.handleInput(input, (err, body) => { + should.not.exist(err); body.should.equal('body'); done(); }); diff --git a/test/logger.js b/test/logger.js index b007b6f..1d5261f 100644 --- a/test/logger.js +++ b/test/logger.js @@ -1,32 +1,33 @@ -var should = require('should'); -var sinon = require('sinon-restore'); -var index = require('../index'); +'use strict'; -describe("logger", function(){ - it ("should log at debug level when --verbose is set", function(){ +require('should')(); +const index = require('..'); + +describe('logger', () => { + it('should log at debug level when --verbose is set', () => { index.options.verbose = true; - var logger = require('../index').logger(); + const logger = index.logger(); logger.level.should.equal('debug'); }); - it ("should log at debug level when NODE_COVERALLS_DEBUG is set in env", function(){ + it('should log at debug level when NODE_COVERALLS_DEBUG is set in env', () => { index.options.verbose = false; process.env.NODE_COVERALLS_DEBUG = 1; - var logger = require('../index').logger(); + const logger = index.logger(); logger.level.should.equal('debug'); }); - it ("should log at debug level when NODE_COVERALLS_DEBUG is set in env as a string", function(){ + it('should log at debug level when NODE_COVERALLS_DEBUG is set in env as a string', () => { index.options.verbose = false; process.env.NODE_COVERALLS_DEBUG = '1'; - var logger = require('../index').logger(); + const logger = index.logger(); logger.level.should.equal('debug'); }); - it ("should log at warn level when NODE_COVERALLS_DEBUG not set and no --verbose", function(){ + it('should log at warn level when NODE_COVERALLS_DEBUG not set and no --verbose', () => { index.options.verbose = false; process.env.NODE_COVERALLS_DEBUG = 0; - var logger = require('../index').logger(); + const logger = index.logger(); logger.level.should.equal('error'); }); }); diff --git a/test/sendToCoveralls.js b/test/sendToCoveralls.js index 6121bbb..2f18880 100644 --- a/test/sendToCoveralls.js +++ b/test/sendToCoveralls.js @@ -1,16 +1,20 @@ -var should = require('should'); -var request = require('request'); -var sinon = require('sinon-restore'); -var index = require('../index'); -logger = require('log-driver')({level : false}); +'use strict'; -describe("sendToCoveralls", function(){ - var realCoverallsHost; - beforeEach(function() { +const should = require('should'); +const request = require('request'); +const sinon = require('sinon-restore'); +const logDriver = require('log-driver'); +const index = require('..'); + +logDriver({ level: false }); + +describe('sendToCoveralls', () => { + let realCoverallsHost; + beforeEach(() => { realCoverallsHost = process.env.COVERALLS_ENDPOINT; }); - afterEach(function() { + afterEach(() => { sinon.restoreAll(); if (realCoverallsHost !== undefined) { process.env.COVERALLS_ENDPOINT = realCoverallsHost; @@ -19,16 +23,16 @@ describe("sendToCoveralls", function(){ } }); - it ("passes on the correct params to request.post", function(done){ - sinon.stub(request, 'post', function(obj, cb){ + it('passes on the correct params to request.post', done => { + sinon.stub(request, 'post', (obj, cb) => { obj.url.should.equal('https://coveralls.io/api/v1/jobs'); - obj.form.should.eql({json : '{"some":"obj"}'}); + obj.form.should.eql({ json: '{"some":"obj"}' }); cb('err', 'response', 'body'); }); - var obj = {"some":"obj"}; - - index.sendToCoveralls(obj, function(err, response, body){ + const obj = { 'some': 'obj' }; + + index.sendToCoveralls(obj, (err, response, body) => { err.should.equal('err'); response.should.equal('response'); body.should.equal('body'); @@ -36,39 +40,40 @@ describe("sendToCoveralls", function(){ }); }); - it ("allows sending to enterprise url", function(done){ + it('allows sending to enterprise url', done => { process.env.COVERALLS_ENDPOINT = 'https://coveralls-ubuntu.domain.com'; - sinon.stub(request, 'post', function(obj, cb){ + sinon.stub(request, 'post', (obj, cb) => { obj.url.should.equal('https://coveralls-ubuntu.domain.com/api/v1/jobs'); - obj.form.should.eql({json : '{"some":"obj"}'}); + obj.form.should.eql({ json: '{"some":"obj"}' }); cb('err', 'response', 'body'); }); - var obj = {"some":"obj"}; - index.sendToCoveralls(obj, function(err, response, body){ + const obj = { 'some': 'obj' }; + index.sendToCoveralls(obj, (err, response, body) => { err.should.equal('err'); response.should.equal('response'); body.should.equal('body'); done(); }); }); - it ("writes output to stdout when --stdout is passed", function(done) { - var obj = {"some":"obj"}; - + it('writes output to stdout when --stdout is passed', done => { + const obj = { 'some': 'obj' }; + // set up mock process.stdout.write temporarily - var origStdoutWrite = process.stdout.write; - process.stdout.write = function(string) { - if (string == JSON.stringify(obj)) { + const origStdoutWrite = process.stdout.write; + process.stdout.write = function(string, ...args) { + if (string === JSON.stringify(obj)) { process.stdout.write = origStdoutWrite; return done(); } - - origStdoutWrite.apply(this, arguments); + + origStdoutWrite.apply(this, args); }; - + index.options.stdout = true; - - index.sendToCoveralls(obj, function(err, response, body) { + + index.sendToCoveralls(obj, (err, response) => { + should.not.exist(err); response.statusCode.should.equal(200); }); }); -- cgit v1.2.3