Skip to content

Commit

Permalink
feat: add getToken helper
Browse files Browse the repository at this point in the history
  • Loading branch information
drazisil-codecov committed Jul 19, 2021
1 parent f6580e6 commit ce14f26
Show file tree
Hide file tree
Showing 6 changed files with 100 additions and 21 deletions.
26 changes: 20 additions & 6 deletions src/helpers/files.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const { log } = require('./logger')
/**
*
* @param {string} projectRoot
* @param {Object} args
* @returns {Promise<string>}
*/
async function getFileListing(projectRoot, args) {
Expand Down Expand Up @@ -161,12 +162,14 @@ function coverageFilePatterns() {
* @returns {string[]}
*/
function getCoverageFiles(projectRoot, coverageFilePatterns) {
return coverageFilePatterns.flatMap(pattern => {
return glob.sync(`**/${pattern}`, {
cwd: projectRoot,
ignore: globBlacklist(),
})
})
return coverageFilePatterns.flatMap(
/** @type {string} */ pattern => {
return glob.sync(`**/${pattern}`, {
cwd: projectRoot,
ignore: globBlacklist(),
})
},
)
}

/**
Expand Down Expand Up @@ -221,6 +224,7 @@ function parseGitIgnore(projectRoot) {
*
* @param {string} projectRoot Root of the project
* @param {string} dirPath Directory to search in
* @param {Object} args
* @param {string[]} arrayOfFiles
* @returns {string[]}
*/
Expand Down Expand Up @@ -285,6 +289,11 @@ function endFileMarker() {
return '<<<<<< EOF\n'
}

/**
*
* @param {string} filePath
* @returns string
*/
function fileHeader(filePath) {
return `# path=${filePath}\n`
}
Expand Down Expand Up @@ -314,6 +323,11 @@ function getFilePath(projectRoot, filePath) {
return path.join(projectRoot, filePath)
}

/**
*
* @param {string} projectRoot
* @param {string} filePath
*/
function removeFile(projectRoot, filePath) {
fs.unlink(getFilePath(projectRoot, filePath), err => {
if (err) {
Expand Down
5 changes: 3 additions & 2 deletions src/helpers/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@

/**
*
* @param {string|Object} message
* @param {string} message
* @param {Object} [options]
* @param {'debug'|'error'} [options.level]
* @param {string} [options.level]
* @param {Object} [options.args]
* @param {boolean} [options.args.verbose]
* @returns void
*/
function log(message, options) {
Expand Down
25 changes: 24 additions & 1 deletion src/helpers/validate.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
const validator = require('validator')

/**
*
* @param {string} token
* @returns boolean
*/
function validateToken(token) {
return validator.isAlphanumeric(token)
}
Expand All @@ -25,15 +30,33 @@ function validateFileNamePath(path) {
* @param {number} requestedLength
* @returns {boolean}
*/
const GIT_SHA_LENGTH = 40;
const GIT_SHA_LENGTH = 40

function validateSHA(commitSHA, requestedLength = GIT_SHA_LENGTH) {
return (
commitSHA.length === requestedLength && validator.isAlphanumeric(commitSHA)
)
}

function getToken(args) {
// Token gets set in the following order:
// * args.token
// * process.env.CODECOV_TOKEN
// * ''
let token = ''
if (args.token && validateToken(args.token)) {
token = args.token
} else if (
process.env.CODECOV_TOKEN &&
validateToken(process.env.CODECOV_TOKEN)
) {
token = process.env.CODECOV_TOKEN
}
return token
}

module.exports = {
getToken,
validateToken,
validateURL,
validateFlags,
Expand Down
14 changes: 5 additions & 9 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const providers = require('./ci_providers')
* @param {string} token
* @param {string} query
* @param {string} uploadFile
* @param {string} source
*/
function dryRun(uploadHost, token, query, uploadFile, source) {
log('==> Dumping upload file (no upload)')
Expand Down Expand Up @@ -47,6 +48,7 @@ function dryRun(uploadHost, token, query, uploadFile, source) {
* @param {string} args.url Change the upload host (Enterprise use)
* @param {boolean} args.clean Move discovered coverage reports to the trash
* @param {string} args.feature Toggle features
* @param {string} args.source Track wrappers of the uploader
*/
async function main(args) {
/*
Expand All @@ -68,14 +70,8 @@ async function main(args) {
const uploadHost = validateHelpers.validateURL(args.url)
? args.url
: 'https://codecov.io'
let token = validateHelpers.validateToken(args.token) ? args.token : ''
if (token === '') {
token = process.env.CODECOV_TOKEN || ''
token = validateHelpers.validateToken(token)
? process.env.CODECOV_TOKEN
: ''
}

const token = validateHelpers.getToken(args)
log(generateHeader(getVersion()))

// == Step 2: detect if we are in a git repo
Expand Down Expand Up @@ -172,7 +168,7 @@ async function main(args) {

// Environment variables
if (args.env || envs.CODECOV_ENV) {
const environmentVars = args.env || envs.CODECOV_ENV
const environmentVars = args.env || envs.CODECOV_ENV || ''
const vars = environmentVars
.split(',')
.filter(Boolean)
Expand Down Expand Up @@ -243,7 +239,7 @@ async function main(args) {
{ level: 'debug', args },
)
const result = await webHelpers.uploadToCodecovPUT(uploadURL, gzippedFile)
log(result)
log(JSON.stringify(result))
return result
} catch (error) {
throw new Error(`Error uploading to ${uploadHost}: ${error}`)
Expand Down
13 changes: 10 additions & 3 deletions test/helpers/logger.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// @ts-check
const logger = require('../../src/helpers/logger')
const { expect, it } = require('@jest/globals')

describe('Logger Helper', () => {
afterEach(() => {
Expand All @@ -23,7 +24,9 @@ describe('Logger Helper', () => {
})

it('Should call logger with options.level = debug and verbose set', () => {
jest.spyOn(console, 'debug').mockImplementation(() => {})
jest.spyOn(console, 'debug').mockImplementation(() => {
// Intentionally empty
})
logger.log('message with debug level and verbose', {
level: 'debug',
args: { verbose: true },
Expand All @@ -34,15 +37,19 @@ describe('Logger Helper', () => {
})

it('Should call logger with options.level = error', () => {
jest.spyOn(console, 'error').mockImplementation(() => {})
jest.spyOn(console, 'error').mockImplementation(() => {
// Intentionally empty
})
logger.log('message with error level', { level: 'error' })
expect(console.error).toHaveBeenCalledWith(
expect.stringMatching(/error level/),
)
})

it('Should call logger with unsupported options.level ', () => {
jest.spyOn(console, 'log').mockImplementation(() => {})
jest.spyOn(console, 'log').mockImplementation(() => {
// Intentionally empty
})
logger.log('message with error level of foobar', { level: 'foobar' })
expect(console.log).toHaveBeenCalledWith(expect.stringMatching(/of foobar/))
})
Expand Down
38 changes: 38 additions & 0 deletions test/helpers/validate.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
const validate = require('../../src/helpers/validate')

// Backup the env
const realEnv = { ...process.env }

describe('Input Validators', () => {
describe('Tokens', () => {
it('Returns true with a valid token', () => {
Expand Down Expand Up @@ -65,5 +68,40 @@ describe('Input Validators', () => {
it('should pass with correct content and length', () => {
expect(validate.validateSHA('abc123', 6)).toBe(true)
})

it('should pass with correct content and default length', () => {
expect(
validate.validateSHA('1732d84b7ef2425e979d6034a3e3bb5633da344a'),
).toBe(true)
})
})

describe('getToken()', () => {
beforeEach(() => {
delete process.env.CODECOV_TOKEN
})

afterEach(() => {
process.env = realEnv
})

it('should return an empty string if neither args or env are set', () => {
const args = {}
expect(validate.getToken(args)).toEqual('')
})

it('should return the value of the env if env is set, and args are not set', () => {
process.env.CODECOV_TOKEN = 'testingEnvToken'
const args = {}
expect(validate.getToken(args)).toEqual('testingEnvToken')
})

it('should return the value of the arg if env is set, and args are set', () => {
process.env.CODECOV_TOKEN = 'testingEnvToken'
const args = {
token: 'testingArgToken',
}
expect(validate.getToken(args)).toEqual('testingArgToken')
})
})
})

0 comments on commit ce14f26

Please sign in to comment.