From d3510fda9c67ece6f6386e103bf8fd990c31dbc8 Mon Sep 17 00:00:00 2001 From: Torgeir S Date: Sat, 5 Oct 2024 17:36:34 +0200 Subject: [PATCH] chore: autoformatted after changed eslint config in #664 Mostly, the changes in #664 relaxes the eslint rules, but that PR also removes the space before the parentheses in function definitions. The formatting was done with the vscode js/ts formatter `vscode.typescript-language-features`, and since this also does the same change it is now consistent across the whole codebase. Other than removing the space-before-function-paren, some files with inconsistent indentation and/or trailing spaces has been updated. --- index.js | 42 +-- lib/commentmessage.js | 4 +- lib/configManager.js | 6 +- lib/deploymentConfig.js | 68 ++-- lib/error.js | 4 +- lib/glob.js | 14 +- lib/mergeArrayBy.js | 4 +- lib/mergeDeep.js | 28 +- lib/nopcommand.js | 4 +- lib/plugins/autolinks.js | 12 +- lib/plugins/branches.js | 8 +- lib/plugins/collaborators.js | 34 +- lib/plugins/custom_properties.js | 14 +- lib/plugins/diffable.js | 6 +- lib/plugins/environments.js | 210 ++++++------ lib/plugins/errorStash.js | 4 +- lib/plugins/labels.js | 18 +- lib/plugins/milestones.js | 14 +- lib/plugins/repository.js | 28 +- lib/plugins/rulesets.js | 20 +- lib/plugins/teams.js | 14 +- lib/plugins/validator.js | 6 +- lib/settings.js | 12 +- test/integration/common.js | 14 +- test/unit/index.test.js | 6 +- test/unit/lib/glob.test.ts | 1 - test/unit/lib/mergeArrayBy.test.js | 24 +- test/unit/lib/mergeDeep.test.js | 204 +++++------ test/unit/lib/plugins/autolinks.test.js | 34 +- test/unit/lib/plugins/branches.test.js | 2 +- test/unit/lib/plugins/collaborators.test.js | 2 +- .../lib/plugins/custom_properties.test.js | 2 +- test/unit/lib/plugins/environments.test.js | 318 +++++++++--------- test/unit/lib/plugins/labels.test.js | 2 +- test/unit/lib/plugins/milestones.test.js | 4 +- test/unit/lib/plugins/repository.test.js | 2 +- test/unit/lib/plugins/teams.test.js | 2 +- test/unit/lib/settings.test.js | 56 +-- 38 files changed, 623 insertions(+), 624 deletions(-) diff --git a/index.js b/index.js index 7e4ef032..e7992b37 100644 --- a/index.js +++ b/index.js @@ -13,7 +13,7 @@ let deploymentConfig module.exports = (robot, { getRouter }, Settings = require('./lib/settings')) => { let appName = 'safe-settings' let appSlug = 'safe-settings' - async function syncAllSettings (nop, context, repo = context.repo(), ref) { + async function syncAllSettings(nop, context, repo = context.repo(), ref) { try { deploymentConfig = await loadYamlFileSystem() robot.log.debug(`deploymentConfig is ${JSON.stringify(deploymentConfig)}`) @@ -42,7 +42,7 @@ module.exports = (robot, { getRouter }, Settings = require('./lib/settings')) => } } - async function syncSubOrgSettings (nop, context, suborg, repo = context.repo(), ref) { + async function syncSubOrgSettings(nop, context, suborg, repo = context.repo(), ref) { try { deploymentConfig = await loadYamlFileSystem() robot.log.debug(`deploymentConfig is ${JSON.stringify(deploymentConfig)}`) @@ -67,7 +67,7 @@ module.exports = (robot, { getRouter }, Settings = require('./lib/settings')) => } } - async function syncSettings (nop, context, repo = context.repo(), ref) { + async function syncSettings(nop, context, repo = context.repo(), ref) { try { deploymentConfig = await loadYamlFileSystem() robot.log.debug(`deploymentConfig is ${JSON.stringify(deploymentConfig)}`) @@ -92,7 +92,7 @@ module.exports = (robot, { getRouter }, Settings = require('./lib/settings')) => } } - async function renameSync (nop, context, repo = context.repo(), rename, ref) { + async function renameSync(nop, context, repo = context.repo(), rename, ref) { try { deploymentConfig = await loadYamlFileSystem() robot.log.debug(`deploymentConfig is ${JSON.stringify(deploymentConfig)}`) @@ -101,7 +101,7 @@ module.exports = (robot, { getRouter }, Settings = require('./lib/settings')) => const config = Object.assign({}, deploymentConfig, runtimeConfig) const renameConfig = Object.assign({}, config, rename) robot.log.debug(`config for ref ${ref} is ${JSON.stringify(config)}`) - return Settings.sync(nop, context, repo, renameConfig, ref ) + return Settings.sync(nop, context, repo, renameConfig, ref) } catch (e) { if (nop) { let filename = env.SETTINGS_FILE_PATH @@ -123,7 +123,7 @@ module.exports = (robot, { getRouter }, Settings = require('./lib/settings')) => * * @return The parsed YAML file */ - async function loadYamlFileSystem () { + async function loadYamlFileSystem() { if (deploymentConfig === undefined) { const deploymentConfigPath = env.DEPLOYMENT_CONFIG_FILE if (fs.existsSync(deploymentConfigPath)) { @@ -135,7 +135,7 @@ module.exports = (robot, { getRouter }, Settings = require('./lib/settings')) => return deploymentConfig } - function getAllChangedSubOrgConfigs (payload) { + function getAllChangedSubOrgConfigs(payload) { const settingPattern = new Glob(`${env.CONFIG_PATH}/suborgs/*.yml`) // Changes will be an array of files that were added const added = payload.commits.map(c => { @@ -159,7 +159,7 @@ module.exports = (robot, { getRouter }, Settings = require('./lib/settings')) => return configs } - function getAllChangedRepoConfigs (payload, owner) { + function getAllChangedRepoConfigs(payload, owner) { const settingPattern = new Glob(`${env.CONFIG_PATH}/repos/*.yml`) // Changes will be an array of files that were added const added = payload.commits.map(c => { @@ -182,7 +182,7 @@ module.exports = (robot, { getRouter }, Settings = require('./lib/settings')) => return configs } - function getChangedRepoConfigName (glob, files, owner) { + function getChangedRepoConfigName(glob, files, owner) { const modifiedFiles = files.filter(s => { robot.log.debug(JSON.stringify(s)) return (s.search(glob) >= 0) @@ -193,7 +193,7 @@ module.exports = (robot, { getRouter }, Settings = require('./lib/settings')) => }) } - function getChangedSubOrgConfigName (glob, files) { + function getChangedSubOrgConfigName(glob, files) { const modifiedFiles = files.filter(s => { robot.log.debug(JSON.stringify(s)) return (s.search(glob) >= 0) @@ -205,7 +205,7 @@ module.exports = (robot, { getRouter }, Settings = require('./lib/settings')) => }) } - async function createCheckRun (context, pull_request, head_sha, head_branch) { + async function createCheckRun(context, pull_request, head_sha, head_branch) { const { payload } = context // robot.log.debug(`Check suite was requested! for ${context.repo()} ${pull_request.number} ${head_sha} ${head_branch}`) const res = await context.octokit.checks.create({ @@ -234,7 +234,7 @@ module.exports = (robot, { getRouter }, Settings = require('./lib/settings')) => } - async function syncInstallation () { + async function syncInstallation() { robot.log.trace('Fetching installations') const github = await robot.auth() @@ -395,7 +395,7 @@ module.exports = (robot, { getRouter }, Settings = require('./lib/settings')) => }) robot.on('repository.renamed', async context => { - if (env.BLOCK_REPO_RENAME_BY_HUMAN!== 'true') { + if (env.BLOCK_REPO_RENAME_BY_HUMAN !== 'true') { robot.log.debug(`"env.BLOCK_REPO_RENAME_BY_HUMAN" is 'false' by default. Repo rename is not managed by Safe-settings. Continue with the default behavior.`) return } @@ -414,7 +414,7 @@ module.exports = (robot, { getRouter }, Settings = require('./lib/settings')) => const newPath = `.github/repos/${payload.repository.name}.yml` robot.log.debug(oldPath) try { - const repofile = await context.octokit.request('GET /repos/{owner}/{repo}/contents/{path}', { + const repofile = await context.octokit.request('GET /repos/{owner}/{repo}/contents/{path}', { owner: payload.repository.owner.login, repo: env.ADMIN_REPO, path: oldPath, @@ -443,7 +443,7 @@ module.exports = (robot, { getRouter }, Settings = require('./lib/settings')) => owner: payload.repository.owner.login, repo: env.ADMIN_REPO, path: newPath, - name: `${payload.repository.name}.yml`, + name: `${payload.repository.name}.yml`, content: content, message: `Repo Renamed and safe-settings renamed the file from ${payload.changes.repository.name.from} to ${payload.repository.name}`, sha: repofile.data.sha, @@ -455,21 +455,21 @@ module.exports = (robot, { getRouter }, Settings = require('./lib/settings')) => } else { robot.log.error(error) } - } + } } catch (error) { if (error.status === 404) { //nop - } else { + } else { robot.log.error(error) } - } + } return } else { robot.log.debug('Repository Edited by a Human') // Create a repository config to reset the name back to the previous name - const rename = {repository: { name: payload.changes.repository.name.from, oldname: payload.repository.name}} - const repo = {repo: payload.changes.repository.name.from, owner: payload.repository.owner.login} + const rename = { repository: { name: payload.changes.repository.name.from, oldname: payload.repository.name } } + const repo = { repo: payload.changes.repository.name.from, owner: payload.repository.owner.login } return renameSync(false, context, repo, rename) } }) @@ -663,7 +663,7 @@ module.exports = (robot, { getRouter }, Settings = require('./lib/settings')) => syncInstallation() }) } - + // Get info about the app info() diff --git a/lib/commentmessage.js b/lib/commentmessage.js index 93d97039..81364f19 100644 --- a/lib/commentmessage.js +++ b/lib/commentmessage.js @@ -5,7 +5,7 @@ module.exports = `* Run on: \` <%= new Date() %> \` ### Breakdown of changes | Repo <% Object.keys(it.changes).forEach(plugin => { %> | <%= plugin %> settings <% }) %> | | -- <% Object.keys(it.changes).forEach(plugin => { -%> | -- <% }) %> -| +| <% Object.keys(it.reposProcessed).forEach( repo => { -%> | <%= repo -%> <%- Object.keys(it.changes).forEach(plugin => { -%> @@ -22,7 +22,7 @@ module.exports = `* Run on: \` <%= new Date() %> \` \`None\` <% } else { %> <% Object.keys(it.errors).forEach(repo => { %> - <%_= repo %>: + <%_= repo %>: <% it.errors[repo].forEach(plugin => { %> * <%= plugin.msg %> <% }) %> diff --git a/lib/configManager.js b/lib/configManager.js index 58f5bb43..efaa18e2 100644 --- a/lib/configManager.js +++ b/lib/configManager.js @@ -3,7 +3,7 @@ const yaml = require('js-yaml') const env = require('./env') module.exports = class ConfigManager { - constructor (context, ref) { + constructor(context, ref) { this.context = context this.ref = ref this.log = context.log @@ -15,7 +15,7 @@ module.exports = class ConfigManager { * @param params Params to fetch the file with * @return The parsed YAML file */ - async loadYaml (filePath) { + async loadYaml(filePath) { try { const repo = { owner: this.context.repo().owner, repo: env.ADMIN_REPO } const params = Object.assign(repo, { path: filePath, ref: this.ref }) @@ -50,7 +50,7 @@ module.exports = class ConfigManager { * @param params Params to fetch the file with * @return The parsed YAML file */ - async loadGlobalSettingsYaml () { + async loadGlobalSettingsYaml() { const CONFIG_PATH = env.CONFIG_PATH const filePath = path.posix.join(CONFIG_PATH, env.SETTINGS_FILE_PATH) return this.loadYaml(filePath) diff --git a/lib/deploymentConfig.js b/lib/deploymentConfig.js index f8fdeb27..b200a329 100644 --- a/lib/deploymentConfig.js +++ b/lib/deploymentConfig.js @@ -8,46 +8,46 @@ const env = require('./env') * The settings are loaded from the deployment-settings.yml file during initialization and stored as static properties. */ class DeploymentConfig { - //static config - static configvalidators = {} - static overridevalidators = {} + //static config + static configvalidators = {} + static overridevalidators = {} - static { - const deploymentConfigPath = process.env.DEPLOYMENT_CONFIG_FILE ? process.env.DEPLOYMENT_CONFIG_FILE : 'deployment-settings.yml' - if (fs.existsSync(deploymentConfigPath)) { - this.config = yaml.load(fs.readFileSync(deploymentConfigPath)) - } else { - this.config = { restrictedRepos: ['admin', '.github', 'safe-settings'] } - } - - const overridevalidators = this.config.overridevalidators - if (this.isIterable(overridevalidators)) { - for (const validator of overridevalidators) { - // eslint-disable-next-line no-new-func - const f = new Function('baseconfig', 'overrideconfig', 'githubContext', validator.script) - this.overridevalidators[validator.plugin] = { canOverride: f, error: validator.error } - } - } - const configvalidators = this.config.configvalidators - if (this.isIterable(configvalidators)) { - for (const validator of configvalidators) { - // eslint-disable-next-line no-new-func - const f = new Function('baseconfig', 'githubContext', validator.script) - this.configvalidators[validator.plugin] = { isValid: f, error: validator.error } - } - } + static { + const deploymentConfigPath = process.env.DEPLOYMENT_CONFIG_FILE ? process.env.DEPLOYMENT_CONFIG_FILE : 'deployment-settings.yml' + if (fs.existsSync(deploymentConfigPath)) { + this.config = yaml.load(fs.readFileSync(deploymentConfigPath)) + } else { + this.config = { restrictedRepos: ['admin', '.github', 'safe-settings'] } } - static isIterable (obj) { - // checks for null and undefined - if (obj == null) { - return false - } - return typeof obj[Symbol.iterator] === 'function' + const overridevalidators = this.config.overridevalidators + if (this.isIterable(overridevalidators)) { + for (const validator of overridevalidators) { + // eslint-disable-next-line no-new-func + const f = new Function('baseconfig', 'overrideconfig', 'githubContext', validator.script) + this.overridevalidators[validator.plugin] = { canOverride: f, error: validator.error } + } + } + const configvalidators = this.config.configvalidators + if (this.isIterable(configvalidators)) { + for (const validator of configvalidators) { + // eslint-disable-next-line no-new-func + const f = new Function('baseconfig', 'githubContext', validator.script) + this.configvalidators[validator.plugin] = { isValid: f, error: validator.error } } + } + } - constructor (nop, context, repo, config, ref, suborg) { + static isIterable(obj) { + // checks for null and undefined + if (obj == null) { + return false } + return typeof obj[Symbol.iterator] === 'function' + } + + constructor(nop, context, repo, config, ref, suborg) { + } } DeploymentConfig.FILE_NAME = `${env.CONFIG_PATH}/settings.yml` diff --git a/lib/error.js b/lib/error.js index f268ac6c..4b1fc5e2 100644 --- a/lib/error.js +++ b/lib/error.js @@ -1,8 +1,8 @@ module.exports = `Run on: \`<%= new Date().toISOString() %>\` #### Breakdown of Errors -| Owner| Repo | Plugin | Error -| --- | --- | --- | --- +| Owner| Repo | Plugin | Error +| --- | --- | --- | --- <% it.forEach( error => { -%> <%= error.owner %> | <%= error.repo %> | <%= error.plugin %> | <%= error.msg %> diff --git a/lib/glob.js b/lib/glob.js index 78a0eaaf..448a02ea 100644 --- a/lib/glob.js +++ b/lib/glob.js @@ -1,5 +1,5 @@ class Glob { - constructor (glob) { + constructor(glob) { this.glob = glob // If not a glob pattern then just match the string. @@ -11,7 +11,7 @@ class Glob { this.regexp = new RegExp(`^${this.regexptText}$`, 'u') } - globize (glob) { + globize(glob) { return glob .replace(/\\/g, '\\\\') // escape backslashes .replace(/\//g, '\\/') // escape forward slashes @@ -21,23 +21,23 @@ class Glob { .replace(/\*/g, '([^\\/]*)') // match any character except / } - toString () { + toString() { return this.glob } - [Symbol.search] (s) { + [Symbol.search](s) { return s.search(this.regexp) } - [Symbol.match] (s) { + [Symbol.match](s) { return s.match(this.regexp) } - [Symbol.replace] (s, replacement) { + [Symbol.replace](s, replacement) { return s.replace(this.regexp, replacement) } - [Symbol.replaceAll] (s, replacement) { + [Symbol.replaceAll](s, replacement) { return s.replaceAll(this.regexp, replacement) } } diff --git a/lib/mergeArrayBy.js b/lib/mergeArrayBy.js index 9faa42e2..d73803e5 100644 --- a/lib/mergeArrayBy.js +++ b/lib/mergeArrayBy.js @@ -2,7 +2,7 @@ const merge = require('deepmerge') -function findMatchingIndex (properties, sourceItem, target) { +function findMatchingIndex(properties, sourceItem, target) { const hasAnyProperty = item => properties.some(prop => Object.prototype.hasOwnProperty.call(item, prop)) if (hasAnyProperty(sourceItem)) { return target @@ -11,7 +11,7 @@ function findMatchingIndex (properties, sourceItem, target) { } } -function mergeBy (key, configvalidator, overridevalidator, properties, target, source, options, githubContext) { +function mergeBy(key, configvalidator, overridevalidator, properties, target, source, options, githubContext) { const destination = target.slice() source.forEach(sourceItem => { const matchingIndex = findMatchingIndex(properties, sourceItem, target) diff --git a/lib/mergeDeep.js b/lib/mergeDeep.js index 054a5b34..244cfa6c 100644 --- a/lib/mergeDeep.js +++ b/lib/mergeDeep.js @@ -6,7 +6,7 @@ const NAME_USERNAME_PROPERTY = item => NAME_FIELDS.find(prop => Object.prototype const GET_NAME_USERNAME_PROPERTY = item => { if (NAME_USERNAME_PROPERTY(item)) return item[NAME_USERNAME_PROPERTY(item)] } class MergeDeep { - constructor (log, github, ignorableFields = [], configvalidators = {}, overridevalidators = {}) { + constructor(log, github, ignorableFields = [], configvalidators = {}, overridevalidators = {}) { this.log = log this.github = github this.ignorableFields = ignorableFields @@ -14,15 +14,15 @@ class MergeDeep { this.overridevalidators = DeploymentConfig.overridevalidators } - isObjectNotArray (item) { + isObjectNotArray(item) { return (item && typeof item === 'object' && !Array.isArray(item)) } - isObject (item) { + isObject(item) { return (item && typeof item === 'object') } - isEmpty (item) { + isEmpty(item) { if (this.isObjectNotArray(item)) { return Object.keys(item).length === 0 } else if (Array.isArray(item)) { @@ -53,7 +53,7 @@ class MergeDeep { * @param {*} deletions aggregated so far * @returns object with additions, modifications, and deletions */ - compareDeep (t, s, additions, modifications, deletions) { + compareDeep(t, s, additions, modifications, deletions) { // Preemtively return if the source is not an object or array if (!this.isObject(s)) { return { additions, modifications, deletions, hasChanges: s !== t } @@ -158,7 +158,7 @@ class MergeDeep { return ({ additions, modifications, deletions, hasChanges: !this.isEmpty(additions) || !this.isEmpty(modifications) || !this.isEmpty(deletions) }) } - addIdentifyingAttribute (source, key, containerObject) { + addIdentifyingAttribute(source, key, containerObject) { const id = NAME_USERNAME_PROPERTY(source) if (id) { this.log.debug(`Adding name for ${key} ${source[key]}`) @@ -175,7 +175,7 @@ class MergeDeep { * @param {*} additions * @param {*} modifications */ - processArrays (key, source, target, deletions, additions, modifications) { + processArrays(key, source, target, deletions, additions, modifications) { // If source array has lesser items than target array, then the missing items are deletions if (source.length < target.length) { const dels = target.filter(item => { @@ -237,7 +237,7 @@ class MergeDeep { } } - compareDeepIfVisited (additions, modifications, deletions, a, visited) { + compareDeepIfVisited(additions, modifications, deletions, a, visited) { const id = GET_NAME_USERNAME_PROPERTY(a) if (visited[id]) { // Common array in target and source @@ -278,7 +278,7 @@ class MergeDeep { return false } - validateOverride (key, baseconfig, overrideconfig) { + validateOverride(key, baseconfig, overrideconfig) { if (!baseconfig || !key || !overrideconfig) { return } @@ -291,7 +291,7 @@ class MergeDeep { } } - validateConfig (key, baseconfig) { + validateConfig(key, baseconfig) { if (this.configvalidators[key]) { // this.log.debug(`Calling configvalidator for key ${key} `) if (!this.configvalidators[key].isValid(baseconfig, this.github)) { @@ -301,7 +301,7 @@ class MergeDeep { } } - mergeEmptyTarget (target, source) { + mergeEmptyTarget(target, source) { if (Array.isArray(source)) { target = Array.isArray(target) ? target.concat(source) : source } else { @@ -310,7 +310,7 @@ class MergeDeep { return target } - mergeDeep (immutabletarget, ...sources) { + mergeDeep(immutabletarget, ...sources) { let target = Object.assign({}, immutabletarget) while (sources.length) { const source = sources.shift() @@ -344,7 +344,7 @@ class MergeDeep { return target } - removeEmptyAndNullsWithoutKeys (modifications) { + removeEmptyAndNullsWithoutKeys(modifications) { if (Array.isArray(modifications)) { modifications = modifications.filter(k => { return !this.isEmpty(k) @@ -353,7 +353,7 @@ class MergeDeep { return modifications } - removeEmptyAndNulls (modifications, key) { + removeEmptyAndNulls(modifications, key) { if (Array.isArray(modifications[key])) { modifications[key] = modifications[key].filter(k => { return !this.isEmpty(k) diff --git a/lib/nopcommand.js b/lib/nopcommand.js index 75965a8b..59d74884 100644 --- a/lib/nopcommand.js +++ b/lib/nopcommand.js @@ -1,5 +1,5 @@ class NopCommand { - constructor (pluginName, repo, endpoint, action, type = 'INFO') { + constructor(pluginName, repo, endpoint, action, type = 'INFO') { this.type = type this.plugin = pluginName this.repo = repo.repo @@ -13,7 +13,7 @@ class NopCommand { } } - toString () { + toString() { return `${this.plugin} plugin will perform ${this.action} using this API ${this.endpoint} passing ${JSON.stringify(this.body, null, 4)}` } } diff --git a/lib/plugins/autolinks.js b/lib/plugins/autolinks.js index 128e4021..ca530d84 100644 --- a/lib/plugins/autolinks.js +++ b/lib/plugins/autolinks.js @@ -7,16 +7,16 @@ module.exports = class Autolinks extends Diffable { // super(...args) // } - async find () { + async find() { const { data } = await this.github.repos.listAutolinks(this.repo) return data } - comparator (existing, attr) { + comparator(existing, attr) { return existing.key_prefix === attr.key_prefix } - changed (existing, attr) { + changed(existing, attr) { // is_alphanumeric was added mid-2023. In order to continue to support settings yamls which dont specify this // attribute, consider an unset is_alphanumeric as `true` (since that is the default value in the API) // https://docs.github.com/en/rest/repos/autolinks?apiVersion=2022-11-28#create-an-autolink-reference-for-a-repository @@ -26,12 +26,12 @@ module.exports = class Autolinks extends Diffable { return existing.url_template !== attr.url_template || !isAlphaNumericMatch } - async update (existing, attr) { + async update(existing, attr) { await this.remove(existing) return this.add(attr) } - async add ({ key_prefix, url_template, is_alphanumeric = true }) { + async add({ key_prefix, url_template, is_alphanumeric = true }) { const attrs = { ...this.repo, key_prefix, @@ -59,7 +59,7 @@ module.exports = class Autolinks extends Diffable { } } - async remove ({ id }) { + async remove({ id }) { const attrs = { ...this.repo, autolink_id: id diff --git a/lib/plugins/branches.js b/lib/plugins/branches.js index cac0aadf..059e178c 100644 --- a/lib/plugins/branches.js +++ b/lib/plugins/branches.js @@ -5,7 +5,7 @@ const ignorableFields = [] const previewHeaders = { accept: 'application/vnd.github.hellcat-preview+json,application/vnd.github.luke-cage-preview+json,application/vnd.github.zzzax-preview+json' } module.exports = class Branches extends ErrorStash { - constructor (nop, github, repo, settings, log, errors) { + constructor(nop, github, repo, settings, log, errors) { super(errors) this.github = github this.repo = repo @@ -14,7 +14,7 @@ module.exports = class Branches extends ErrorStash { this.nop = nop } - sync () { + sync() { const resArray = [] return this.github.repos.get(this.repo).then((currentRepo) => { return Promise.all( @@ -104,11 +104,11 @@ module.exports = class Branches extends ErrorStash { }) } - isEmpty (maybeEmpty) { + isEmpty(maybeEmpty) { return (maybeEmpty === null) || Object.keys(maybeEmpty).length === 0 } - reformatAndReturnBranchProtection (protection) { + reformatAndReturnBranchProtection(protection) { if (protection) { // Re-format the enabled protection attributes protection.required_conversation_resolution = protection.required_conversation_resolution && protection.required_conversation_resolution.enabled diff --git a/lib/plugins/collaborators.js b/lib/plugins/collaborators.js index 21415180..cec95f8f 100644 --- a/lib/plugins/collaborators.js +++ b/lib/plugins/collaborators.js @@ -3,7 +3,7 @@ const Diffable = require('./diffable') const NopCommand = require('../nopcommand') module.exports = class Collaborators extends Diffable { - constructor (...args) { + constructor(...args) { super(...args) if (this.entries) { @@ -14,11 +14,11 @@ module.exports = class Collaborators extends Diffable { } } - find () { + find() { // this.log.debug(`Finding collaborators for { repo: ${this.repo.repo}, owner: ${this.repo.owner}, affiliation: 'direct', 'outside', and 'pending invites' }`) return Promise.all([this.github.repos.listCollaborators({ repo: this.repo.repo, owner: this.repo.owner, affiliation: 'direct' }), - this.github.repos.listCollaborators({ repo: this.repo.repo, owner: this.repo.owner, affiliation: 'outside' }), - this.github.repos.listInvitations({ repo: this.repo.repo, owner: this.repo.owner })]) + this.github.repos.listCollaborators({ repo: this.repo.repo, owner: this.repo.owner, affiliation: 'outside' }), + this.github.repos.listInvitations({ repo: this.repo.repo, owner: this.repo.owner })]) .then(res => { const mapCollaborator = user => { return { @@ -26,8 +26,8 @@ module.exports = class Collaborators extends Diffable { username: user.login.toLowerCase(), pendinginvite: false, permission: (user.permissions.admin && 'admin') || - (user.permissions.push && 'push') || - (user.permissions.pull && 'pull') + (user.permissions.push && 'push') || + (user.permissions.pull && 'pull') } } @@ -35,13 +35,13 @@ module.exports = class Collaborators extends Diffable { const results1 = (res[1].data || []).map(mapCollaborator) const results2 = (res[2].data || []).map(invite => { return { - // Force all usernames to lowercase to avoid comparison issues. + // Force all usernames to lowercase to avoid comparison issues. username: invite.invitee.login.toLowerCase(), pendinginvite: true, invitation_id: invite.id, permission: (invite.permissions === 'admin' && 'admin') || - (invite.permissions === 'read' && 'pull') || - (invite.permissions === 'write' && 'push') + (invite.permissions === 'read' && 'pull') || + (invite.permissions === 'write' && 'push') } }) return results0.concat(results1).concat(results2) @@ -52,15 +52,15 @@ module.exports = class Collaborators extends Diffable { }) } - comparator (existing, attrs) { + comparator(existing, attrs) { return existing.username === attrs.username } - changed (existing, attrs) { + changed(existing, attrs) { return existing.permission !== attrs.permission } - update (existing, attrs) { + update(existing, attrs) { if (existing.pendinginvite) { return this.updateInvite(existing.invitation_id, attrs.permission) } else { @@ -68,7 +68,7 @@ module.exports = class Collaborators extends Diffable { } } - add (attrs) { + add(attrs) { const data = Object.assign({}, attrs, this.repo) if (this.nop) { return Promise.resolve([ @@ -78,12 +78,12 @@ module.exports = class Collaborators extends Diffable { return this.github.repos.addCollaborator(data) } - updateInvite (invitation_id, permissions) { + updateInvite(invitation_id, permissions) { const data = Object.assign({ invitation_id, permissions: (permissions === 'admin' && 'admin') || - (permissions === 'pull' && 'read') || - (permissions === 'push' && 'write') + (permissions === 'pull' && 'read') || + (permissions === 'push' && 'write') }, this.repo) if (this.nop) { return Promise.resolve([ @@ -93,7 +93,7 @@ module.exports = class Collaborators extends Diffable { return this.github.repos.updateInvitation(data) } - remove (existing) { + remove(existing) { if (existing.pendinginvite) { const data = Object.assign({ invitation_id: existing.invitation_id }, this.repo) if (this.nop) { diff --git a/lib/plugins/custom_properties.js b/lib/plugins/custom_properties.js index cb0adf7d..77e9ee6f 100644 --- a/lib/plugins/custom_properties.js +++ b/lib/plugins/custom_properties.js @@ -1,7 +1,7 @@ const Diffable = require('./diffable') module.exports = class CustomProperties extends Diffable { - constructor (...args) { + constructor(...args) { super(...args) if (this.entries) { @@ -12,7 +12,7 @@ module.exports = class CustomProperties extends Diffable { } } - async find () { + async find() { const data = await this.github.request('GET /repos/:org/:repo/properties/values', { org: this.repo.owner, repo: this.repo.repo @@ -22,15 +22,15 @@ module.exports = class CustomProperties extends Diffable { return properties } - comparator (existing, attrs) { + comparator(existing, attrs) { return existing.name === attrs.name } - changed (existing, attrs) { + changed(existing, attrs) { return attrs.value !== existing.value } - async update (existing, attrs) { + async update(existing, attrs) { await this.github.request('PATCH /repos/:org/:repo/properties/values', { org: this.repo.owner, repo: this.repo.repo, @@ -41,7 +41,7 @@ module.exports = class CustomProperties extends Diffable { }) } - async add (attrs) { + async add(attrs) { await this.github.request('PATCH /repos/:org/:repo/properties/values', { org: this.repo.owner, repo: this.repo.repo, @@ -52,7 +52,7 @@ module.exports = class CustomProperties extends Diffable { }) } - async remove (existing) { + async remove(existing) { await this.github.request('PATCH /repos/:org/:repo/properties/values', { org: this.repo.owner, repo: this.repo.repo, diff --git a/lib/plugins/diffable.js b/lib/plugins/diffable.js index 8db6a0ef..21626ec6 100644 --- a/lib/plugins/diffable.js +++ b/lib/plugins/diffable.js @@ -24,7 +24,7 @@ const MergeDeep = require('../mergeDeep') const NopCommand = require('../nopcommand') const ignorableFields = ['id', 'node_id', 'default', 'url'] module.exports = class Diffable extends ErrorStash { - constructor (nop, github, repo, entries, log, errors) { + constructor(nop, github, repo, entries, log, errors) { super(errors) this.github = github this.repo = repo @@ -33,7 +33,7 @@ module.exports = class Diffable extends ErrorStash { this.nop = nop } - filterEntries () { + filterEntries() { let filteredEntries = Array.from(this.entries) // this.log.debug(` entries ${JSON.stringify(filteredEntries)}`) @@ -72,7 +72,7 @@ module.exports = class Diffable extends ErrorStash { return filteredEntries } - sync () { + sync() { const resArray = [] if (this.entries) { let filteredEntries = this.filterEntries() diff --git a/lib/plugins/environments.js b/lib/plugins/environments.js index 4ceaa9ff..383b55b6 100644 --- a/lib/plugins/environments.js +++ b/lib/plugins/environments.js @@ -9,12 +9,12 @@ module.exports = class Environments extends Diffable { if (this.entries) { // Force all names to lowercase to avoid comparison issues. this.entries.forEach(environment => { - environment.name = environment.name.toLowerCase(); - if(environment.variables) { - environment.variables.forEach(variable => { - variable.name = variable.name.toLowerCase(); - }); - } + environment.name = environment.name.toLowerCase(); + if (environment.variables) { + environment.variables.forEach(variable => { + variable.name = variable.name.toLowerCase(); + }); + } }) } } @@ -27,13 +27,13 @@ module.exports = class Environments extends Diffable { let environments_mapped = []; - for(let environment of environments) { + for (let environment of environments) { const mapped = { name: environment.name.toLowerCase(), repo: this.repo.repo, wait_timer: (environment.protection_rules.find(rule => rule.type === 'wait_timer') || { wait_timer: 0 }).wait_timer, prevent_self_review: (environment.protection_rules.find(rule => rule.type === 'required_reviewers') || { prevent_self_review: false }).prevent_self_review, - reviewers: (environment.protection_rules.find(rule => rule.type === 'required_reviewers') || { reviewers: [] }).reviewers.map(reviewer => ({id: reviewer.reviewer.id, type: reviewer.type})), + reviewers: (environment.protection_rules.find(rule => rule.type === 'required_reviewers') || { reviewers: [] }).reviewers.map(reviewer => ({ id: reviewer.reviewer.id, type: reviewer.type })), deployment_branch_policy: environment.deployment_branch_policy === null ? null : { protected_branches: (environment.deployment_branch_policy || { protected_branches: false }).protected_branches, custom_branch_policies: (environment.deployment_branch_policy || { custom_branch_policies: false }).custom_branch_policies && (await this.github.request('GET /repos/:org/:repo/environments/:environment_name/deployment-branch-policies', { @@ -48,7 +48,7 @@ module.exports = class Environments extends Diffable { org: this.repo.owner, repo: this.repo.repo, environment_name: environment.name - })).data.variables.map(variable => ({name: variable.name.toLowerCase(), value: variable.value})), + })).data.variables.map(variable => ({ name: variable.name.toLowerCase(), value: variable.value })), deployment_protection_rules: (await this.github.request('GET /repos/:org/:repo/environments/:environment_name/deployment_protection_rules', { org: this.repo.owner, repo: this.repo.repo, @@ -74,23 +74,23 @@ module.exports = class Environments extends Diffable { if (!attrs.prevent_self_review) attrs.prevent_self_review = false; if (!attrs.reviewers) attrs.reviewers = []; if (!attrs.deployment_branch_policy) attrs.deployment_branch_policy = null; - if(!attrs.variables) attrs.variables = []; - if(!attrs.deployment_protection_rules) attrs.deployment_protection_rules = []; + if (!attrs.variables) attrs.variables = []; + if (!attrs.deployment_protection_rules) attrs.deployment_protection_rules = []; const wait_timer = existing.wait_timer !== attrs.wait_timer; const prevent_self_review = existing.prevent_self_review !== attrs.prevent_self_review; const reviewers = JSON.stringify(existing.reviewers.sort((x1, x2) => x1.id - x2.id)) !== JSON.stringify(attrs.reviewers.sort((x1, x2) => x1.id - x2.id)); let existing_custom_branch_policies = existing.deployment_branch_policy === null ? null : existing.deployment_branch_policy.custom_branch_policies; - if(typeof(existing_custom_branch_policies) === 'object' && existing_custom_branch_policies !== null) { + if (typeof (existing_custom_branch_policies) === 'object' && existing_custom_branch_policies !== null) { existing_custom_branch_policies = existing_custom_branch_policies.sort(); } let attrs_custom_branch_policies = attrs.deployment_branch_policy === null ? null : attrs.deployment_branch_policy.custom_branch_policies; - if(typeof(attrs_custom_branch_policies) === 'object' && attrs_custom_branch_policies !== null) { + if (typeof (attrs_custom_branch_policies) === 'object' && attrs_custom_branch_policies !== null) { attrs_custom_branch_policies = attrs_custom_branch_policies.sort(); } let deployment_branch_policy; - if(existing.deployment_branch_policy === attrs.deployment_branch_policy) { + if (existing.deployment_branch_policy === attrs.deployment_branch_policy) { deployment_branch_policy = false; } else { @@ -98,26 +98,26 @@ module.exports = class Environments extends Diffable { (existing.deployment_branch_policy === null && attrs.deployment_branch_policy !== null) || (existing.deployment_branch_policy !== null && attrs.deployment_branch_policy === null) || (existing.deployment_branch_policy.protected_branches !== attrs.deployment_branch_policy.protected_branches) || - (JSON.stringify(existing_custom_branch_policies) !== JSON.stringify(attrs_custom_branch_policies)) + (JSON.stringify(existing_custom_branch_policies) !== JSON.stringify(attrs_custom_branch_policies)) ); } const variables = JSON.stringify(existing.variables.sort((x1, x2) => x1.name - x2.name)) !== JSON.stringify(attrs.variables.sort((x1, x2) => x1.name - x2.name)); - const deployment_protection_rules = JSON.stringify(existing.deployment_protection_rules.map(x => ({app_id: x.app_id})).sort((x1, x2) => x1.app_id - x2.app_id)) !== JSON.stringify(attrs.deployment_protection_rules.map(x => ({app_id: x.app_id})).sort((x1, x2) => x1.app_id - x2.app_id)); + const deployment_protection_rules = JSON.stringify(existing.deployment_protection_rules.map(x => ({ app_id: x.app_id })).sort((x1, x2) => x1.app_id - x2.app_id)) !== JSON.stringify(attrs.deployment_protection_rules.map(x => ({ app_id: x.app_id })).sort((x1, x2) => x1.app_id - x2.app_id)); - return {wait_timer, prevent_self_review, reviewers, deployment_branch_policy, variables, deployment_protection_rules}; + return { wait_timer, prevent_self_review, reviewers, deployment_branch_policy, variables, deployment_protection_rules }; } changed(existing, attrs) { - const {wait_timer, prevent_self_review, reviewers, deployment_branch_policy, variables, deployment_protection_rules} = this.getChanged(existing, attrs); + const { wait_timer, prevent_self_review, reviewers, deployment_branch_policy, variables, deployment_protection_rules } = this.getChanged(existing, attrs); return wait_timer || prevent_self_review || reviewers || deployment_branch_policy || variables || deployment_protection_rules; } async update(existing, attrs) { - const {wait_timer, prevent_self_review, reviewers, deployment_branch_policy, variables, deployment_protection_rules} = this.getChanged(existing, attrs); + const { wait_timer, prevent_self_review, reviewers, deployment_branch_policy, variables, deployment_protection_rules } = this.getChanged(existing, attrs); - if(wait_timer || prevent_self_review || reviewers || deployment_branch_policy) { + if (wait_timer || prevent_self_review || reviewers || deployment_branch_policy) { await this.github.request(`PUT /repos/:org/:repo/environments/:environment_name`, { org: this.repo.owner, repo: this.repo.repo, @@ -132,14 +132,14 @@ module.exports = class Environments extends Diffable { }) } - if(deployment_branch_policy && attrs.deployment_branch_policy && attrs.deployment_branch_policy.custom_branch_policies) { + if (deployment_branch_policy && attrs.deployment_branch_policy && attrs.deployment_branch_policy.custom_branch_policies) { const existingPolicies = (await this.github.request('GET /repos/:org/:repo/environments/:environment_name/deployment-branch-policies', { org: this.repo.owner, repo: this.repo.repo, environment_name: attrs.name })).data.branch_policies; - for(let policy of existingPolicies) { + for (let policy of existingPolicies) { await this.github.request('DELETE /repos/:org/:repo/environments/:environment_name/deployment-branch-policies/:branch_policy_id', { org: this.repo.owner, repo: this.repo.repo, @@ -148,7 +148,7 @@ module.exports = class Environments extends Diffable { }); } - for(let policy of attrs.deployment_branch_policy.custom_branch_policies) { + for (let policy of attrs.deployment_branch_policy.custom_branch_policies) { await this.github.request('POST /repos/:org/:repo/environments/:environment_name/deployment-branch-policies', { org: this.repo.owner, repo: this.repo.repo, @@ -158,14 +158,14 @@ module.exports = class Environments extends Diffable { } } - if(variables) { + if (variables) { let existingVariables = [...existing.variables]; - for(let variable of attrs.variables) { + for (let variable of attrs.variables) { const existingVariable = existingVariables.find((_var) => _var.name === variable.name); - if(existingVariable) { + if (existingVariable) { existingVariables = existingVariables.filter(_var => _var.name !== variable.name); - if(existingVariable.value !== variable.value) { + if (existingVariable.value !== variable.value) { await this.github.request(`PATCH /repos/:org/:repo/environments/:environment_name/variables/:variable_name`, { org: this.repo.owner, repo: this.repo.repo, @@ -186,7 +186,7 @@ module.exports = class Environments extends Diffable { } } - for(let variable of existingVariables) { + for (let variable of existingVariables) { await this.github.request('DELETE /repos/:org/:repo/environments/:environment_name/variables/:variable_name', { org: this.repo.owner, repo: this.repo.repo, @@ -196,13 +196,13 @@ module.exports = class Environments extends Diffable { } } - if(deployment_protection_rules) { + if (deployment_protection_rules) { let existingRules = [...existing.deployment_protection_rules]; - for(let rule of attrs.deployment_protection_rules) { + for (let rule of attrs.deployment_protection_rules) { const existingRule = existingRules.find((_rule) => _rule.id === rule.id); - if(!existingRule) { + if (!existingRule) { await this.github.request(`POST /repos/:org/:repo/environments/:environment_name/deployment_protection_rules`, { org: this.repo.owner, repo: this.repo.repo, @@ -212,7 +212,7 @@ module.exports = class Environments extends Diffable { } } - for(let rule of existingRules) { + for (let rule of existingRules) { await this.github.request('DELETE /repos/:org/:repo/environments/:environment_name/deployment_protection_rules/:rule_id', { org: this.repo.owner, repo: this.repo.repo, @@ -237,9 +237,9 @@ module.exports = class Environments extends Diffable { } }); - if(attrs.deployment_branch_policy && attrs.deployment_branch_policy.custom_branch_policies) { + if (attrs.deployment_branch_policy && attrs.deployment_branch_policy.custom_branch_policies) { - for(let policy of attrs.deployment_branch_policy.custom_branch_policies) { + for (let policy of attrs.deployment_branch_policy.custom_branch_policies) { await this.github.request('POST /repos/:org/:repo/environments/:environment_name/deployment-branch-policies', { org: this.repo.owner, repo: this.repo.repo, @@ -250,9 +250,9 @@ module.exports = class Environments extends Diffable { } - if(attrs.variables) { + if (attrs.variables) { - for(let variable of attrs.variables) { + for (let variable of attrs.variables) { await this.github.request(`POST /repos/:org/:repo/environments/:environment_name/variables`, { org: this.repo.owner, repo: this.repo.repo, @@ -262,11 +262,11 @@ module.exports = class Environments extends Diffable { }); } - } + } - if(attrs.deployment_protection_rules) { + if (attrs.deployment_protection_rules) { - for(let rule of attrs.deployment_protection_rules) { + for (let rule of attrs.deployment_protection_rules) { await this.github.request(`POST /repos/:org/:repo/environments/:environment_name/deployment_protection_rules`, { org: this.repo.owner, repo: this.repo.repo, @@ -286,78 +286,78 @@ module.exports = class Environments extends Diffable { }); } - sync () { - const resArray = [] - if (this.entries) { - let 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) { - for (const key of Object.keys(entry)) { - if (entry[key] === null || entry[key] === undefined) { - delete entry[key] - } - } - } - // For environments, we want to keep the entries with only name defined. - - const changes = [] - - existingRecords.forEach(x => { - if (!filteredEntries.find(y => this.comparator(x, y))) { - const change = this.remove(x).then(res => { - if (this.nop) { - return resArray.push(res) + sync() { + const resArray = [] + if (this.entries) { + let 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) { + for (const key of Object.keys(entry)) { + if (entry[key] === null || entry[key] === undefined) { + delete entry[key] + } + } } - return res - }) - changes.push(change) - } - }) - - filteredEntries.forEach(attrs => { - const existing = existingRecords.find(record => { - return this.comparator(record, attrs) - }) + // For environments, we want to keep the entries with only name defined. + + const changes = [] + + existingRecords.forEach(x => { + if (!filteredEntries.find(y => this.comparator(x, y))) { + const change = this.remove(x).then(res => { + if (this.nop) { + return resArray.push(res) + } + return res + }) + changes.push(change) + } + }) + + filteredEntries.forEach(attrs => { + const existing = existingRecords.find(record => { + return this.comparator(record, attrs) + }) + + if (!existing) { + const change = this.add(attrs).then(res => { + if (this.nop) { + return resArray.push(res) + } + return res + }) + changes.push(change) + } else if (this.changed(existing, attrs)) { + const change = this.update(existing, attrs).then(res => { + if (this.nop) { + return resArray.push(res) + } + return res + }) + changes.push(change) + } + }) - if (!existing) { - const change = this.add(attrs).then(res => { if (this.nop) { - return resArray.push(res) + return Promise.resolve(resArray) } - return res - }) - changes.push(change) - } else if (this.changed(existing, attrs)) { - const change = this.update(existing, attrs).then(res => { + return Promise.all(changes) + }).catch(e => { if (this.nop) { - return resArray.push(res) + if (e.status === 404) { + // Ignore 404s which can happen in dry-run as the repo may not exist. + return Promise.resolve(resArray) + } else { + resArray.push(new NopCommand(this.constructor.name, this.repo, null, `error ${e} in ${this.constructor.name} for repo: ${JSON.stringify(this.repo)} entries ${JSON.stringify(this.entries)}`, 'ERROR')) + return Promise.resolve(resArray) + } + } else { + this.logError(`Error ${e} in ${this.constructor.name} for repo: ${JSON.stringify(this.repo)} entries ${JSON.stringify(this.entries)}`) } - return res - }) - changes.push(change) - } - }) - - if (this.nop) { - return Promise.resolve(resArray) - } - return Promise.all(changes) - }).catch(e => { - if (this.nop) { - if (e.status === 404) { - // Ignore 404s which can happen in dry-run as the repo may not exist. - return Promise.resolve(resArray) - } else { - resArray.push(new NopCommand(this.constructor.name, this.repo, null, `error ${e} in ${this.constructor.name} for repo: ${JSON.stringify(this.repo)} entries ${JSON.stringify(this.entries)}`, 'ERROR')) - return Promise.resolve(resArray) - } - } else { - this.logError(`Error ${e} in ${this.constructor.name} for repo: ${JSON.stringify(this.repo)} entries ${JSON.stringify(this.entries)}`) - } - }) - } + }) + } } } diff --git a/lib/plugins/errorStash.js b/lib/plugins/errorStash.js index 4b625559..751b9cbc 100644 --- a/lib/plugins/errorStash.js +++ b/lib/plugins/errorStash.js @@ -1,10 +1,10 @@ // Base class to make it easy to log errors as issue in the `admin` repo module.exports = class ErrorStash { - constructor (errors) { + constructor(errors) { this.errors = errors } - logError (msg) { + logError(msg) { this.log.error(msg) this.errors.push({ owner: this.repo.owner, diff --git a/lib/plugins/labels.js b/lib/plugins/labels.js index 49558cc0..d93739fc 100644 --- a/lib/plugins/labels.js +++ b/lib/plugins/labels.js @@ -3,7 +3,7 @@ const NopCommand = require('../nopcommand') const previewHeaders = { accept: 'application/vnd.github.symmetra-preview+json' } module.exports = class Labels extends Diffable { - constructor (nop, github, repo, entries, log, errors) { + constructor(nop, github, repo, entries, log, errors) { const { include, exclude = [] } = entries if (Array.isArray(include)) { // Config is object with include array @@ -32,7 +32,7 @@ module.exports = class Labels extends Diffable { } } - find () { + find() { this.log.debug(`Finding labels for ${JSON.stringify(this.wrapAttrs({ per_page: 100 }))}`) const options = this.github.issues.listLabelsForRepo.endpoint.merge(this.wrapAttrs({ per_page: 100 })) return this.github.repos.get(this.repo).then(() => { @@ -46,15 +46,15 @@ module.exports = class Labels extends Diffable { }) } - comparator (existing, attrs) { + comparator(existing, attrs) { return existing.name === attrs.name || existing.name === attrs.oldname || existing.name === attrs.current_name } - changed (existing, attrs) { + changed(existing, attrs) { return attrs.oldname === existing.name || existing.color !== attrs.color || existing.description !== attrs.description } - update (existing, attrs) { + update(existing, attrs) { // Our settings file uses oldname for renaming labels, // however octokit/rest 16.30.1 uses the current_name attribute. // Future versions of octokit/rest will need name and new_name attrs. @@ -69,7 +69,7 @@ module.exports = class Labels extends Diffable { return this.github.issues.updateLabel(this.wrapAttrs(attrs)) } - add (attrs) { + add(attrs) { if (this.nop) { return Promise.resolve([ new NopCommand(this.constructor.name, this.repo, this.github.issues.createLabel.endpoint(this.wrapAttrs(attrs)), 'Create label') @@ -79,7 +79,7 @@ module.exports = class Labels extends Diffable { return this.github.issues.createLabel(this.wrapAttrs(attrs)).catch(e => this.logError(` ${JSON.stringify(e)}`)) } - remove (existing) { + remove(existing) { if (this.isExcluded(existing)) { return Promise.resolve([]) } @@ -91,11 +91,11 @@ module.exports = class Labels extends Diffable { return this.github.issues.deleteLabel(this.wrapAttrs({ name: existing.name })) } - wrapAttrs (attrs) { + wrapAttrs(attrs) { return Object.assign({}, attrs, this.repo, { headers: previewHeaders }) } - isExcluded (label) { + isExcluded(label) { return this.exclude.some(rx => rx.test(label.name)) } } diff --git a/lib/plugins/milestones.js b/lib/plugins/milestones.js index 9fc93ab2..7455479b 100644 --- a/lib/plugins/milestones.js +++ b/lib/plugins/milestones.js @@ -1,7 +1,7 @@ const Diffable = require('./diffable') module.exports = class Milestones extends Diffable { - constructor (...args) { + constructor(...args) { super(...args) if (this.entries) { @@ -13,32 +13,32 @@ module.exports = class Milestones extends Diffable { } } - find () { + find() { const options = this.github.issues.listMilestones.endpoint.merge(Object.assign({ per_page: 100, state: 'all' }, this.repo)) return this.github.paginate(options) } - comparator (existing, attrs) { + comparator(existing, attrs) { return existing.title === attrs.title } - changed (existing, attrs) { + changed(existing, attrs) { return existing.description !== attrs.description || existing.state !== attrs.state } - update (existing, attrs) { + update(existing, attrs) { const { owner, repo } = this.repo return this.github.issues.updateMilestone(Object.assign({ milestone_number: existing.number }, attrs, { owner, repo })) } - add (attrs) { + add(attrs) { const { owner, repo } = this.repo return this.github.issues.createMilestone(Object.assign({}, attrs, { owner, repo })) } - remove (existing) { + remove(existing) { const { owner, repo } = this.repo return this.github.issues.deleteMilestone(Object.assign({ milestone_number: existing.number }, { owner, repo })) diff --git a/lib/plugins/repository.js b/lib/plugins/repository.js index 42bbd28e..0a7716b6 100644 --- a/lib/plugins/repository.js +++ b/lib/plugins/repository.js @@ -40,7 +40,7 @@ const ignorableFields = [ ] module.exports = class Repository extends ErrorStash { - constructor (nop, github, repo, settings, installationId, log, errors) { + constructor(nop, github, repo, settings, installationId, log, errors) { super(errors) this.installationId = installationId this.github = github @@ -57,7 +57,7 @@ module.exports = class Repository extends ErrorStash { delete this.settings.template } - sync () { + sync() { const resArray = [] this.log.debug(`Syncing Repo ${this.settings.name}`) this.settings.name = this.settings.name || this.settings.repo @@ -91,7 +91,7 @@ module.exports = class Repository extends ErrorStash { const promises = [] if (topicChanges.hasChanges) { promises.push(this.updatetopics(resp.data, resArray)) - } + } if (changes.hasChanges) { this.log.debug('There are repo changes') let updateDefaultBranchPromise = Promise.resolve() @@ -155,7 +155,7 @@ module.exports = class Repository extends ErrorStash { }) } - updateDefaultBranch (oldname, newname, resArray) { + updateDefaultBranch(oldname, newname, resArray) { this.log.debug(`Checking if ${newname} is already a branch`) return this.github.repos.getBranch({ owner: this.settings.owner, @@ -205,7 +205,7 @@ module.exports = class Repository extends ErrorStash { } } - updaterepo (resArray) { + updaterepo(resArray) { this.log.debug(`Updating repo with settings ${JSON.stringify(this.topics)} ${JSON.stringify(this.settings)}`) if (this.nop) { resArray.push(new NopCommand(this.constructor.name, this.repo, this.github.repos.update.endpoint(this.settings), 'Update Repo')) @@ -214,7 +214,7 @@ module.exports = class Repository extends ErrorStash { return this.github.repos.update(this.settings) } - updatetopics (repoData, resArray) { + updatetopics(repoData, resArray) { const parms = { owner: this.settings.owner, repo: this.settings.repo, @@ -227,12 +227,12 @@ module.exports = class Repository extends ErrorStash { if (this.topics) { // if (repoData.data?.topics.length !== this.topics.length || // !repoData.data?.topics.every(t => this.topics.includes(t))) { - this.log.debug(`Updating repo with topics ${this.topics.join(',')}`) - if (this.nop) { - resArray.push((new NopCommand(this.constructor.name, this.repo, this.github.repos.replaceAllTopics.endpoint(parms), 'Update Topics'))) - return Promise.resolve(resArray) - } - return this.github.repos.replaceAllTopics(parms) + this.log.debug(`Updating repo with topics ${this.topics.join(',')}`) + if (this.nop) { + resArray.push((new NopCommand(this.constructor.name, this.repo, this.github.repos.replaceAllTopics.endpoint(parms), 'Update Topics'))) + return Promise.resolve(resArray) + } + return this.github.repos.replaceAllTopics(parms) // } else { // this.log.debug(`no need to update topics for ${repoData.data.name}`) // if (this.nop) { @@ -244,7 +244,7 @@ module.exports = class Repository extends ErrorStash { } // Added support for Code Security and Analysis - updateSecurity (repoData, resArray) { + updateSecurity(repoData, resArray) { if (this.security?.enableVulnerabilityAlerts === true || this.security?.enableVulnerabilityAlerts === false) { this.log.debug(`Found repo with security settings ${JSON.stringify(this.security)}`) if (this.security.enableVulnerabilityAlerts === true) { @@ -283,7 +283,7 @@ module.exports = class Repository extends ErrorStash { } } - updateAutomatedSecurityFixes (repoData, resArray) { + updateAutomatedSecurityFixes(repoData, resArray) { if (this.security?.enableAutomatedSecurityFixes === true || this.security?.enableAutomatedSecurityFixes === false) { if (this.security.enableAutomatedSecurityFixes === true) { this.log.debug(`Enabling Dependabot security updates for owner: ${repoData.owner.login} and repo ${repoData.name}`) diff --git a/lib/plugins/rulesets.js b/lib/plugins/rulesets.js index 6846e1ce..f263d7d5 100644 --- a/lib/plugins/rulesets.js +++ b/lib/plugins/rulesets.js @@ -7,7 +7,7 @@ const version = { 'X-GitHub-Api-Version': '2022-11-28' } module.exports = class Rulesets extends Diffable { - constructor (nop, github, repo, entries, log, errors, scope) { + constructor(nop, github, repo, entries, log, errors, scope) { super(nop, github, repo, entries, log, errors) this.github = github this.repo = repo @@ -18,7 +18,7 @@ module.exports = class Rulesets extends Diffable { } // Find all Rulesets for this org - find () { + find() { if (this.scope === 'org') { this.log.debug(`Getting all rulesets for the org ${this.org}`) @@ -74,21 +74,21 @@ module.exports = class Rulesets extends Diffable { } } - isEmpty (maybeEmpty) { + isEmpty(maybeEmpty) { return (maybeEmpty === null) || Object.keys(maybeEmpty).length === 0 } - comparator (existing, attrs) { + comparator(existing, attrs) { return existing.name === attrs.name } - changed (existing, attrs) { + changed(existing, attrs) { const mergeDeep = new MergeDeep(this.log, this.github, ignorableFields) const merged = mergeDeep.compareDeep(existing, attrs) return merged.hasChanges } - update (existing, attrs) { + update(existing, attrs) { const parms = this.wrapAttrs(Object.assign({ id: existing.id }, attrs)) if (this.scope === 'org') { if (this.nop) { @@ -119,7 +119,7 @@ module.exports = class Rulesets extends Diffable { } } - add (attrs) { + add(attrs) { if (this.scope === 'org') { if (this.nop) { return Promise.resolve([ @@ -149,7 +149,7 @@ module.exports = class Rulesets extends Diffable { } } - remove (existing) { + remove(existing) { const parms = this.wrapAttrs(Object.assign({ id: existing.id })) if (this.scope === 'org') { if (this.nop) { @@ -183,7 +183,7 @@ module.exports = class Rulesets extends Diffable { } } - wrapAttrs (attrs) { + wrapAttrs(attrs) { if (this.scope === 'org') { return Object.assign({}, attrs, { org: this.repo.owner, @@ -198,7 +198,7 @@ module.exports = class Rulesets extends Diffable { } } - handleError (e, returnValue) { + handleError(e, returnValue) { this.logError(e) if (this.nop) { return Promise.resolve([(new NopCommand(this.constructor.name, this.repo, null, `error: ${e}`, 'ERROR'))]) diff --git a/lib/plugins/teams.js b/lib/plugins/teams.js index eaabc468..775d9048 100644 --- a/lib/plugins/teams.js +++ b/lib/plugins/teams.js @@ -3,20 +3,20 @@ const NopCommand = require('../nopcommand') const teamRepoEndpoint = '/orgs/:owner/teams/:team_slug/repos/:owner/:repo' module.exports = class Teams extends Diffable { - async find () { + async find() { this.log.debug(`Finding teams for ${this.repo.owner}/${this.repo.repo}`) return this.github.paginate(this.github.repos.listTeams, this.repo) } - comparator (existing, attrs) { + comparator(existing, attrs) { return existing.slug === attrs.name.toLowerCase() } - changed (existing, attrs) { + changed(existing, attrs) { return existing.permission !== attrs.permission } - update (existing, attrs) { + update(existing, attrs) { if (this.nop) { return Promise.resolve([ new NopCommand(this.constructor.name, this.repo, this.github.request.endpoint(`PUT ${teamRepoEndpoint}`, this.toParams(existing, attrs)), 'Add Teams to Repo') @@ -25,7 +25,7 @@ module.exports = class Teams extends Diffable { return this.github.request(`PUT ${teamRepoEndpoint}`, this.toParams(existing, attrs)) } - add (attrs) { + add(attrs) { let existing = { team_id: 1 } this.log.debug(`Getting team with the parms ${JSON.stringify(attrs)}`) return this.github.teams.getByName({ org: this.repo.owner, team_slug: attrs.name }).then(res => { @@ -68,7 +68,7 @@ module.exports = class Teams extends Diffable { }) } - remove (existing) { + remove(existing) { if (this.nop) { return Promise.resolve([ new NopCommand(this.constructor.name, this.repo, this.github.request.endpoint( @@ -83,7 +83,7 @@ module.exports = class Teams extends Diffable { ) } - toParams (existing, attrs) { + toParams(existing, attrs) { return { team_id: existing.id, org: this.repo.owner, diff --git a/lib/plugins/validator.js b/lib/plugins/validator.js index 45f04d60..e65f3461 100644 --- a/lib/plugins/validator.js +++ b/lib/plugins/validator.js @@ -1,6 +1,6 @@ const NopCommand = require('../nopcommand') module.exports = class Validator { - constructor (nop, github, repo, settings, log) { + constructor(nop, github, repo, settings, log) { this.github = github this.pattern = settings.pattern // this.regex = /[a-zA-Z0-9_-]+_\w[a-zA-Z0-9_-]+.*/gm @@ -10,7 +10,7 @@ module.exports = class Validator { this.nop = nop } - sync () { + sync() { try { return this.github.repos.getAllTopics({ owner: this.repo.owner, @@ -57,7 +57,7 @@ module.exports = class Validator { } } }) - .catch(() => {}) + .catch(() => { }) } catch (error) { this.log(`Error in Validation checking ${error}`) } diff --git a/lib/settings.js b/lib/settings.js index 9683cb82..0e62b9df 100644 --- a/lib/settings.js +++ b/lib/settings.js @@ -10,7 +10,7 @@ const CONFIG_PATH = env.CONFIG_PATH const eta = new Eta({ views: path.join(__dirname) }) const SCOPE = { ORG: 'org', REPO: 'repo' } // Determine if the setting is a org setting or repo setting class Settings { - static async syncAll (nop, context, repo, config, ref) { + static async syncAll(nop, context, repo, config, ref) { const settings = new Settings(nop, context, repo, config, ref) try { await settings.loadConfigs() @@ -164,10 +164,10 @@ class Settings { //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 @@ -755,7 +755,7 @@ ${this.results.reduce((x, y) => { } )) { delete subOrgConfigs[key] - } + } } } return subOrgConfigs @@ -826,7 +826,7 @@ ${this.results.reduce((x, y) => { if (this.nop) { //Remove nulls and undefined from the results const results = res.flat(3).filter(r => r) - + this.results = this.results.concat(results) } } diff --git a/test/integration/common.js b/test/integration/common.js index 13d47617..60d5f622 100644 --- a/test/integration/common.js +++ b/test/integration/common.js @@ -15,24 +15,24 @@ const repository = { } } -function loadInstance () { +function loadInstance() { const probot = createProbot({ id: 1, cert: 'test', githubToken: 'test' }) probot.load(settingsBot) return probot } -function initializeNock () { +function initializeNock() { return nock('https://api.github.com') } -function teardownNock (githubScope) { +function teardownNock(githubScope) { expect(githubScope.isDone()).toBe(true) nock.cleanAll() } -function buildPushEvent () { +function buildPushEvent() { return { name: 'push', payload: { @@ -43,7 +43,7 @@ function buildPushEvent () { } } -function buildRepositoryEditedEvent () { +function buildRepositoryEditedEvent() { return { name: 'repository.edited', payload: { @@ -53,14 +53,14 @@ function buildRepositoryEditedEvent () { } } -function buildRepositoryCreatedEvent () { +function buildRepositoryCreatedEvent() { return { name: 'repository.created', payload: { repository } } } -function buildTriggerEvent () { +function buildTriggerEvent() { return any.fromList([buildPushEvent(), buildRepositoryCreatedEvent(), buildRepositoryEditedEvent()]) } diff --git a/test/unit/index.test.js b/test/unit/index.test.js index 9d09804d..84358b87 100644 --- a/test/unit/index.test.js +++ b/test/unit/index.test.js @@ -6,11 +6,11 @@ describe.skip('plugin', () => { beforeEach(() => { class Octokit { - static defaults () { + static defaults() { return Octokit } - constructor () { + constructor() { this.config = { get: jest.fn().mockReturnValue({}) } @@ -19,7 +19,7 @@ describe.skip('plugin', () => { } } - auth () { + auth() { return this } } diff --git a/test/unit/lib/glob.test.ts b/test/unit/lib/glob.test.ts index 27b6d29b..b565c2c6 100644 --- a/test/unit/lib/glob.test.ts +++ b/test/unit/lib/glob.test.ts @@ -74,5 +74,4 @@ describe('glob test', function () { str = 'java/csrf-protection-disabled' expect(str.search(pattern)>=0).toBeTruthy() }) - }) diff --git a/test/unit/lib/mergeArrayBy.test.js b/test/unit/lib/mergeArrayBy.test.js index 32292e68..798ededd 100644 --- a/test/unit/lib/mergeArrayBy.test.js +++ b/test/unit/lib/mergeArrayBy.test.js @@ -59,18 +59,18 @@ describe('mergeArrayByName', () => { const expected = [{ name: 'master', protection: - { - required_pull_request_reviews: - { - required_approving_review_count: 2, - dismiss_stale_reviews: false, - require_code_owner_reviews: true, - dismissal_restrictions: {} - }, - required_status_checks: { strict: true, contexts: [] }, - enforce_admins: false, - restrictions: null - } + { + required_pull_request_reviews: + { + required_approving_review_count: 2, + dismiss_stale_reviews: false, + require_code_owner_reviews: true, + dismissal_restrictions: {} + }, + required_status_checks: { strict: true, contexts: [] }, + enforce_admins: false, + restrictions: null + } }] const merged = branchArrayMerge('', null, null, ['name'], target.branches, source.branches) diff --git a/test/unit/lib/mergeDeep.test.js b/test/unit/lib/mergeDeep.test.js index c114377e..54d1873a 100644 --- a/test/unit/lib/mergeDeep.test.js +++ b/test/unit/lib/mergeDeep.test.js @@ -9,12 +9,12 @@ describe('MergeDeep Test', () => { repository: name: test # A short description of the repository that will show up on GitHub - description: description of the repos - + description: description of the repos + # A comma-separated list of topics to set on the repository - topics: - - uber - - newone + topics: + - uber + - newone branches: # If the name of the branch is default, it will create a branch protection for the default branch in the repo - name: default @@ -49,40 +49,40 @@ branches: `) const source = YAML.load(` - repository: - name: test + repository: + name: test org: decyjphr-org - force_create: false + force_create: false description: description of test repository homepage: https://newhome.github.io/ - topics: - - red - auto_init: true - has_issues: true + topics: + - red + auto_init: true + has_issues: true has_projects: true has_wiki: false has_downloads: true allow_squash_merge: true allow_merge_commit: false allow_rebase_merge: false - default_branch: develop - - labels: + default_branch: develop + + labels: # Labels: define labels for Issues and Pull Requests - name: green color: '#B60205' - description: An issue sswithss the system - + description: An issue sswithss the system + validator: - #pattern: '[a-zA-Z0-9_-]+_[a-zA-Z0-9_-]+.*' - pattern: '[a-zA-Z0-9_-]+' - + #pattern: '[a-zA-Z0-9_-]+_[a-zA-Z0-9_-]+.*' + pattern: '[a-zA-Z0-9_-]+' + collaborators: - username: regpaco permission: pull - - branches: - - name: feature1 + + branches: + - name: feature1 # https://developer.github.com/v3/repos/branches/#update-branch-protection # Branch Protection settings. Set to null to disable protection: @@ -109,8 +109,8 @@ branches: # Required. Restrict who can push to this branch. Team and user restrictions are only available for organization-owned repositories. Set to null to disable. restrictions: apps: [] - users: [] - teams: [] + users: [] + teams: [] `) const expected = { @@ -183,7 +183,7 @@ branches: const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -224,28 +224,28 @@ branches: const expected = { additions: - { - protection: { - required_pull_request_reviews: { - required_approving_review_count: 2, - dismiss_stale_reviews: false, - require_code_owner_reviews: true, - dismissal_restrictions: {} - }, - required_status_checks: { - strict: true, - contexts: [] - }, - enforce_admins: false - } - }, + { + protection: { + required_pull_request_reviews: { + required_approving_review_count: 2, + dismiss_stale_reviews: false, + require_code_owner_reviews: true, + dismissal_restrictions: {} + }, + required_status_checks: { + strict: true, + contexts: [] + }, + enforce_admins: false + } + }, modifications: {}, hasChanges: true } const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -274,27 +274,27 @@ branches: const expected = { additions: - { - protection: { - required_pull_request_reviews: { - required_approving_review_count: 2, - dismiss_stale_reviews: false, - require_code_owner_reviews: true, - dismissal_restrictions: {} - }, - required_status_checks: { - strict: true, - contexts: [] - }, - enforce_admins: false - } - }, + { + protection: { + required_pull_request_reviews: { + required_approving_review_count: 2, + dismiss_stale_reviews: false, + require_code_owner_reviews: true, + dismissal_restrictions: {} + }, + required_status_checks: { + strict: true, + contexts: [] + }, + enforce_admins: false + } + }, modifications: {}, hasChanges: true } const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -416,7 +416,7 @@ branches: const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -447,7 +447,7 @@ branches: const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -472,17 +472,17 @@ branches: repository: name: new home: new home - labels: + labels: # Labels: define labels for Issues and Pull Requests - name: green color: '#B60205' - description: An issue sswithss the system - + description: An issue sswithss the system + `) const target = YAML.load(` repository: name: new - home: old home + home: old home `) const expected = { additions: { @@ -500,7 +500,7 @@ branches: const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -533,7 +533,7 @@ branches: const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -566,7 +566,7 @@ branches: const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -612,7 +612,7 @@ branches: required_status_checks: strict: true contexts: - - "Lint, compile and build" + - "Lint, compile and build" `) const expected = { @@ -642,7 +642,7 @@ branches: const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -666,24 +666,24 @@ branches: const source = YAML.load(` x: - name: default - values: + values: a: [a,b,c] - name: new - values: + values: a: [b] `) const target = YAML.load(` x: - name: default - values: - a: [c,a] + values: + a: [c,a] `) const expected = JSON.parse('{"additions":{"x":[{"name":"new","values":{"a":["b"]}}]},"modifications":{"x":[{"values":{"a":["b"]},"name":"default"}]},"hasChanges":true}') const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -705,34 +705,34 @@ branches: it('Repo test', () => { const source = YAML.load(` - repository: - name: test + repository: + name: test org: decyjphr-org - force_create: false + force_create: false description: description of test repository homepage: https://newhome.github.io/ - topics: - - red - auto_init: true - has_issues: true + topics: + - red + auto_init: true + has_issues: true has_projects: true has_wiki: false has_downloads: true allow_squash_merge: true allow_merge_commit: false allow_rebase_merge: false - default_branch: develop + default_branch: develop `) const target = YAML.load(` repository: # A short description of the repository that will show up on GitHub - description: description of the repos - + description: description of the repos + # A comma-separated list of topics to set on the repository - topics: - - uber - - newone + topics: + - uber + - newone `) const expected = { @@ -763,7 +763,7 @@ branches: const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -813,7 +813,7 @@ entries: } const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -861,7 +861,7 @@ entries: } const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -876,7 +876,7 @@ entries: it('CompareDeep does not mutate source object', () => { const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -905,7 +905,7 @@ entries: it('CompareDeep produces correct result for arrays of named objects', () => { const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -933,7 +933,7 @@ entries: it('CompareDeep result has changes when source is empty and target is not', () => { const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -967,7 +967,7 @@ entries: it('CompareDeep result has no change when source and target match', () => { const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -1001,7 +1001,7 @@ entries: it('CompareDeep finds modifications on top-level arrays with different ordering', () => { const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -1024,7 +1024,7 @@ entries: it('CompareDeep does not report changes for matching empty targets', () => { const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -1070,7 +1070,7 @@ entries: const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -1300,7 +1300,7 @@ entries: ] const ignorableFields = ['id', 'node_id', 'default', 'url'] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -1353,7 +1353,7 @@ entries: const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -1403,7 +1403,7 @@ entries: - name: ROUTE53_HOSTNAME_DEVL value: 'https://foo-devl.com' - name: SECOND_VARIABLE_DEVL - value: 'My_SECOND_VARIABLE_DEVL' + value: 'My_SECOND_VARIABLE_DEVL' `) const expected = { @@ -1443,7 +1443,7 @@ entries: const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, @@ -1599,7 +1599,7 @@ branches: const ignorableFields = [] const mockReturnGitHubContext = jest.fn().mockReturnValue({ - request: () => {} + request: () => { } }) const mergeDeep = new MergeDeep( log, diff --git a/test/unit/lib/plugins/autolinks.test.js b/test/unit/lib/plugins/autolinks.test.js index 63d82927..351c6be1 100644 --- a/test/unit/lib/plugins/autolinks.test.js +++ b/test/unit/lib/plugins/autolinks.test.js @@ -4,7 +4,7 @@ describe('Autolinks', () => { const repo = { owner: 'owner', repo: 'repo' } let github - function configure (config) { + function configure(config) { const log = { debug: jest.fn(), error: console.error } const nop = false const errors = [] @@ -54,89 +54,89 @@ describe('Autolinks', () => { key_prefix: 'ADD-', url_template: 'https://test/', is_alphanumeric: true, - ...repo + ...repo }) expect(github.repos.deleteAutolink).toHaveBeenCalledWith({ autolink_id: '2', - ...repo + ...repo }) expect(github.repos.deleteAutolink).toHaveBeenCalledWith({ autolink_id: '3', - ...repo + ...repo }) expect(github.repos.createAutolink).toHaveBeenCalledWith({ key_prefix: 'NEW_URL-', url_template: 'https://new-url/', is_alphanumeric: true, - ...repo + ...repo }) expect(github.repos.deleteAutolink).not.toHaveBeenCalledWith({ autolink_id: '4', - ...repo + ...repo }) expect(github.repos.createAutolink).not.toHaveBeenCalledWith({ key_prefix: 'SAME_ALPHA-UNDEFINED-', url_template: 'https://test/', is_alphanumeric: true, - ...repo + ...repo }) expect(github.repos.deleteAutolink).not.toHaveBeenCalledWith({ autolink_id: '5', - ...repo + ...repo }) expect(github.repos.createAutolink).not.toHaveBeenCalledWith({ key_prefix: 'SAME_ALPHA-FALSE-', url_template: 'https://test/', is_alphanumeric: false, - ...repo + ...repo }) expect(github.repos.deleteAutolink).not.toHaveBeenCalledWith({ autolink_id: '6', - ...repo + ...repo }) expect(github.repos.createAutolink).not.toHaveBeenCalledWith({ key_prefix: 'SAME_ALPHA-TRUE-', url_template: 'https://test/', is_alphanumeric: true, - ...repo + ...repo }) expect(github.repos.deleteAutolink).toHaveBeenCalledWith({ autolink_id: '7', - ...repo + ...repo }) expect(github.repos.createAutolink).toHaveBeenCalledWith({ key_prefix: 'NEW_ALPHA-UNDEFINED-', url_template: 'https://test/', is_alphanumeric: true, - ...repo + ...repo }) expect(github.repos.deleteAutolink).toHaveBeenCalledWith({ autolink_id: '8', - ...repo + ...repo }) expect(github.repos.createAutolink).toHaveBeenCalledWith({ key_prefix: 'NEW_ALPHA-FALSE-', url_template: 'https://test/', is_alphanumeric: false, - ...repo + ...repo }) expect(github.repos.deleteAutolink).toHaveBeenCalledWith({ autolink_id: '9', - ...repo + ...repo }) expect(github.repos.createAutolink).toHaveBeenCalledWith({ key_prefix: 'NEW_ALPHA-TRUE-', url_template: 'https://test/', is_alphanumeric: true, - ...repo + ...repo }) expect(github.repos.deleteAutolink).toHaveBeenCalledTimes(5) diff --git a/test/unit/lib/plugins/branches.test.js b/test/unit/lib/plugins/branches.test.js index 68290ea4..4c6f5190 100644 --- a/test/unit/lib/plugins/branches.test.js +++ b/test/unit/lib/plugins/branches.test.js @@ -9,7 +9,7 @@ describe('Branches', () => { log.debug = jest.fn() log.error = jest.fn() - function configure (config) { + function configure(config) { const noop = false const errors = [] return new Branches(noop, github, { owner: 'bkeepers', repo: 'test' }, config, log, errors) diff --git a/test/unit/lib/plugins/collaborators.test.js b/test/unit/lib/plugins/collaborators.test.js index 359dd461..f0dde5d6 100644 --- a/test/unit/lib/plugins/collaborators.test.js +++ b/test/unit/lib/plugins/collaborators.test.js @@ -3,7 +3,7 @@ const Collaborators = require('../../../../lib/plugins/collaborators') describe('Collaborators', () => { let github - function configure (config) { + function configure(config) { const log = { debug: jest.fn(), error: console.error } return new Collaborators(undefined, github, { owner: 'bkeepers', repo: 'test' }, config, log) } diff --git a/test/unit/lib/plugins/custom_properties.test.js b/test/unit/lib/plugins/custom_properties.test.js index 69568a28..5a9fb1af 100644 --- a/test/unit/lib/plugins/custom_properties.test.js +++ b/test/unit/lib/plugins/custom_properties.test.js @@ -5,7 +5,7 @@ describe('CustomProperties', () => { const repo = { owner: 'owner', repo: 'repo' } let log - function configure (config) { + function configure(config) { const nop = false; const errors = [] return new CustomProperties(nop, github, { owner: 'bkeepers', repo: 'test' }, config, log, errors) diff --git a/test/unit/lib/plugins/environments.test.js b/test/unit/lib/plugins/environments.test.js index 276a82cd..ba789c78 100644 --- a/test/unit/lib/plugins/environments.test.js +++ b/test/unit/lib/plugins/environments.test.js @@ -38,14 +38,14 @@ describe('Environments Plugin test suite', () => { variables: [] } }) - when(github.request) + when(github.request) .calledWith('GET /repos/:org/:repo/environments/:environment_name/deployment_protection_rules', { org, repo, environment_name }) .mockResolvedValue({ data: { custom_deployment_protection_rules: [] } }) - } + } ); when(github.request) @@ -698,95 +698,95 @@ describe('Environments Plugin test suite', () => { expect(github.request).toHaveBeenCalledWith('GET /repos/:org/:repo/environments', { org, repo }); ['wait-timer_environment', 'reviewers_environment', 'prevent-self-review_environment', 'deployment-branch-policy_environment', 'deployment-branch-policy-custom_environment', 'variables_environment', 'deployment-protection-rules_environment'].forEach((environment_name) => { - expect(github.request).toHaveBeenCalledWith('GET /repos/:org/:repo/environments/:environment_name/variables', { org, repo, environment_name }); + expect(github.request).toHaveBeenCalledWith('GET /repos/:org/:repo/environments/:environment_name/variables', { org, repo, environment_name }); - expect(github.request).toHaveBeenCalledWith('GET /repos/:org/:repo/environments/:environment_name/deployment_protection_rules', { org, repo, environment_name }); + expect(github.request).toHaveBeenCalledWith('GET /repos/:org/:repo/environments/:environment_name/deployment_protection_rules', { org, repo, environment_name }); }); expect(github.request).toHaveBeenCalledWith('PUT /repos/:org/:repo/environments/:environment_name', expect.objectContaining({ - org, - repo, - environment_name: 'wait-timer_environment', - wait_timer: 1 + org, + repo, + environment_name: 'wait-timer_environment', + wait_timer: 1 })); expect(github.request).toHaveBeenCalledWith('PUT /repos/:org/:repo/environments/:environment_name', expect.objectContaining({ - org, - repo, - environment_name: 'reviewers_environment', - reviewers: [ - { - type: 'User', - id: 1 - }, - { - type: 'Team', - id: 2 - } - ] + org, + repo, + environment_name: 'reviewers_environment', + reviewers: [ + { + type: 'User', + id: 1 + }, + { + type: 'Team', + id: 2 + } + ] })); expect(github.request).toHaveBeenCalledWith('PUT /repos/:org/:repo/environments/:environment_name', expect.objectContaining({ - org, - repo, - environment_name: 'prevent-self-review_environment', - prevent_self_review: true + org, + repo, + environment_name: 'prevent-self-review_environment', + prevent_self_review: true })); expect(github.request).toHaveBeenCalledWith('PUT /repos/:org/:repo/environments/:environment_name', expect.objectContaining({ - org, - repo, - environment_name: 'prevent-self-review_environment', - prevent_self_review: true + org, + repo, + environment_name: 'prevent-self-review_environment', + prevent_self_review: true })); expect(github.request).toHaveBeenCalledWith('PUT /repos/:org/:repo/environments/:environment_name', expect.objectContaining({ - org, - repo, - environment_name: 'deployment-branch-policy_environment', - deployment_branch_policy: { - protected_branches: true, - custom_branch_policies: false - } + org, + repo, + environment_name: 'deployment-branch-policy_environment', + deployment_branch_policy: { + protected_branches: true, + custom_branch_policies: false + } })); expect(github.request).toHaveBeenCalledWith('PUT /repos/:org/:repo/environments/:environment_name', expect.objectContaining({ - org, - repo, - environment_name: 'deployment-branch-policy-custom_environment', - deployment_branch_policy: { - protected_branches: false, - custom_branch_policies: true - } + org, + repo, + environment_name: 'deployment-branch-policy-custom_environment', + deployment_branch_policy: { + protected_branches: false, + custom_branch_policies: true + } })); expect(github.request).toHaveBeenCalledWith('POST /repos/:org/:repo/environments/:environment_name/deployment-branch-policies', expect.objectContaining({ - org, - repo, - environment_name: 'deployment-branch-policy-custom_environment', - name: 'master' + org, + repo, + environment_name: 'deployment-branch-policy-custom_environment', + name: 'master' })); expect(github.request).toHaveBeenCalledWith('POST /repos/:org/:repo/environments/:environment_name/deployment-branch-policies', expect.objectContaining({ - org, - repo, - environment_name: 'deployment-branch-policy-custom_environment', - name: 'dev' + org, + repo, + environment_name: 'deployment-branch-policy-custom_environment', + name: 'dev' })); expect(github.request).toHaveBeenCalledWith('POST /repos/:org/:repo/environments/:environment_name/variables', expect.objectContaining({ - org, - repo, - environment_name: 'variables_environment', - name: 'test', - value: 'test' + org, + repo, + environment_name: 'variables_environment', + name: 'test', + value: 'test' })); expect(github.request).toHaveBeenCalledWith('POST /repos/:org/:repo/environments/:environment_name/deployment_protection_rules', expect.objectContaining({ - org, - repo, - environment_name: 'deployment-protection-rules_environment', - integration_id: 1 + org, + repo, + environment_name: 'deployment-protection-rules_environment', + integration_id: 1 })); }) }) @@ -854,59 +854,59 @@ describe('Environments Plugin test suite', () => { ] }, { - name: 'new-wait-timer', - wait_timer: 1 + name: 'new-wait-timer', + wait_timer: 1 }, { - name: 'new-reviewers', - reviewers: [ - { - type: 'User', - id: 1 - }, - { - type: 'Team', - id: 2 - } - ] + name: 'new-reviewers', + reviewers: [ + { + type: 'User', + id: 1 + }, + { + type: 'Team', + id: 2 + } + ] }, { - name: 'new-prevent-self-review', - prevent_self_review: true + name: 'new-prevent-self-review', + prevent_self_review: true }, { - name: 'new-deployment-branch-policy', - deployment_branch_policy: { - protected_branches: true, - custom_branch_policies: false - } + name: 'new-deployment-branch-policy', + deployment_branch_policy: { + protected_branches: true, + custom_branch_policies: false + } }, { - name: 'new-deployment-branch-policy-custom', - deployment_branch_policy: { - protected_branches: false, - custom_branch_policies: [ - 'master', - 'dev' - ] - } + name: 'new-deployment-branch-policy-custom', + deployment_branch_policy: { + protected_branches: false, + custom_branch_policies: [ + 'master', + 'dev' + ] + } }, { - name: 'new-variables', - variables: [ - { - name: 'test', - value: 'test' - } - ] + name: 'new-variables', + variables: [ + { + name: 'test', + value: 'test' + } + ] }, { - name: 'new-deployment-protection-rules', - deployment_protection_rules: [ - { - app_id: 1 - } - ] + name: 'new-deployment-protection-rules', + deployment_protection_rules: [ + { + app_id: 1 + } + ] } ], log, errors); @@ -957,95 +957,95 @@ describe('Environments Plugin test suite', () => { expect(github.request).toHaveBeenCalledWith('GET /repos/:org/:repo/environments', { org, repo }); ['wait-timer_environment', 'reviewers_environment', 'prevent-self-review_environment', 'deployment-branch-policy_environment', 'deployment-branch-policy-custom_environment', 'variables_environment', 'deployment-protection-rules_environment'].forEach((environment_name) => { - expect(github.request).toHaveBeenCalledWith('GET /repos/:org/:repo/environments/:environment_name/variables', { org, repo, environment_name }); + expect(github.request).toHaveBeenCalledWith('GET /repos/:org/:repo/environments/:environment_name/variables', { org, repo, environment_name }); - expect(github.request).toHaveBeenCalledWith('GET /repos/:org/:repo/environments/:environment_name/deployment_protection_rules', { org, repo, environment_name }); + expect(github.request).toHaveBeenCalledWith('GET /repos/:org/:repo/environments/:environment_name/deployment_protection_rules', { org, repo, environment_name }); }); expect(github.request).toHaveBeenCalledWith('PUT /repos/:org/:repo/environments/:environment_name', expect.objectContaining({ - org, - repo, - environment_name: 'wait-timer_environment', - wait_timer: 1 + org, + repo, + environment_name: 'wait-timer_environment', + wait_timer: 1 })); expect(github.request).toHaveBeenCalledWith('PUT /repos/:org/:repo/environments/:environment_name', expect.objectContaining({ - org, - repo, - environment_name: 'reviewers_environment', - reviewers: [ - { - type: 'User', - id: 1 - }, - { - type: 'Team', - id: 2 - } - ] + org, + repo, + environment_name: 'reviewers_environment', + reviewers: [ + { + type: 'User', + id: 1 + }, + { + type: 'Team', + id: 2 + } + ] })); expect(github.request).toHaveBeenCalledWith('PUT /repos/:org/:repo/environments/:environment_name', expect.objectContaining({ - org, - repo, - environment_name: 'prevent-self-review_environment', - prevent_self_review: true + org, + repo, + environment_name: 'prevent-self-review_environment', + prevent_self_review: true })); expect(github.request).toHaveBeenCalledWith('PUT /repos/:org/:repo/environments/:environment_name', expect.objectContaining({ - org, - repo, - environment_name: 'prevent-self-review_environment', - prevent_self_review: true + org, + repo, + environment_name: 'prevent-self-review_environment', + prevent_self_review: true })); expect(github.request).toHaveBeenCalledWith('PUT /repos/:org/:repo/environments/:environment_name', expect.objectContaining({ - org, - repo, - environment_name: 'deployment-branch-policy_environment', - deployment_branch_policy: { - protected_branches: true, - custom_branch_policies: false - } + org, + repo, + environment_name: 'deployment-branch-policy_environment', + deployment_branch_policy: { + protected_branches: true, + custom_branch_policies: false + } })); expect(github.request).toHaveBeenCalledWith('PUT /repos/:org/:repo/environments/:environment_name', expect.objectContaining({ - org, - repo, - environment_name: 'deployment-branch-policy-custom_environment', - deployment_branch_policy: { - protected_branches: false, - custom_branch_policies: true - } + org, + repo, + environment_name: 'deployment-branch-policy-custom_environment', + deployment_branch_policy: { + protected_branches: false, + custom_branch_policies: true + } })); expect(github.request).toHaveBeenCalledWith('POST /repos/:org/:repo/environments/:environment_name/deployment-branch-policies', expect.objectContaining({ - org, - repo, - environment_name: 'deployment-branch-policy-custom_environment', - name: 'master' + org, + repo, + environment_name: 'deployment-branch-policy-custom_environment', + name: 'master' })); expect(github.request).toHaveBeenCalledWith('POST /repos/:org/:repo/environments/:environment_name/deployment-branch-policies', expect.objectContaining({ - org, - repo, - environment_name: 'deployment-branch-policy-custom_environment', - name: 'dev' + org, + repo, + environment_name: 'deployment-branch-policy-custom_environment', + name: 'dev' })); expect(github.request).toHaveBeenCalledWith('POST /repos/:org/:repo/environments/:environment_name/variables', expect.objectContaining({ - org, - repo, - environment_name: 'variables_environment', - name: 'test', - value: 'test' + org, + repo, + environment_name: 'variables_environment', + name: 'test', + value: 'test' })); expect(github.request).toHaveBeenCalledWith('POST /repos/:org/:repo/environments/:environment_name/deployment_protection_rules', expect.objectContaining({ - org, - repo, - environment_name: 'deployment-protection-rules_environment', - integration_id: 1 + org, + repo, + environment_name: 'deployment-protection-rules_environment', + integration_id: 1 })); //assert - seven new environments were also added diff --git a/test/unit/lib/plugins/labels.test.js b/test/unit/lib/plugins/labels.test.js index a94ffb5b..51e3a967 100644 --- a/test/unit/lib/plugins/labels.test.js +++ b/test/unit/lib/plugins/labels.test.js @@ -18,7 +18,7 @@ describe('Labels', () => { issues: { listLabelsForRepo: { endpoint: { - merge: jest.fn().mockImplementation(() => {}) + merge: jest.fn().mockImplementation(() => { }) } }, createLabel: jest.fn().mockImplementation(() => Promise.resolve()), diff --git a/test/unit/lib/plugins/milestones.test.js b/test/unit/lib/plugins/milestones.test.js index 93cde7db..bbe2175b 100644 --- a/test/unit/lib/plugins/milestones.test.js +++ b/test/unit/lib/plugins/milestones.test.js @@ -3,7 +3,7 @@ const Milestones = require('../../../../lib/plugins/milestones') describe.skip('Milestones', () => { let github - function configure (config) { + function configure(config) { return new Milestones(github, { owner: 'bkeepers', repo: 'test' }, config) } @@ -13,7 +13,7 @@ describe.skip('Milestones', () => { issues: { listMilestonesForRepo: { endpoint: { - merge: jest.fn().mockImplementation(() => {}) + merge: jest.fn().mockImplementation(() => { }) } }, createMilestone: jest.fn().mockImplementation(() => Promise.resolve()), diff --git a/test/unit/lib/plugins/repository.test.js b/test/unit/lib/plugins/repository.test.js index b7af3912..01630dd5 100644 --- a/test/unit/lib/plugins/repository.test.js +++ b/test/unit/lib/plugins/repository.test.js @@ -16,7 +16,7 @@ describe('Repository', () => { log.debug = jest.fn() log.error = jest.fn() - function configure (config) { + function configure(config) { const noop = false const errors = [] return new Repository(noop, github, { owner: 'bkeepers', repo: 'test' }, config, 1, log, errors) diff --git a/test/unit/lib/plugins/teams.test.js b/test/unit/lib/plugins/teams.test.js index f289421e..26e35817 100644 --- a/test/unit/lib/plugins/teams.test.js +++ b/test/unit/lib/plugins/teams.test.js @@ -14,7 +14,7 @@ describe('Teams', () => { const unchangedTeamId = any.integer() const org = 'bkeepers' - function configure (config) { + function configure(config) { const log = { debug: jest.fn(), error: console.error } const errors = [] return new Teams(undefined, github, { owner: 'bkeepers', repo: 'test' }, config, log, errors) diff --git a/test/unit/lib/settings.test.js b/test/unit/lib/settings.test.js index c91583d3..81f232d3 100644 --- a/test/unit/lib/settings.test.js +++ b/test/unit/lib/settings.test.js @@ -25,32 +25,32 @@ describe('Settings Tests', () => { beforeEach(() => { const mockOctokit = jest.mocked(Octokit) const content = Buffer.from(` -suborgrepos: -- new-repo -#- test* -#- secret* - +suborgrepos: +- new-repo +#- test* +#- secret* + suborgteams: - core -suborgproperties: +suborgproperties: - EDP: true - do_no_delete: true - -teams: - - name: core - permission: bypass + +teams: + - name: core + permission: bypass - name: docss permission: pull - name: docs permission: pull - + validator: - pattern: '[a-zA-Z0-9_-]+_[a-zA-Z0-9_-]+.*' + pattern: '[a-zA-Z0-9_-]+_[a-zA-Z0-9_-]+.*' -repository: +repository: # A comma-separated list of topics to set on the repository - topics: + topics: - frontend `).toString('base64'); mockOctokit.repos = { @@ -200,29 +200,29 @@ repository: } } subOrgConfig = yaml.load(` - suborgrepos: - - new-repo - - suborgproperties: + suborgrepos: + - new-repo + + suborgproperties: - EDP: true - do_no_delete: true - - teams: - - name: core - permission: bypass + + teams: + - name: core + permission: bypass - name: docss permission: pull - name: docs permission: pull - + validator: - pattern: '[a-zA-Z0-9_-]+_[a-zA-Z0-9_-]+.*' - - repository: + pattern: '[a-zA-Z0-9_-]+_[a-zA-Z0-9_-]+.*' + + repository: # A comma-separated list of topics to set on the repository - topics: + topics: - frontend - + `) })