diff --git a/.github/workflows/node-ci.yml b/.github/workflows/node-ci.yml index 5db222f6..49013a52 100644 --- a/.github/workflows/node-ci.yml +++ b/.github/workflows/node-ci.yml @@ -21,6 +21,9 @@ jobs: node-version: ${{ matrix.node-version }} cache: npm - run: npm install + - run: npm run lint:es + - run: npm run lint:js + - run: npm run lint:lockfile - run: npm run test:unit:ci strategy: matrix: diff --git a/lib/mergeDeep.js b/lib/mergeDeep.js index ab278e5c..28938ba1 100644 --- a/lib/mergeDeep.js +++ b/lib/mergeDeep.js @@ -92,8 +92,8 @@ class MergeDeep { // So any property in the target that is not in the source is not treated as a deletion for (const key in source) { // Skip prototype pollution vectors - if (key === "__proto__" || key === "constructor") { - continue; + if (key === '__proto__' || key === 'constructor') { + continue } // Logic specific for Github // API response includes urls for resources, or other ignorable fields; we can ignore them diff --git a/lib/plugins/archive.js b/lib/plugins/archive.js index a481029c..eb3d25c1 100644 --- a/lib/plugins/archive.js +++ b/lib/plugins/archive.js @@ -1,86 +1,79 @@ -const NopCommand = require('../nopcommand'); +const NopCommand = require('../nopcommand') -function returnValue(shouldContinue, nop) { - return { shouldContinue, nopCommands: nop }; +function returnValue (shouldContinue, nop) { + return { shouldContinue, nopCommands: nop } } module.exports = class Archive { - constructor(nop, github, repo, settings, log) { - this.github = github; - this.repo = repo; - this.settings = settings; - this.log = log; - this.nop = nop; + constructor (nop, github, repo, settings, log) { + this.github = github + this.repo = repo + this.settings = settings + this.log = log + this.nop = nop } // Returns true if plugin application should continue, false otherwise - async sync() { + async sync () { // Fetch repository details using REST API const { data: repoDetails } = await this.github.repos.get({ - owner: this.repo.owner, - repo: this.repo.repo - }); + owner: this.repo.owner, + repo: this.repo.repo + }) if (typeof this.settings?.archived !== 'undefined') { - this.log.debug(`Checking if ${this.repo.owner}/${this.repo.repo} is archived`); - - this.log.debug(`Repo ${this.repo.owner}/${this.repo.repo} is ${repoDetails.archived ? 'archived' : 'not archived'}`); + this.log.debug(`Checking if ${this.repo.owner}/${this.repo.repo} is archived`) + + this.log.debug(`Repo ${this.repo.owner}/${this.repo.repo} is ${repoDetails.archived ? 'archived' : 'not archived'}`) if (repoDetails.archived) { if (this.settings.archived) { - this.log.debug(`Repo ${this.repo.owner}/${this.repo.repo} already archived, inform other plugins should not run.`); - return returnValue(false); - } - else { - this.log.debug(`Unarchiving ${this.repo.owner}/${this.repo.repo}`); + this.log.debug(`Repo ${this.repo.owner}/${this.repo.repo} already archived, inform other plugins should not run.`) + return returnValue(false) + } else { + this.log.debug(`Unarchiving ${this.repo.owner}/${this.repo.repo}`) if (this.nop) { - return returnValue(true, [new NopCommand(this.constructor.name, this.repo, this.github.repos.update.endpoint(this.settings), 'will unarchive')]); - } - else { + return returnValue(true, [new NopCommand(this.constructor.name, this.repo, this.github.repos.update.endpoint(this.settings), 'will unarchive')]) + } else { // Unarchive the repository using REST API const updateResponse = await this.github.repos.update({ owner: this.repo.owner, repo: this.repo.repo, archived: false - }); - this.log.debug(`Unarchive result ${JSON.stringify(updateResponse)}`); + }) + this.log.debug(`Unarchive result ${JSON.stringify(updateResponse)}`) - return returnValue(true); + return returnValue(true) } } - } - else { + } else { if (this.settings.archived) { - this.log.debug(`Archiving ${this.repo.owner}/${this.repo.repo}`); + this.log.debug(`Archiving ${this.repo.owner}/${this.repo.repo}`) if (this.nop) { - return returnValue(false, [new NopCommand(this.constructor.name, this.repo, this.github.repos.update.endpoint(this.settings), 'will archive')]); - } - else { + return returnValue(false, [new NopCommand(this.constructor.name, this.repo, this.github.repos.update.endpoint(this.settings), 'will archive')]) + } else { // Archive the repository using REST API const updateResponse = await this.github.repos.update({ owner: this.repo.owner, repo: this.repo.repo, archived: true - }); - this.log.debug(`Archive result ${JSON.stringify(updateResponse)}`); + }) + this.log.debug(`Archive result ${JSON.stringify(updateResponse)}`) - return returnValue(false); + return returnValue(false) } - } - else { - this.log.debug(`Repo ${this.repo.owner}/${this.repo.repo} is not archived, ignoring.`); - return returnValue(true); + } else { + this.log.debug(`Repo ${this.repo.owner}/${this.repo.repo} is not archived, ignoring.`) + return returnValue(true) } } - } - else { - if (repoDetails.archived) { - this.log.debug(`Repo ${this.repo.owner}/${this.repo.repo} is archived, ignoring.`); - return returnValue(false); - } - else { - this.log.debug(`Repo ${this.repo.owner}/${this.repo.repo} is not archived, proceed as usual.`); - return returnValue(true); - } + } else { + if (repoDetails.archived) { + this.log.debug(`Repo ${this.repo.owner}/${this.repo.repo} is archived, ignoring.`) + return returnValue(false) + } else { + this.log.debug(`Repo ${this.repo.owner}/${this.repo.repo} is not archived, proceed as usual.`) + return returnValue(true) + } } } -}; +} diff --git a/lib/plugins/branches.js b/lib/plugins/branches.js index fb43a8d7..a50f382f 100644 --- a/lib/plugins/branches.js +++ b/lib/plugins/branches.js @@ -5,10 +5,10 @@ const Overrides = require('./overrides') const ignorableFields = [] const previewHeaders = { accept: 'application/vnd.github.hellcat-preview+json,application/vnd.github.luke-cage-preview+json,application/vnd.github.zzzax-preview+json' } const overrides = { - 'contexts': { - 'action': 'reset', - 'type': 'array' - }, + contexts: { + action: 'reset', + type: 'array' + } } module.exports = class Branches extends ErrorStash { diff --git a/lib/plugins/diffable.js b/lib/plugins/diffable.js index c5c5b253..54198433 100644 --- a/lib/plugins/diffable.js +++ b/lib/plugins/diffable.js @@ -40,8 +40,8 @@ module.exports = class Diffable extends ErrorStash { // this.log.debug(` entries ${JSON.stringify(filteredEntries)}`) filteredEntries = filteredEntries.filter(attrs => { if (Array.isArray(attrs.exclude)) { - const excludeGlobs = attrs.exclude.map(exc => new Glob(exc)); - const excludeGlobsMatch = excludeGlobs.some(glob => !!this.repo.repo.match(glob)); + const excludeGlobs = attrs.exclude.map(exc => new Glob(exc)) + const excludeGlobsMatch = excludeGlobs.some(glob => !!this.repo.repo.match(glob)) if (!attrs.exclude.includes(this.repo.repo) && !excludeGlobsMatch) { // this.log.debug(`returning not excluded entry = ${JSON.stringify(attrs)} for repo ${this.repo.repo}`) @@ -57,8 +57,8 @@ module.exports = class Diffable extends ErrorStash { }) filteredEntries = filteredEntries.filter(attrs => { if (Array.isArray(attrs.include)) { - const includeGlobs = attrs.include.map(inc => new Glob(inc)); - const includeGlobsMatch = includeGlobs.some(glob => !!this.repo.repo.match(glob)); + const includeGlobs = attrs.include.map(inc => new Glob(inc)) + const includeGlobsMatch = includeGlobs.some(glob => !!this.repo.repo.match(glob)) if (attrs.include.includes(this.repo.repo) || includeGlobsMatch) { // this.log.debug(`returning included entry = ${JSON.stringify(attrs)} for repo ${this.repo.repo}`) diff --git a/lib/plugins/environments.js b/lib/plugins/environments.js index bc44ae37..46267a31 100644 --- a/lib/plugins/environments.js +++ b/lib/plugins/environments.js @@ -1,5 +1,4 @@ const Diffable = require('./diffable') -const MergeDeep = require('../mergeDeep') const NopCommand = require('../nopcommand') module.exports = class Environments extends Diffable { @@ -19,13 +18,13 @@ module.exports = class Environments extends Diffable { } } - async nopifyRequest(url, options, description) { + async nopifyRequest (url, options, description) { if (!this.nop) { - await this.github.request(url, options); + await this.github.request(url, options) } else { - return Promise.resolve([ - new NopCommand(this.constructor.name, this.repo, url, description) - ]) + return Promise.resolve([ + new NopCommand(this.constructor.name, this.repo, url, description) + ]) } } @@ -147,7 +146,7 @@ module.exports = class Environments extends Diffable { custom_branch_policies: !!attrs.deployment_branch_policy.custom_branch_policies } } - await this.nopifyRequest(`PUT /repos/:org/:repo/environments/:environment_name`, options, 'Update environment settings'); + await this.nopifyRequest('PUT /repos/:org/:repo/environments/:environment_name', options, 'Update environment settings') } if (deploymentBranchPolicy && attrs.deployment_branch_policy && attrs.deployment_branch_policy.custom_branch_policies) { @@ -157,14 +156,14 @@ module.exports = class Environments extends Diffable { await this.nopifyRequest('DELETE /repos/:org/:repo/environments/:environment_name/deployment-branch-policies/:branch_policy_id', { ...baseRequestOptions, branch_policy_id: policy.id - }, 'Delete deployment branch policy') + }, 'Delete deployment branch policy') } for (const policy of attrs.deployment_branch_policy.custom_branch_policies) { await this.nopifyRequest( - 'POST /repos/:org/:repo/environments/:environment_name/deployment-branch-policies',{ - ...baseRequestOptions, - name: policy + 'POST /repos/:org/:repo/environments/:environment_name/deployment-branch-policies', { + ...baseRequestOptions, + name: policy }, 'Create deployment branch policy') } } @@ -179,18 +178,18 @@ module.exports = class Environments extends Diffable { if (existingVariable.value !== variable.value) { await this.nopifyRequest( 'PATCH /repos/:org/:repo/environments/:environment_name/variables/:variable_name', { - ...baseRequestOptions, - variable_name: variable.name, - value: variable.value + ...baseRequestOptions, + variable_name: variable.name, + value: variable.value }, 'Update environment variable' - ) + ) } } else { await this.nopifyRequest( 'POST /repos/:org/:repo/environments/:environment_name/variables', { - ...baseRequestOptions, - name: variable.name, - value: variable.value + ...baseRequestOptions, + name: variable.name, + value: variable.value }, 'Create environment variable' ) } @@ -199,8 +198,8 @@ module.exports = class Environments extends Diffable { for (const variable of existingVariables) { await this.nopifyRequest( 'DELETE /repos/:org/:repo/environments/:environment_name/variables/:variable_name', { - ...baseRequestOptions, - variable_name: variable.name + ...baseRequestOptions, + variable_name: variable.name }, 'Delete environment variable' ) } @@ -215,19 +214,18 @@ module.exports = class Environments extends Diffable { if (!existingRule) { await this.nopifyRequest( 'POST /repos/:org/:repo/environments/:environment_name/deployment_protection_rules', { - ...baseRequestOptions, - integration_id: rule.app_id + ...baseRequestOptions, + integration_id: rule.app_id }, 'Create deployment protection rule' - ) + ) } } for (const rule of existingRules) { await this.nopifyRequest('DELETE /repos/:org/:repo/environments/:environment_name/deployment_protection_rules/:rule_id', { ...baseRequestOptions, rule_id: rule.id - }, "Delete deployment protection rule") + }, 'Delete deployment protection rule') } - } } @@ -237,48 +235,50 @@ module.exports = class Environments extends Diffable { repo: this.repo.repo, environment_name: attrs.name } - + await this.nopifyRequest( 'PUT /repos/:org/:repo/environments/:environment_name', { - ...baseRequestOptions, - wait_timer: attrs.wait_timer, - prevent_self_review: attrs.prevent_self_review, - reviewers: attrs.reviewers, - deployment_branch_policy: attrs.deployment_branch_policy == null ? null : { + ...baseRequestOptions, + wait_timer: attrs.wait_timer, + prevent_self_review: attrs.prevent_self_review, + reviewers: attrs.reviewers, + deployment_branch_policy: attrs.deployment_branch_policy == null + ? null + : { protected_branches: !!attrs.deployment_branch_policy.protected_branches, custom_branch_policies: !!attrs.deployment_branch_policy.custom_branch_policies - } + } }, 'Update environment settings') if (attrs.deployment_branch_policy && attrs.deployment_branch_policy.custom_branch_policies) { for (const policy of attrs.deployment_branch_policy.custom_branch_policies) { await this.nopifyRequest( 'POST /repos/:org/:repo/environments/:environment_name/deployment-branch-policies', { - ...baseRequestOptions, - name: policy.name + ...baseRequestOptions, + name: policy.name }, 'Create deployment branch policy' ) } } if (attrs.variables) { - for(const variable of attrs.variables) { + for (const variable of attrs.variables) { await this.nopifyRequest( 'POST /repos/:org/:repo/environments/:environment_name/variables', { ...baseRequestOptions, name: variable.name, value: variable.value }, 'Create environment variable' - ) - } + ) } + } if (attrs.deployment_protection_rules) { for (const rule of attrs.deployment_protection_rules) { await this.nopifyRequest( 'POST /repos/:org/:repo/environments/:environment_name/deployment_protection_rules', { - ...baseRequestOptions, - integration_id: rule.app_id + ...baseRequestOptions, + integration_id: rule.app_id }, 'Create deployment protection rule' ) } @@ -293,16 +293,16 @@ module.exports = class Environments extends Diffable { } await this.nopifyRequest( - 'DELETE /repos/:org/:repo/environments/:environment_name', { - ...baseRequestOptions - }, 'Delete environment' + 'DELETE /repos/:org/:repo/environments/:environment_name', { + ...baseRequestOptions + }, 'Delete environment' ) -} + } sync () { const resArray = [] if (this.entries) { - let filteredEntries = this.filterEntries() + const filteredEntries = this.filterEntries() return this.find().then(existingRecords => { // Remove any null or undefined values from the diffables (usually comes from repo override) for (const entry of filteredEntries) { diff --git a/lib/plugins/overrides.js b/lib/plugins/overrides.js index 0030b124..b6d68942 100644 --- a/lib/plugins/overrides.js +++ b/lib/plugins/overrides.js @@ -74,23 +74,23 @@ module.exports = class Overrides extends ErrorStash { // - The POST method for rulesets (create) allows for one override only. static removeOverrides (overrides, source, existing) { Object.entries(overrides).forEach(([override, props]) => { - let sourceRefs = Overrides.getObjectRef(source, override) - let data = JSON.stringify(sourceRefs) + const sourceRefs = Overrides.getObjectRef(source, override) + const data = JSON.stringify(sourceRefs) if (data.includes('{{EXTERNALLY_DEFINED}}')) { - let existingRefs = Overrides.getObjectRef(existing, override) + const existingRefs = Overrides.getObjectRef(existing, override) sourceRefs.forEach(sourceRef => { if (existingRefs[0]) { sourceRef[override] = existingRefs[0][override] - } else if (props['action'] === 'delete') { - Overrides.removeTopLevelParent(source, sourceRef[override], props['parents']) + } else if (props.action === 'delete') { + Overrides.removeTopLevelParent(source, sourceRef[override], props.parents) delete sourceRef[override] - } else if (props['type'] === 'array') { + } else if (props.type === 'array') { sourceRef[override] = [] - } else if (props['type'] === 'dict') { + } else if (props.type === 'dict') { sourceRef[override] = {} } else { - throw new Error(`Unknown type ${props['type']} for ${override}`) + throw new Error(`Unknown type ${props.type} for ${override}`) } }) } diff --git a/lib/plugins/rulesets.js b/lib/plugins/rulesets.js index c4208de8..bbf80084 100644 --- a/lib/plugins/rulesets.js +++ b/lib/plugins/rulesets.js @@ -4,11 +4,11 @@ const MergeDeep = require('../mergeDeep') const Overrides = require('./overrides') const ignorableFields = [] const overrides = { - 'required_status_checks': { - 'action': 'delete', - 'parents': 3, - 'type': 'dict' - }, + required_status_checks: { + action: 'delete', + parents: 3, + type: 'dict' + } } const version = { diff --git a/lib/settings.js b/lib/settings.js index 9e00c140..6426a445 100644 --- a/lib/settings.js +++ b/lib/settings.js @@ -26,7 +26,7 @@ class Settings { return settings } - static async syncSubOrgs(nop, context, suborg, repo, config, ref) { + static async syncSubOrgs (nop, context, suborg, repo, config, ref) { const settings = new Settings(nop, context, repo, config, ref, suborg) try { await settings.loadConfigs() @@ -38,7 +38,7 @@ class Settings { } } - static async sync(nop, context, repo, config, ref) { + static async sync (nop, context, repo, config, ref) { const settings = new Settings(nop, context, repo, config, ref) try { await settings.loadConfigs(repo) @@ -53,13 +53,13 @@ class Settings { } } - static async handleError(nop, context, repo, config, ref, nopcommand) { + static async handleError (nop, context, repo, config, ref, nopcommand) { const settings = new Settings(nop, context, repo, config, ref) settings.appendToResults([nopcommand]) await settings.handleResults() } - constructor(nop, context, repo, config, ref, suborg) { + constructor (nop, context, repo, config, ref, suborg) { this.ref = ref this.context = context this.installation_id = context.payload.installation.id @@ -98,7 +98,7 @@ class Settings { } // Create a check in the Admin repo for safe-settings. - async createCheckRun() { + async createCheckRun () { const startTime = new Date() let conclusion = 'success' let details = `Run on: \`${new Date().toISOString()}\`` @@ -144,7 +144,7 @@ class Settings { }) } - logError(msg) { + logError (msg) { this.log.error(msg) this.errors.push({ owner: this.repo.owner, @@ -154,7 +154,7 @@ class Settings { }) } - async handleResults() { + async handleResults () { const { payload } = this.context // Create a checkrun if not in nop mode @@ -164,12 +164,12 @@ class Settings { return } - //remove duplicate rows in this.results + // remove duplicate rows in this.results this.results = this.results.filter((thing, index, self) => { - return index === self.findIndex((t) => { - return t.type === thing.type && t.repo === thing.repo && t.plugin === thing.plugin - }) + return index === self.findIndex((t) => { + return t.type === thing.type && t.repo === thing.repo && t.plugin === thing.plugin }) + }) let error = false // Different logic @@ -281,12 +281,12 @@ ${this.results.reduce((x, y) => { await this.github.checks.update(params) } - async loadConfigs(repo) { + async loadConfigs (repo) { this.subOrgConfigs = await this.getSubOrgConfigs() this.repoConfigs = await this.getRepoConfigs(repo) } - async updateOrg() { + async updateOrg () { const rulesetsConfig = this.config.rulesets if (rulesetsConfig) { const RulesetsPlugin = Settings.PLUGINS.rulesets @@ -296,7 +296,7 @@ ${this.results.reduce((x, y) => { } } - async updateRepos(repo) { + async updateRepos (repo) { this.subOrgConfigs = this.subOrgConfigs || await this.getSubOrgConfigs() let repoConfig = this.config.repository if (repoConfig) { @@ -327,7 +327,7 @@ ${this.results.reduce((x, y) => { if (overrideRepoConfig) { repoConfig = this.mergeDeep.mergeDeep({}, repoConfig, overrideRepoConfig) } - const {shouldContinue, nopCommands} = await new Archive(this.nop, this.github, repo, repoConfig, this.log).sync() + const { shouldContinue, nopCommands } = await new Archive(this.nop, this.github, repo, repoConfig, this.log).sync() if (nopCommands) this.appendToResults(nopCommands) if (shouldContinue) { if (repoConfig) { @@ -366,7 +366,7 @@ ${this.results.reduce((x, y) => { } } - async updateAll() { + async updateAll () { // this.subOrgConfigs = this.subOrgConfigs || await this.getSubOrgConfigs(this.github, this.repo, this.log) // this.repoConfigs = this.repoConfigs || await this.getRepoConfigs(this.github, this.repo, this.log) return this.eachRepositoryRepos(this.github, this.log).then(res => { @@ -374,7 +374,7 @@ ${this.results.reduce((x, y) => { }) } - getSubOrgConfig(repoName) { + getSubOrgConfig (repoName) { if (this.subOrgConfigs) { for (const k of Object.keys(this.subOrgConfigs)) { const repoPattern = new Glob(k) @@ -387,13 +387,13 @@ ${this.results.reduce((x, y) => { } // Remove Org specific configs from the repo config - returnRepoSpecificConfigs(config) { + returnRepoSpecificConfigs (config) { const newConfig = Object.assign({}, config) // clone delete newConfig.rulesets return newConfig } - childPluginsList(repo) { + childPluginsList (repo) { const repoName = repo.repo const subOrgOverrideConfig = this.getSubOrgConfig(repoName) this.log.debug(`suborg config for ${repoName} is ${JSON.stringify(subOrgOverrideConfig)}`) @@ -425,7 +425,7 @@ ${this.results.reduce((x, y) => { return childPlugins } - validate(section, baseConfig, overrideConfig) { + validate (section, baseConfig, overrideConfig) { const configValidator = this.configvalidators[section] if (configValidator) { this.log.debug(`Calling configvalidator for key ${section} `) @@ -444,7 +444,7 @@ ${this.results.reduce((x, y) => { } } - isRestricted(repoName) { + isRestricted (repoName) { const restrictedRepos = this.config.restrictedRepos // Skip configuring any restricted repos if (Array.isArray(restrictedRepos)) { @@ -476,7 +476,7 @@ ${this.results.reduce((x, y) => { return false } - includesRepo(repoName, restrictedRepos) { + includesRepo (repoName, restrictedRepos) { return restrictedRepos.filter((restrictedRepo) => { return RegExp(restrictedRepo).test(repoName) }).length > 0 } @@ -531,7 +531,7 @@ ${this.results.reduce((x, y) => { * @param params Params to fetch the file with * @return The parsed YAML file */ - async loadConfigMap(params) { + async loadConfigMap (params) { try { this.log.debug(` In loadConfigMap ${JSON.stringify(params)}`) const response = await this.github.repos.getContent(params).catch(e => { @@ -578,7 +578,7 @@ ${this.results.reduce((x, y) => { * @param params Params to fetch the file with * @return The parsed YAML file */ - async getRepoConfigMap() { + async getRepoConfigMap () { try { this.log.debug(` In getRepoConfigMap ${JSON.stringify(this.repo)}`) // GitHub getContent api has a hard limit of returning 1000 entries without @@ -645,7 +645,7 @@ ${this.results.reduce((x, y) => { * @param params Params to fetch the file with * @return The parsed YAML file */ - async getSubOrgConfigMap() { + async getSubOrgConfigMap () { try { this.log.debug(` In getSubOrgConfigMap ${JSON.stringify(this.repo)}`) const repo = { owner: this.repo.owner, repo: env.ADMIN_REPO } @@ -672,7 +672,7 @@ ${this.results.reduce((x, y) => { * @param {*} repo repo param * @returns repoConfigs object */ - async getRepoConfigs(repo) { + async getRepoConfigs (repo) { try { const overridePaths = await this.getRepoConfigMap() const repoConfigs = {} @@ -724,7 +724,7 @@ ${this.results.reduce((x, y) => { * @param params Params to fetch the file with * @return The parsed YAML file */ - async getSubOrgConfigs() { + async getSubOrgConfigs () { try { // Get all suborg configs even though we might be here becuase of a suborg config change // we will filter them out if request is due to a suborg config change @@ -791,7 +791,7 @@ ${this.results.reduce((x, y) => { } )) { delete subOrgConfigs[key] - } + } } } return subOrgConfigs @@ -807,7 +807,7 @@ ${this.results.reduce((x, y) => { } } - storeSubOrgConfigIfNoConflicts(subOrgConfigs, overridePath, repoName, data) { + storeSubOrgConfigIfNoConflicts (subOrgConfigs, overridePath, repoName, data) { const existingConfigForRepo = subOrgConfigs[repoName] if (existingConfigForRepo && existingConfigForRepo.source !== overridePath) { throw new Error(`Multiple suborg configs for ${repoName} in ${overridePath} and ${existingConfigForRepo?.source}`) @@ -821,7 +821,7 @@ ${this.results.reduce((x, y) => { * @param params Params to fetch the file with * @return The parsed YAML file */ - async loadYaml(filePath) { + async loadYaml (filePath) { try { const repo = { owner: this.repo.owner, repo: env.ADMIN_REPO } const params = Object.assign(repo, { path: filePath, ref: this.ref }) @@ -858,16 +858,16 @@ ${this.results.reduce((x, y) => { } } - appendToResults(res) { + appendToResults (res) { if (this.nop) { - //Remove nulls and undefined from the results + // Remove nulls and undefined from the results const results = res.flat(3).filter(r => r) - + this.results = this.results.concat(results) } } - async getReposForTeam(teamslug) { + async getReposForTeam (teamslug) { const options = this.github.rest.teams.listReposInOrg.endpoint.merge({ org: this.repo.owner, team_slug: teamslug, @@ -888,7 +888,7 @@ ${this.results.reduce((x, y) => { return (item && typeof item === 'object' && !Array.isArray(item)) } - isIterable(obj) { + isIterable (obj) { // checks for null and undefined if (obj == null) { return false diff --git a/test/unit/lib/plugins/archive.test.js b/test/unit/lib/plugins/archive.test.js index 9f5804f0..8ab8dcd8 100644 --- a/test/unit/lib/plugins/archive.test.js +++ b/test/unit/lib/plugins/archive.test.js @@ -1,12 +1,11 @@ -const Archive = require('../../../../lib/plugins/archive'); -const NopCommand = require('../../../../lib/nopcommand'); +const Archive = require('../../../../lib/plugins/archive') describe('Archive Plugin', () => { - let github; - let log; - let repo; - let settings; - let nop; + let github + let log + let repo + let settings + let nop beforeEach(() => { github = { @@ -14,55 +13,55 @@ describe('Archive Plugin', () => { get: jest.fn(), update: jest.fn() } - }; + } log = { - debug: jest.fn(), - }; - repo = { owner: 'test-owner', repo: 'test-repo' }; - settings = {}; - nop = false; - }); + debug: jest.fn() + } + repo = { owner: 'test-owner', repo: 'test-repo' } + settings = {} + nop = false + }) it('should return false if the repository is archived and settings.archived is true', async () => { - github.repos.get.mockResolvedValue({ data: { archived: true } }); - settings.archived = true; + github.repos.get.mockResolvedValue({ data: { archived: true } }) + settings.archived = true - const archive = new Archive(nop, github, repo, settings, log); - const result = await archive.sync(); + const archive = new Archive(nop, github, repo, settings, log) + const result = await archive.sync() - expect(result.shouldContinue).toBe(false); - }); + expect(result.shouldContinue).toBe(false) + }) it('should return true if the repository is archived and settings.archived is false', async () => { - github.repos.get.mockResolvedValue({ data: { archived: true } }); - settings.archived = false; + github.repos.get.mockResolvedValue({ data: { archived: true } }) + settings.archived = false - const archive = new Archive(nop, github, repo, settings, log); - const result = await archive.sync(); + const archive = new Archive(nop, github, repo, settings, log) + const result = await archive.sync() - expect(result.shouldContinue).toBe(true); - expect(log.debug).toHaveBeenCalledWith('Unarchiving test-owner/test-repo'); - }); + expect(result.shouldContinue).toBe(true) + expect(log.debug).toHaveBeenCalledWith('Unarchiving test-owner/test-repo') + }) it('should return false if the repository is not archived and settings.archived is true', async () => { - github.repos.get.mockResolvedValue({ data: { archived: false } }); - settings.archived = true; + github.repos.get.mockResolvedValue({ data: { archived: false } }) + settings.archived = true - const archive = new Archive(nop, github, repo, settings, log); - const result = await archive.sync(); + const archive = new Archive(nop, github, repo, settings, log) + const result = await archive.sync() - expect(result.shouldContinue).toBe(false); - expect(log.debug).toHaveBeenCalledWith('Archiving test-owner/test-repo'); - }); + expect(result.shouldContinue).toBe(false) + expect(log.debug).toHaveBeenCalledWith('Archiving test-owner/test-repo') + }) it('should return true if the repository is not archived and settings.archived is false', async () => { - github.repos.get.mockResolvedValue({ data: { archived: false } }); - settings.archived = false; + github.repos.get.mockResolvedValue({ data: { archived: false } }) + settings.archived = false - const archive = new Archive(nop, github, repo, settings, log); - const result = await archive.sync(); + const archive = new Archive(nop, github, repo, settings, log) + const result = await archive.sync() - expect(result.shouldContinue).toBe(true); - expect(log.debug).toHaveBeenCalledWith('Repo test-owner/test-repo is not archived, ignoring.'); - }); -}); \ No newline at end of file + expect(result.shouldContinue).toBe(true) + expect(log.debug).toHaveBeenCalledWith('Repo test-owner/test-repo is not archived, ignoring.') + }) +}) diff --git a/test/unit/lib/plugins/environments.test.js b/test/unit/lib/plugins/environments.test.js index 8b5467de..ef7784e1 100644 --- a/test/unit/lib/plugins/environments.test.js +++ b/test/unit/lib/plugins/environments.test.js @@ -1,6 +1,6 @@ const { when } = require('jest-when') const Environments = require('../../../../lib/plugins/environments') -const NopCommand = require('../../../../lib/nopcommand'); +const NopCommand = require('../../../../lib/nopcommand') describe('Environments Plugin test suite', () => { let github @@ -1063,37 +1063,37 @@ describe('Environments Plugin test suite', () => { }) describe('nopifyRequest', () => { - let github; - let plugin; - const org = 'bkeepers'; - const repo = 'test'; - const environment_name = 'test-environment'; - const url = 'PUT /repos/:org/:repo/environments/:environment_name'; - const options = { org, repo, environment_name, wait_timer: 1 }; - const description = 'Update environment wait timer'; + let github + let plugin + const org = 'bkeepers' + const repo = 'test' + const environmentName = 'test-environment' + const url = 'PUT /repos/:org/:repo/environments/:environment_name' + const options = { org, repo, environment_name: environmentName, wait_timer: 1 } + const description = 'Update environment wait timer' beforeEach(() => { github = { request: jest.fn(() => Promise.resolve(true)) - }; - plugin = new Environments(undefined, github, { owner: org, repo }, [], { debug: jest.fn(), error: console.error }, []); - }); + } + plugin = new Environments(undefined, github, { owner: org, repo }, [], { debug: jest.fn(), error: console.error }, []) + }) it('should make a request when nop is false', async () => { - plugin.nop = false; + plugin.nop = false - await plugin.nopifyRequest(url, options, description); + await plugin.nopifyRequest(url, options, description) - expect(github.request).toHaveBeenCalledWith(url, options); - }); + expect(github.request).toHaveBeenCalledWith(url, options) + }) it('should return NopCommand when nop is true', async () => { - plugin.nop = true; + plugin.nop = true - const result = await plugin.nopifyRequest(url, options, description); + const result = await plugin.nopifyRequest(url, options, description) expect(result).toEqual([ new NopCommand('Environments', { owner: org, repo }, url, description) - ]); - }); -}); + ]) + }) +}) diff --git a/test/unit/lib/plugins/rulesets.test.js b/test/unit/lib/plugins/rulesets.test.js index f15abd63..ca0c25b0 100644 --- a/test/unit/lib/plugins/rulesets.test.js +++ b/test/unit/lib/plugins/rulesets.test.js @@ -1,34 +1,33 @@ /* eslint-disable no-undef */ -const { when } = require('jest-when') const Rulesets = require('../../../../lib/plugins/rulesets') const version = { 'X-GitHub-Api-Version': '2022-11-28' } -const repo_conditions = { +const repoConditions = { ref_name: { include: ['~ALL'], exclude: [] - }, + } } -const org_conditions = { +const orgConditions = { ref_name: { include: ['~ALL'], exclude: [] }, repository_name: { - include: ["~ALL"], - exclude: ["admin"] + include: ['~ALL'], + exclude: ['admin'] } } -function generateRequestRuleset(id, name, conditions, checks, org=false) { +function generateRequestRuleset (id, name, conditions, checks, org = false) { request = { - id: id, - name: name, + id, + name, target: 'branch', enforcement: 'active', - conditions: conditions, + conditions, rules: [ { type: 'required_status_checks', @@ -50,13 +49,13 @@ function generateRequestRuleset(id, name, conditions, checks, org=false) { return request } -function generateResponseRuleset(id, name, conditions, checks, org=false) { +function generateResponseRuleset (id, name, conditions, checks, org = false) { response = { - id: id, - name: name, + id, + name, target: 'branch', enforcement: 'active', - conditions: conditions, + conditions, rules: [ { type: 'required_status_checks', @@ -66,7 +65,7 @@ function generateResponseRuleset(id, name, conditions, checks, org=false) { } } ], - headers: version, + headers: version } if (org) { response.source_type = 'Organization' @@ -88,7 +87,7 @@ describe('Rulesets', () => { log.debug = jest.fn() log.error = jest.fn() - function configure (config, scope='repo') { + function configure (config, scope = 'repo') { const noop = false const errors = [] return new Rulesets(noop, github, { owner: 'jitran', repo: 'test' }, config, log, errors, scope) @@ -103,7 +102,7 @@ describe('Rulesets', () => { } }) }, - request: jest.fn().mockImplementation(() => Promise.resolve('request')), + request: jest.fn().mockImplementation(() => Promise.resolve('request')) } github.request.endpoint = { @@ -111,7 +110,7 @@ describe('Rulesets', () => { method: 'GET', url: '/repos/jitran/test/rulesets', headers: version - } + } ) } }) @@ -127,7 +126,7 @@ describe('Rulesets', () => { generateRequestRuleset( 1, 'All branches', - repo_conditions, + repoConditions, [ { context: 'Status Check 1' }, { context: 'Status Check 2' } @@ -142,7 +141,7 @@ describe('Rulesets', () => { generateResponseRuleset( 1, 'All branches', - repo_conditions, + repoConditions, [ { context: 'Status Check 1' }, { context: 'Status Check 2' } @@ -164,7 +163,7 @@ describe('Rulesets', () => { generateRequestRuleset( 1, 'All branches', - repo_conditions, + repoConditions, [ { context: 'Status Check 1' }, { context: '{{EXTERNALLY_DEFINED}}' } @@ -179,7 +178,7 @@ describe('Rulesets', () => { generateResponseRuleset( 1, 'All branches', - repo_conditions, + repoConditions, [] ) ) @@ -194,7 +193,7 @@ describe('Rulesets', () => { generateRequestRuleset( 1, 'All branches 1', - repo_conditions, + repoConditions, [ { context: 'Custom Check 1' }, { context: 'Custom Check 2' } @@ -203,7 +202,7 @@ describe('Rulesets', () => { generateRequestRuleset( 2, 'All branches 2', - repo_conditions, + repoConditions, [ { context: 'Custom Check 3' }, { context: 'Custom Check 4' } @@ -212,7 +211,7 @@ describe('Rulesets', () => { generateRequestRuleset( 3, 'All branches 3', - repo_conditions, + repoConditions, [ { context: 'Custom Check 5' }, { context: 'Custom Check 6' } @@ -226,7 +225,7 @@ describe('Rulesets', () => { generateRequestRuleset( 1, 'All branches 1', - repo_conditions, + repoConditions, [ { context: 'Status Check 1' }, { context: '{{EXTERNALLY_DEFINED}}' } @@ -235,7 +234,7 @@ describe('Rulesets', () => { generateRequestRuleset( 2, 'All branches 2', - repo_conditions, + repoConditions, [ { context: 'Status Check 1' }, { context: 'Status Check 2' } @@ -244,7 +243,7 @@ describe('Rulesets', () => { generateRequestRuleset( 3, 'All branches 3', - repo_conditions, + repoConditions, [] ) ] @@ -257,7 +256,7 @@ describe('Rulesets', () => { generateResponseRuleset( 1, 'All branches 1', - repo_conditions, + repoConditions, [ { context: 'Custom Check 1' }, { context: 'Custom Check 2' } @@ -270,7 +269,7 @@ describe('Rulesets', () => { generateResponseRuleset( 2, 'All branches 2', - repo_conditions, + repoConditions, [ { context: 'Status Check 1' }, { context: 'Status Check 2' } @@ -283,7 +282,7 @@ describe('Rulesets', () => { generateResponseRuleset( 3, 'All branches 3', - repo_conditions, + repoConditions, [] ) ) @@ -302,7 +301,7 @@ describe('Rulesets', () => { generateRequestRuleset( 1, 'All branches', - org_conditions, + orgConditions, [ { context: 'Status Check 1' }, { context: 'Status Check 2' } @@ -319,7 +318,7 @@ describe('Rulesets', () => { generateResponseRuleset( 1, 'All branches', - org_conditions, + orgConditions, [ { context: 'Status Check 1' }, { context: 'Status Check 2' } @@ -342,7 +341,7 @@ describe('Rulesets', () => { generateRequestRuleset( 1, 'All branches', - org_conditions, + orgConditions, [ { context: 'Status Check 1' }, { context: '{{EXTERNALLY_DEFINED}}' } @@ -359,7 +358,7 @@ describe('Rulesets', () => { generateResponseRuleset( 1, 'All branches', - org_conditions, + orgConditions, [], true ) @@ -375,7 +374,7 @@ describe('Rulesets', () => { generateRequestRuleset( 1, 'All branches 1', - org_conditions, + orgConditions, [ { context: 'Custom Check 1' }, { context: 'Custom Check 2' } @@ -390,7 +389,7 @@ describe('Rulesets', () => { generateRequestRuleset( 1, 'All branches 1', - org_conditions, + orgConditions, [ { context: 'Status Check 1' }, { context: '{{EXTERNALLY_DEFINED}}' } @@ -408,7 +407,7 @@ describe('Rulesets', () => { generateResponseRuleset( 1, 'All branches 1', - org_conditions, + orgConditions, [ { context: 'Custom Check 1' }, { context: 'Custom Check 2' } diff --git a/test/unit/lib/settings.test.js b/test/unit/lib/settings.test.js index c91583d3..f7df9491 100644 --- a/test/unit/lib/settings.test.js +++ b/test/unit/lib/settings.test.js @@ -8,7 +8,6 @@ const yaml = require('js-yaml') // return OriginalSettings // }) - describe('Settings Tests', () => { let stubContext let mockRepo @@ -17,9 +16,9 @@ describe('Settings Tests', () => { let mockSubOrg let subOrgConfig - function createSettings(config) { + function createSettings (config) { const settings = new Settings(false, stubContext, mockRepo, config, mockRef, mockSubOrg) - return settings; + return settings } beforeEach(() => { @@ -52,7 +51,7 @@ repository: # A comma-separated list of topics to set on the repository topics: - frontend - `).toString('base64'); + `).toString('base64') mockOctokit.repos = { getContent: jest.fn().mockResolvedValue({ data: { content } }) } @@ -83,8 +82,6 @@ repository: } } - - mockRepo = { owner: 'test', repo: 'test-repo' } mockRef = 'main' mockSubOrg = 'frontend' @@ -224,14 +221,13 @@ repository: - frontend `) - }) it("Should load configMap for suborgs'", async () => { - //mockSubOrg = jest.fn().mockReturnValue(['suborg1', 'suborg2']) + // mockSubOrg = jest.fn().mockReturnValue(['suborg1', 'suborg2']) mockSubOrg = undefined settings = createSettings(stubConfig) - jest.spyOn(settings, 'loadConfigMap').mockImplementation(() => [{ name: "frontend", path: ".github/suborgs/frontend.yml" }]) + jest.spyOn(settings, 'loadConfigMap').mockImplementation(() => [{ name: 'frontend', path: '.github/suborgs/frontend.yml' }]) jest.spyOn(settings, 'loadYaml').mockImplementation(() => subOrgConfig) jest.spyOn(settings, 'getReposForTeam').mockImplementation(() => [{ name: 'repo-test' }]) jest.spyOn(settings, 'getReposForCustomProperty').mockImplementation(() => [{ repository_name: 'repo-for-property' }]) @@ -240,15 +236,15 @@ repository: expect(settings.loadConfigMap).toHaveBeenCalledTimes(1) // Get own properties of subOrgConfigs - const ownProperties = Object.getOwnPropertyNames(subOrgConfigs); + const ownProperties = Object.getOwnPropertyNames(subOrgConfigs) expect(ownProperties.length).toEqual(3) }) it("Should throw an error when a repo is found in multiple suborgs configs'", async () => { - //mockSubOrg = jest.fn().mockReturnValue(['suborg1', 'suborg2']) + // mockSubOrg = jest.fn().mockReturnValue(['suborg1', 'suborg2']) mockSubOrg = undefined settings = createSettings(stubConfig) - jest.spyOn(settings, 'loadConfigMap').mockImplementation(() => [{ name: "frontend", path: ".github/suborgs/frontend.yml" }, { name: "backend", path: ".github/suborgs/backend.yml" }]) + jest.spyOn(settings, 'loadConfigMap').mockImplementation(() => [{ name: 'frontend', path: '.github/suborgs/frontend.yml' }, { name: 'backend', path: '.github/suborgs/backend.yml' }]) jest.spyOn(settings, 'loadYaml').mockImplementation(() => subOrgConfig) jest.spyOn(settings, 'getReposForTeam').mockImplementation(() => [{ name: 'repo-test' }]) jest.spyOn(settings, 'getReposForCustomProperty').mockImplementation(() => [{ repository_name: 'repo-for-property' }]) @@ -262,5 +258,4 @@ repository: }) }) }) // loadConfigs - }) // Settings Tests