diff --git a/.eslintrc.js b/.eslintrc.js index 6d5952d4900c022df6021ce05e26842d4c5668c8..10ba93515fcd4146f913051e8fbf2984cf8e6ad5 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -6,8 +6,7 @@ module.exports = { extends: [ 'airbnb-typescript/base', 'plugin:@typescript-eslint/recommended', - // TODO: enable in separate PR - // 'plugin:@typescript-eslint/recommended-requiring-type-checking', + 'plugin:@typescript-eslint/recommended-requiring-type-checking', 'plugin:promise/recommended', 'prettier', 'prettier/@typescript-eslint', @@ -71,6 +70,7 @@ module.exports = { '@typescript-eslint/no-var-requires': 0, '@typescript-eslint/no-object-literal-type-assertion': 0, '@typescript-eslint/explicit-function-return-type': 0, + '@typescript-eslint/unbound-method': 0, }, }, ], diff --git a/lib/config/presets.ts b/lib/config/presets.ts index 06e217559aff1a7298ac12db6ae86586fea98eb9..e41361ed81a088147b64447f4b9f32299b64da27 100644 --- a/lib/config/presets.ts +++ b/lib/config/presets.ts @@ -76,13 +76,13 @@ export function parsePreset(input: string): ParsedPreset { .map(elem => elem.trim()); str = str.slice(0, str.indexOf('(')); } - if (str[0] === ':') { + if (str.startsWith(':')) { // default namespace packageName = 'renovate-config-default'; presetName = str.slice(1); - } else if (str[0] === '@') { + } else if (str.startsWith('@')) { // scoped namespace - [, packageName] = str.match(/(@.*?)(:|$)/); + [, packageName] = /(@.*?)(:|$)/.exec(str); str = str.slice(packageName.length); if (!packageName.includes('/')) { packageName += '/renovate-config'; @@ -94,7 +94,7 @@ export function parsePreset(input: string): ParsedPreset { } } else { // non-scoped namespace - [, packageName] = str.match(/(.*?)(:|$)/); + [, packageName] = /(.*?)(:|$)/.exec(str); presetName = str.slice(packageName.length + 1); if ( datasource === DATASOURCE_NPM && diff --git a/lib/config/validation.ts b/lib/config/validation.ts index db22a69c1f33629747f7043d5148b566b598e0e2..0b584c669cebb2df78eada26c598ca2bbac3d1dc 100644 --- a/lib/config/validation.ts +++ b/lib/config/validation.ts @@ -138,9 +138,10 @@ export async function validateConfig( } } if (key === 'extends') { + const tzRe = /^:timezone\((.+)\)$/; for (const subval of val) { - if (is.string(subval) && subval.match(/^:timezone(.+)$/)) { - const [, timezone] = subval.match(/^:timezone\((.+)\)$/); + if (is.string(subval) && tzRe.test(subval)) { + const [, timezone] = tzRe.exec(subval); const [validTimezone, errorMessage] = hasValidTimezone( timezone ); @@ -226,7 +227,7 @@ export async function validateConfig( } if ( (selectors.includes(key) || key === 'matchCurrentVersion') && - !(parentPath && parentPath.match(/p.*Rules\[\d+\]$/)) && // Inside a packageRule + !/p.*Rules\[\d+\]$/.test(parentPath) && // Inside a packageRule (parentPath || !isPreset) // top level in a preset ) { errors.push({ diff --git a/lib/datasource/cargo/index.ts b/lib/datasource/cargo/index.ts index d36ccdc120729f6f24851dafd6c6fa995cd5c8c6..f20c6f58e904209e37a4db0114d70744c99efd61 100644 --- a/lib/datasource/cargo/index.ts +++ b/lib/datasource/cargo/index.ts @@ -60,6 +60,7 @@ export async function getPkgReleases({ return null; } // Filter empty lines (takes care of trailing \n) + // eslint-disable-next-line @typescript-eslint/unbound-method res = res.map(JSON.parse); if (res[0].name !== lookupName) { logger.warn( diff --git a/lib/datasource/cdnjs/index.ts b/lib/datasource/cdnjs/index.ts index 29276fb2f48735b486836afa8ed8fc0a75d97490..22c8758f42ccf1cb5be52431f91d777e780179ed 100644 --- a/lib/datasource/cdnjs/index.ts +++ b/lib/datasource/cdnjs/index.ts @@ -56,7 +56,7 @@ export async function getPkgReleases({ const { assets, homepage, repository } = cdnjsResp; const releases = assets - .filter(({ files }) => files.indexOf(assetName) !== -1) + .filter(({ files }) => files.includes(assetName)) .map(({ version }) => ({ version })); const result: ReleaseResult = { releases }; diff --git a/lib/datasource/docker/index.ts b/lib/datasource/docker/index.ts index 28c5e04be73db41bc8a698468777907dc494c44b..e06e7c66b6b0d1511130f158ab6bf0987216ed84 100644 --- a/lib/datasource/docker/index.ts +++ b/lib/datasource/docker/index.ts @@ -43,7 +43,7 @@ export function getRegistryRepository( if (!registry || registry === 'docker.io') { registry = 'index.docker.io'; } - if (!registry.match('^https?://')) { + if (!/^https?:\/\//.exec(registry)) { registry = `https://${registry}`; } const opts = hostRules.find({ hostType: 'docker', url: registry }); @@ -113,7 +113,7 @@ async function getAuthHeaders( } = hostRules.find({ hostType: 'docker', url: apiCheckUrl }); opts.json = true; if (ecrRegex.test(registry)) { - const region = registry.match(ecrRegex)[1]; + const [, region] = ecrRegex.exec(registry); const auth = await getECRAuthToken(region, opts); if (auth) { opts.headers = { authorization: `Basic ${auth}` }; diff --git a/lib/datasource/github/index.ts b/lib/datasource/github/index.ts index 83b15f8d6418412f8a516b62108be85179606c8e..ea95cdc9ef6e9e054a0af7f64e73bd01997c023d 100644 --- a/lib/datasource/github/index.ts +++ b/lib/datasource/github/index.ts @@ -9,7 +9,7 @@ import { logger } from '../../logger'; import got, { GotJSONOptions } from '../../util/got'; import { PLATFORM_FAILURE } from '../../constants/error-messages'; -const ghGot = api.get; +const { get: ghGot } = api; async function fetchJSONFile(repo: string, fileName: string): Promise<Preset> { const url = `https://api.github.com/repos/${repo}/contents/${fileName}`; diff --git a/lib/datasource/gitlab/index.ts b/lib/datasource/gitlab/index.ts index 091a26afa7f3a26d3e571aeb307ee57f54e75b36..3515415cf7f6f29e26e9100f3b5d76ef3aceb82d 100644 --- a/lib/datasource/gitlab/index.ts +++ b/lib/datasource/gitlab/index.ts @@ -3,7 +3,7 @@ import { api } from '../../platform/gitlab/gl-got-wrapper'; import { logger } from '../../logger'; import { PkgReleaseConfig, ReleaseResult, Preset } from '../common'; -const glGot = api.get; +const { get: glGot } = api; const GitLabApiUrl = 'https://gitlab.com/api/v4/projects'; diff --git a/lib/datasource/index.ts b/lib/datasource/index.ts index 9e7d1d7deda0050dd770d46ddd230de0a7e75184..392642d3aab5b83d01eec3163b78cfbe5eb29355 100644 --- a/lib/datasource/index.ts +++ b/lib/datasource/index.ts @@ -126,7 +126,7 @@ export async function getPkgReleases( } export function supportsDigests(config: DigestConfig): boolean { - return !!datasources[config.datasource].getDigest; + return 'getDigest' in datasources[config.datasource]; } export function getDigest( diff --git a/lib/datasource/maven/index.ts b/lib/datasource/maven/index.ts index 9a37f58e7588a98f1d54d5082918ee6632758e84..c6916401d602c4308b810afd5a379957ea9dcc67 100644 --- a/lib/datasource/maven/index.ts +++ b/lib/datasource/maven/index.ts @@ -93,7 +93,8 @@ async function getDependencyInfo( } function getLatestStableVersion(versions: string[]): string | null { - const stableVersions = versions.filter(mavenVersion.isStable); + const { isStable } = mavenVersion; // auto this bind + const stableVersions = versions.filter(isStable); if (stableVersions.length) { return stableVersions.reduce((latestVersion, version) => compare(version, latestVersion) === 1 ? version : latestVersion diff --git a/lib/datasource/rubygems/get-rubygems-org.ts b/lib/datasource/rubygems/get-rubygems-org.ts index 208f814fd55743b97dce8e32bcfda5d9ae261bc5..b415d7bbc10170988d584e62f34ecd5478f026f8 100644 --- a/lib/datasource/rubygems/get-rubygems-org.ts +++ b/lib/datasource/rubygems/get-rubygems-org.ts @@ -83,6 +83,7 @@ function isDataStale(): boolean { async function syncVersions(): Promise<void> { if (isDataStale()) { global.updateRubyGemsVersions = + // eslint-disable-next-line @typescript-eslint/no-misused-promises global.updateRubyGemsVersions || updateRubyGemsVersions(); await global.updateRubyGemsVersions; delete global.updateRubyGemsVersions; diff --git a/lib/datasource/sbt/index.ts b/lib/datasource/sbt/index.ts index 78458fc084d6e430a361f1467624ed3aa893fb11..3656b5b08724560001b9e6d4dd7b36d3969e23ba 100644 --- a/lib/datasource/sbt/index.ts +++ b/lib/datasource/sbt/index.ts @@ -20,15 +20,15 @@ async function resolvePackageReleases( const parseSubdirs = (content: string): string[] => parseIndexDir(content, x => { if (x === artifact) return true; - if (x.indexOf(`${artifact}_native`) === 0) return false; - if (x.indexOf(`${artifact}_sjs`) === 0) return false; - return x.indexOf(`${artifact}_`) === 0; + if (x.startsWith(`${artifact}_native`)) return false; + if (x.startsWith(`${artifact}_sjs`)) return false; + return x.startsWith(`${artifact}_`); }); const artifactSubdirs = parseSubdirs(indexContent); let searchSubdirs = artifactSubdirs; if ( scalaVersion && - artifactSubdirs.indexOf(`${artifact}_${scalaVersion}`) !== -1 + artifactSubdirs.includes(`${artifact}_${scalaVersion}`) ) { searchSubdirs = [`${artifact}_${scalaVersion}`]; } @@ -66,10 +66,9 @@ async function resolvePluginReleases( const releases: string[] = []; const scalaVersionItems = parse(indexContent); const scalaVersions = scalaVersionItems.map(x => x.replace(/^scala_/, '')); - const searchVersions = - scalaVersions.indexOf(scalaVersion) === -1 - ? scalaVersions - : [scalaVersion]; + const searchVersions = !scalaVersions.includes(scalaVersion) + ? scalaVersions + : [scalaVersion]; for (const searchVersion of searchVersions) { const searchSubRoot = `${searchRoot}/scala_${searchVersion}`; const subRootContent = await downloadHttpProtocol( diff --git a/lib/datasource/terraform/index.ts b/lib/datasource/terraform/index.ts index 045d2bf044078b281b660f608422cb30dbd0be35..121ecfe0a3882bc68293993b56561594c4bc3dae 100644 --- a/lib/datasource/terraform/index.ts +++ b/lib/datasource/terraform/index.ts @@ -22,7 +22,7 @@ function getRegistryRepository( } else { registry = 'registry.terraform.io'; } - if (!registry.match('^https?://')) { + if (!/^https?:\/\//.test(registry)) { registry = `https://${registry}`; } const repository = split.join('/'); diff --git a/lib/manager/ansible/extract.ts b/lib/manager/ansible/extract.ts index f50ea788232a6437bac65f439be6368725358eaf..fa71966b0e7e974cbbe39dcc3241e290c7f67e40 100644 --- a/lib/manager/ansible/extract.ts +++ b/lib/manager/ansible/extract.ts @@ -9,8 +9,9 @@ export default function extractPackageFile( logger.trace('ansible.extractPackageFile()'); let deps: PackageDependency[] = []; let lineNumber = 0; + const re = /^\s*image:\s*'?"?([^\s'"]+)'?"?\s*$/; for (const line of content.split('\n')) { - const match = line.match(/^\s*image:\s*'?"?([^\s'"]+)'?"?\s*$/); + const match = re.exec(line); if (match) { const currentFrom = match[1]; const dep = getDep(currentFrom); diff --git a/lib/manager/ansible/update.ts b/lib/manager/ansible/update.ts index 8b7b2282f6af1ea85302019157fc1439b4a65476..7e4e272673392937e77e80ade8a55b76d463397e 100644 --- a/lib/manager/ansible/update.ts +++ b/lib/manager/ansible/update.ts @@ -13,7 +13,7 @@ export default function updateDependency( const lines = fileContent.split('\n'); const lineToChange = lines[upgrade.managerData.lineNumber]; const imageLine = regEx(`^(\\s*image:\\s*'?"?)[^\\s'"]+('?"?\\s*)$`); - if (!lineToChange.match(imageLine)) { + if (!imageLine.test(lineToChange)) { logger.debug('No image line found'); return null; } diff --git a/lib/manager/bazel/extract.ts b/lib/manager/bazel/extract.ts index 5b9aa1cd0a9c3aa7becc767f2bda5c5b866b40f3..ac9182d78c68950d039f4a86edaf0528a367d72a 100644 --- a/lib/manager/bazel/extract.ts +++ b/lib/manager/bazel/extract.ts @@ -120,48 +120,48 @@ export function extractPackageFile(content: string): PackageFile | null { let digest: string; let repository: string; let registry: string; - let match = def.match(/name\s*=\s*"([^"]+)"/); + let match = /name\s*=\s*"([^"]+)"/.exec(def); if (match) { [, depName] = match; } - match = def.match(/digest\s*=\s*"([^"]+)"/); + match = /digest\s*=\s*"([^"]+)"/.exec(def); if (match) { [, digest] = match; } - match = def.match(/registry\s*=\s*"([^"]+)"/); + match = /registry\s*=\s*"([^"]+)"/.exec(def); if (match) { [, registry] = match; } - match = def.match(/repository\s*=\s*"([^"]+)"/); + match = /repository\s*=\s*"([^"]+)"/.exec(def); if (match) { [, repository] = match; } - match = def.match(/remote\s*=\s*"([^"]+)"/); + match = /remote\s*=\s*"([^"]+)"/.exec(def); if (match) { [, remote] = match; } - match = def.match(/tag\s*=\s*"([^"]+)"/); + match = /tag\s*=\s*"([^"]+)"/.exec(def); if (match) { [, currentValue] = match; } - match = def.match(/url\s*=\s*"([^"]+)"/); + match = /url\s*=\s*"([^"]+)"/.exec(def); if (match) { [, url] = match; } - match = def.match(/urls\s*=\s*\[\s*"([^\]]+)",?\s*\]/); + match = /urls\s*=\s*\[\s*"([^\]]+)",?\s*\]/.exec(def); if (match) { const urls = match[1].replace(/\s/g, '').split('","'); url = urls.find(parseUrl); } - match = def.match(/commit\s*=\s*"([^"]+)"/); + match = /commit\s*=\s*"([^"]+)"/.exec(def); if (match) { [, commit] = match; } - match = def.match(/sha256\s*=\s*"([^"]+)"/); + match = /sha256\s*=\s*"([^"]+)"/.exec(def); if (match) { [, sha256] = match; } - match = def.match(/importpath\s*=\s*"([^"]+)"/); + match = /importpath\s*=\s*"([^"]+)"/.exec(def); if (match) { [, importpath] = match; } @@ -198,8 +198,8 @@ export function extractPackageFile(content: string): PackageFile | null { dep.datasource = DATASOURCE_GO; dep.lookupName = importpath; if (remote) { - const remoteMatch = remote.match( - /https:\/\/github\.com(?:.*\/)(([a-zA-Z]+)([-])?([a-zA-Z]+))/ + const remoteMatch = /https:\/\/github\.com(?:.*\/)(([a-zA-Z]+)([-])?([a-zA-Z]+))/.exec( + remote ); if (remoteMatch && remoteMatch[0].length === remote.length) { dep.lookupName = remote.replace('https://', ''); @@ -223,7 +223,7 @@ export function extractPackageFile(content: string): PackageFile | null { const parsedUrl = parseUrl(url); dep.depName = depName; dep.repo = parsedUrl.repo; - if (parsedUrl.currentValue.match(/^[a-f0-9]{40}$/i)) { + if (/^[a-f0-9]{40}$/i.test(parsedUrl.currentValue)) { dep.currentDigest = parsedUrl.currentValue; } else { dep.currentValue = parsedUrl.currentValue; diff --git a/lib/manager/bazel/update.ts b/lib/manager/bazel/update.ts index 7877606fe1fd148c0302f4e88dbf1060dadc7b08..4dcc1c1d8461e51ba2d948f9e6117e7665a9f031 100644 --- a/lib/manager/bazel/update.ts +++ b/lib/manager/bazel/update.ts @@ -19,7 +19,7 @@ function updateWithNewVersion( } function extractUrl(flattened: string): string[] | null { - const urlMatch = flattened.match(/url="(.*?)"/); + const urlMatch = /url="(.*?)"/.exec(flattened); if (!urlMatch) { logger.debug('Cannot locate urls in new definition'); return null; @@ -29,7 +29,7 @@ function extractUrl(flattened: string): string[] | null { function extractUrls(content: string): string[] | null { const flattened = content.replace(/\n/g, '').replace(/\s/g, ''); - const urlsMatch = flattened.match(/urls?=\[.*?\]/); + const urlsMatch = /urls?=\[.*?\]/.exec(flattened); if (!urlsMatch) { return extractUrl(flattened); } @@ -158,7 +158,7 @@ export async function updateDependency( } const existingDef = regEx(existingRegExStr); // istanbul ignore if - if (!fileContent.match(existingDef)) { + if (!existingDef.test(fileContent)) { logger.info('Cannot match existing string'); return null; } diff --git a/lib/manager/buildkite/extract.ts b/lib/manager/buildkite/extract.ts index 1ceca164d42c2e3686bb486d4c3d612f87fad994..51b566c038550bc8d354e4a28c0a424e54f0cb64 100644 --- a/lib/manager/buildkite/extract.ts +++ b/lib/manager/buildkite/extract.ts @@ -12,18 +12,16 @@ export function extractPackageFile(content: string): PackageFile | null { for (let lineNumber = 1; lineNumber <= lines.length; lineNumber += 1) { const lineIdx = lineNumber - 1; const line = lines[lineIdx]; - const pluginsSection = line.match( - /^(?<pluginsIndent>\s*)(-?\s*)plugins:/ - ); + const pluginsSection = /^(?<pluginsIndent>\s*)(-?\s*)plugins:/.exec(line); if (pluginsSection) { logger.trace(`Matched plugins on line ${lineNumber}`); isPluginsSection = true; pluginsIndent = pluginsSection.groups.pluginsIndent; } else if (isPluginsSection) { logger.debug(`serviceImageLine: "${line}"`); - const { currentIndent } = line.match(/^(?<currentIndent>\s*)/).groups; - const depLineMatch = line.match( - /^\s+(?:-\s+)?(?<depName>[^#]+)#(?<currentValue>[^:]+)/ + const { currentIndent } = /^(?<currentIndent>\s*)/.exec(line).groups; + const depLineMatch = /^\s+(?:-\s+)?(?<depName>[^#]+)#(?<currentValue>[^:]+)/.exec( + line ); if (currentIndent.length <= pluginsIndent.length) { isPluginsSection = false; diff --git a/lib/manager/buildkite/update.ts b/lib/manager/buildkite/update.ts index 3c709b9df929ba3129642157b4a4c9c22cb836bf..e400dd15a927eeabe312c30be5377d4ab79b33b5 100644 --- a/lib/manager/buildkite/update.ts +++ b/lib/manager/buildkite/update.ts @@ -12,7 +12,7 @@ export function updateDependency( const lines = currentFileContent.split('\n'); const lineToChange = lines[lineIdx]; const depLine = regEx(`^(\\s+[^#]+#)[^:]+(.*)$`); - if (!lineToChange.match(depLine)) { + if (!depLine.test(lineToChange)) { logger.debug('No image line found'); return null; } diff --git a/lib/manager/bundler/extract.ts b/lib/manager/bundler/extract.ts index a26b1554efa0ab4298ebbce3f238f3f6a0984c64..b5a5dbb99c049dda0e072b17f8fc40a8e43fc294 100644 --- a/lib/manager/bundler/extract.ts +++ b/lib/manager/bundler/extract.ts @@ -22,8 +22,8 @@ export async function extractPackageFile( for (const delimiter of delimiters) { sourceMatch = sourceMatch || - line.match( - regEx(`^source ${delimiter}([^${delimiter}]+)${delimiter}\\s*$`) + regEx(`^source ${delimiter}([^${delimiter}]+)${delimiter}\\s*$`).exec( + line ); } if (sourceMatch) { @@ -33,7 +33,7 @@ export async function extractPackageFile( for (const delimiter of delimiters) { rubyMatch = rubyMatch || - line.match(regEx(`^ruby ${delimiter}([^${delimiter}]+)${delimiter}`)); + regEx(`^ruby ${delimiter}([^${delimiter}]+)${delimiter}`).exec(line); } if (rubyMatch) { res.compatibility = { ruby: rubyMatch[1] }; @@ -42,9 +42,9 @@ export async function extractPackageFile( let gemDelimiter: string; for (const delimiter of delimiters) { const gemMatchRegex = `^gem ${delimiter}([^${delimiter}]+)${delimiter}(,\\s+${delimiter}([^${delimiter}]+)${delimiter}){0,2}`; - if (line.match(regEx(gemMatchRegex))) { + if (regEx(gemMatchRegex).test(line)) { gemDelimiter = delimiter; - gemMatch = gemMatch || line.match(regEx(gemMatchRegex)); + gemMatch = gemMatch || regEx(gemMatchRegex).exec(line); } } if (gemMatch) { @@ -68,7 +68,7 @@ export async function extractPackageFile( } res.deps.push(dep); } - const groupMatch = line.match(/^group\s+(.*?)\s+do/); + const groupMatch = /^group\s+(.*?)\s+do/.exec(line); if (groupMatch) { const depTypes = groupMatch[1] .split(',') @@ -98,9 +98,9 @@ export async function extractPackageFile( } } for (const delimiter of delimiters) { - const sourceBlockMatch = line.match( - regEx(`^source\\s+${delimiter}(.*?)${delimiter}\\s+do`) - ); + const sourceBlockMatch = regEx( + `^source\\s+${delimiter}(.*?)${delimiter}\\s+do` + ).exec(line); if (sourceBlockMatch) { const repositoryUrl = sourceBlockMatch[1]; const sourceLineNumber = lineNumber; @@ -132,7 +132,7 @@ export async function extractPackageFile( } } } - const platformsMatch = line.match(/^platforms\s+(.*?)\s+do/); + const platformsMatch = /^platforms\s+(.*?)\s+do/.test(line); if (platformsMatch) { const platformsLineNumber = lineNumber; let platformsContent = ''; @@ -157,7 +157,7 @@ export async function extractPackageFile( ); } } - const ifMatch = line.match(/^if\s+(.*?)/); + const ifMatch = /^if\s+(.*?)/.test(line); if (ifMatch) { const ifLineNumber = lineNumber; let ifContent = ''; @@ -199,7 +199,7 @@ export async function extractPackageFile( dep.lockedVersion = lockedDepValue; } } - const bundledWith = lockContent.match(/\nBUNDLED WITH\n\s+(.*?)(\n|$)/); + const bundledWith = /\nBUNDLED WITH\n\s+(.*?)(\n|$)/.exec(lockContent); if (bundledWith) { res.compatibility = res.compatibility || {}; res.compatibility.bundler = bundledWith[1]; diff --git a/lib/manager/cdnurl/extract.ts b/lib/manager/cdnurl/extract.ts index d5c9de0d407a5296bf23460c3f65793be0fecd9c..10380ba0745622cbd057771a9fbf8f50cefe39e5 100644 --- a/lib/manager/cdnurl/extract.ts +++ b/lib/manager/cdnurl/extract.ts @@ -6,7 +6,7 @@ export function extractPackageFile(content: string): PackageFile { const regex = /\/\/cdnjs\.cloudflare\.com\/ajax\/libs\/(?<depName>[^/]+?)\/(?<currentValue>[^/]+?)\/(?<asset>[-_.a-zA-Z0-9]+)/; let rest = content; - let match = rest.match(regex); + let match = regex.exec(rest); let offset = 0; while (match) { const [wholeSubstr] = match; @@ -17,7 +17,7 @@ export function extractPackageFile(content: string): PackageFile { offset += match.index + wholeSubstr.length; rest = content.slice(offset); - match = rest.match(regex); + match = regex.exec(rest); deps.push({ datasource: DATASOURCE_CDNJS, diff --git a/lib/manager/circleci/extract.ts b/lib/manager/circleci/extract.ts index 99a36c682b758fc66bf53eca29354d7915840150..474955546921e1791880af1f4d950f7bed3fbaa0 100644 --- a/lib/manager/circleci/extract.ts +++ b/lib/manager/circleci/extract.ts @@ -10,7 +10,7 @@ export function extractPackageFile(content: string): PackageFile | null { const lines = content.split('\n'); for (let lineNumber = 0; lineNumber < lines.length; lineNumber += 1) { const line = lines[lineNumber]; - const orbs = line.match(/^\s*orbs:\s*$/); + const orbs = /^\s*orbs:\s*$/.exec(line); if (orbs) { logger.trace(`Matched orbs on line ${lineNumber}`); let foundOrb: boolean; @@ -18,7 +18,7 @@ export function extractPackageFile(content: string): PackageFile | null { foundOrb = false; const orbLine = lines[lineNumber + 1]; logger.trace(`orbLine: "${orbLine}"`); - const orbMatch = orbLine.match(/^\s+([^:]+):\s(.+)$/); + const orbMatch = /^\s+([^:]+):\s(.+)$/.exec(orbLine); if (orbMatch) { logger.trace('orbMatch'); foundOrb = true; @@ -40,7 +40,7 @@ export function extractPackageFile(content: string): PackageFile | null { } } while (foundOrb); } - const match = line.match(/^\s*- image:\s*'?"?([^\s'"]+)'?"?\s*$/); + const match = /^\s*- image:\s*'?"?([^\s'"]+)'?"?\s*$/.exec(line); if (match) { const currentFrom = match[1]; const dep = getDep(currentFrom); diff --git a/lib/manager/circleci/update.ts b/lib/manager/circleci/update.ts index b54eae70bbb9420f820b8bbb45b46bdfb34d2c38..5732081cfcfcf34710b11b952383c18cd28cccf2 100644 --- a/lib/manager/circleci/update.ts +++ b/lib/manager/circleci/update.ts @@ -13,7 +13,7 @@ export function updateDependency( const newFrom = getNewFrom(upgrade); logger.debug(`circleci.updateDependency(): ${newFrom}`); const imageLine = new RegExp(/^(\s*- image:\s*'?"?)[^\s'"]+('?"?\s*)$/); - if (!lineToChange.match(imageLine)) { + if (!imageLine.test(lineToChange)) { logger.debug('No image line found'); return null; } @@ -27,7 +27,7 @@ export function updateDependency( } if (upgrade.depType === 'orb') { const orbLine = new RegExp(`^(\\s+${upgrade.depName}:\\s[^@]+@).+$`); - if (!lineToChange.match(orbLine)) { + if (!orbLine.test(lineToChange)) { logger.debug('No image line found'); return null; } diff --git a/lib/manager/composer/artifacts.ts b/lib/manager/composer/artifacts.ts index e59b18fd6105227a4920ed430abe64031ccf0bc9..3080dfc356ed67fa05e5a3be3fcb51ecba9ed28a 100644 --- a/lib/manager/composer/artifacts.ts +++ b/lib/manager/composer/artifacts.ts @@ -62,7 +62,7 @@ export async function updateArtifacts({ try { // istanbul ignore else if (is.array(config.registryUrls)) { - for (const regUrl of config.registryUrls as string[]) { + for (const regUrl of config.registryUrls) { if (regUrl) { const { host } = URL.parse(regUrl); const hostRule = hostRules.find({ diff --git a/lib/manager/deps-edn/extract.ts b/lib/manager/deps-edn/extract.ts index 184fa613ed2fd2adcd0fbfab80321c15f6427ea3..1a4303aa54ea466e2331e1e5b99782f0077129fb 100644 --- a/lib/manager/deps-edn/extract.ts +++ b/lib/manager/deps-edn/extract.ts @@ -8,7 +8,7 @@ export function extractPackageFile(content: string): PackageFile { const regex = /([^{\s,]*)[\s,]*{[\s,]*:mvn\/version[\s,]+"([^"]+)"[\s,]*}/; let rest = content; - let match = rest.match(regex); + let match = regex.exec(rest); let offset = 0; while (match) { const [wholeSubstr, depName, currentValue] = match; @@ -17,7 +17,7 @@ export function extractPackageFile(content: string): PackageFile { offset += match.index + wholeSubstr.length; rest = content.slice(offset); - match = rest.match(regex); + match = regex.exec(rest); deps.push({ datasource: DATASOURCE_MAVEN, diff --git a/lib/manager/docker-compose/update.ts b/lib/manager/docker-compose/update.ts index 4f511553abbcea1c994d101e913c69fbfb54f14b..9a12dc4076e64e07ba9a59b04c24c0f2f31bf664 100644 --- a/lib/manager/docker-compose/update.ts +++ b/lib/manager/docker-compose/update.ts @@ -11,8 +11,8 @@ export function updateDependency( logger.debug(`docker-compose.updateDependency(): ${newFrom}`); const lines = fileContent.split('\n'); const lineToChange = lines[upgrade.managerData.lineNumber]; - const imageLine = new RegExp(/^(\s*image:\s*'?"?)[^\s'"]+('?"?\s*)/); - if (!lineToChange.match(imageLine)) { + const imageLine = /^(\s*image:\s*'?"?)[^\s'"]+('?"?\s*)/; + if (!imageLine.test(lineToChange)) { logger.debug('No image line found'); return null; } diff --git a/lib/manager/dockerfile/extract.ts b/lib/manager/dockerfile/extract.ts index 99458a695b02cbd2fc2ed698c7b81c707b07060b..5e659aa14240968f10765fe6eab1863572bb53be 100644 --- a/lib/manager/dockerfile/extract.ts +++ b/lib/manager/dockerfile/extract.ts @@ -47,7 +47,7 @@ export function extractPackageFile(content: string): PackageFile | null { const stageNames: string[] = []; let lineNumber = 0; for (const fromLine of content.split('\n')) { - const fromMatch = fromLine.match(/^FROM /i); + const fromMatch = /^FROM /i.test(fromLine); if (fromMatch) { logger.trace({ lineNumber, fromLine }, 'FROM line'); const [fromPrefix, currentFrom, ...fromRest] = fromLine.match(/\S+/g); @@ -79,9 +79,9 @@ export function extractPackageFile(content: string): PackageFile | null { } } - const copyFromMatch = fromLine.match(/^(COPY --from=)([^\s]+)\s+(.*)$/i); + const copyFromMatch = /^(COPY --from=)([^\s]+)\s+(.*)$/i.exec(fromLine); if (copyFromMatch) { - const [fromPrefix, currentFrom, fromSuffix] = copyFromMatch.slice(1); + const [, fromPrefix, currentFrom, fromSuffix] = copyFromMatch; logger.trace({ lineNumber, fromLine }, 'COPY --from line'); if (stageNames.includes(currentFrom)) { logger.debug({ currentFrom }, 'Skipping alias COPY --from'); diff --git a/lib/manager/dockerfile/update.ts b/lib/manager/dockerfile/update.ts index cfab1b29ec0f725bc1f0ba868d7a4b68f7d42dc1..5f034bd5f8b08a666d4bd79a5322032802745041 100644 --- a/lib/manager/dockerfile/update.ts +++ b/lib/manager/dockerfile/update.ts @@ -24,8 +24,8 @@ export function updateDependency( logger.debug(`docker.updateDependency(): ${newFrom}`); const lines = fileContent.split('\n'); const lineToChange = lines[lineNumber]; - const imageLine = new RegExp(/^(FROM |COPY --from=)/i); - if (!lineToChange.match(imageLine)) { + const imageLine = /^(FROM |COPY --from=)/i; + if (!imageLine.test(lineToChange)) { logger.debug('No image line found'); return null; } diff --git a/lib/manager/droneci/extract.ts b/lib/manager/droneci/extract.ts index 775917e65d454c3884c974cf190bb5f7c77b9b0c..9c65241b3ecd2089e51195a51f8f0ba6ed85532d 100644 --- a/lib/manager/droneci/extract.ts +++ b/lib/manager/droneci/extract.ts @@ -8,7 +8,7 @@ export function extractPackageFile(content: string): PackageFile | null { const lines = content.split('\n'); for (let lineNumber = 0; lineNumber < lines.length; lineNumber += 1) { const line = lines[lineNumber]; - const match = line.match(/^\s* image:\s*'?"?([^\s'"]+)'?"?\s*$/); + const match = /^\s* image:\s*'?"?([^\s'"]+)'?"?\s*$/.exec(line); if (match) { const currentFrom = match[1]; const dep = getDep(currentFrom); diff --git a/lib/manager/droneci/update.ts b/lib/manager/droneci/update.ts index 78e8633c1b5982b478f7bd22cc1a0f24b0dedab5..d2f38eec6980f51f8e8c5526f1d873c1d9db4e53 100644 --- a/lib/manager/droneci/update.ts +++ b/lib/manager/droneci/update.ts @@ -12,8 +12,8 @@ export function updateDependency( if (upgrade.depType === 'docker') { const newFrom = getNewFrom(upgrade); logger.debug(`droneci.updateDependency(): ${newFrom}`); - const imageLine = new RegExp(/^(\s* image:\s*'?"?)[^\s'"]+('?"?\s*)$/); - if (!lineToChange.match(imageLine)) { + const imageLine = /^(\s* image:\s*'?"?)[^\s'"]+('?"?\s*)$/; + if (!imageLine.test(lineToChange)) { logger.debug('No image line found'); return null; } diff --git a/lib/manager/github-actions/extract.ts b/lib/manager/github-actions/extract.ts index 0740cf86ad24545335c688d0b590dfdd9ea5ebb1..ef78d9e803d65e63352b14cd2387daf5d1d80cfd 100644 --- a/lib/manager/github-actions/extract.ts +++ b/lib/manager/github-actions/extract.ts @@ -11,10 +11,10 @@ export function extractPackageFile(content: string): PackageFile | null { // old github actions syntax will be deprecated on September 30, 2019 // after that, the first line can be removed const match = - line.match(/^\s+uses = "docker:\/\/([^"]+)"\s*$/) || - line.match(/^\s+uses: docker:\/\/([^"]+)\s*$/); + /^\s+uses = "docker:\/\/([^"]+)"\s*$/.exec(line) || + /^\s+uses: docker:\/\/([^"]+)\s*$/.exec(line); if (match) { - const currentFrom = match[1]; + const [, currentFrom] = match; const dep = getDep(currentFrom); logger.debug( { diff --git a/lib/manager/github-actions/update.ts b/lib/manager/github-actions/update.ts index 3e66ffc091ad8a865640e619a6bc6cf1feaa24d5..449a403cda39d5bd322a95971acaff65ad6961c0 100644 --- a/lib/manager/github-actions/update.ts +++ b/lib/manager/github-actions/update.ts @@ -11,8 +11,8 @@ export function updateDependency( logger.debug(`github-actions.updateDependency(): ${newFrom}`); const lines = fileContent.split('\n'); const lineToChange = lines[upgrade.managerData.lineNumber]; - const imageLine = new RegExp(/^(.+docker:\/\/)[^"]+("\s*)?$/); - if (!lineToChange.match(imageLine)) { + const imageLine = /^(.+docker:\/\/)[^"]+("\s*)?$/; + if (!imageLine.test(lineToChange)) { logger.debug('No image line found'); return null; } diff --git a/lib/manager/gitlabci/extract.ts b/lib/manager/gitlabci/extract.ts index db5e95131c3dec664813319ac9fa7e13e3b3759a..e938a2e996d691aa05bb816dd631f4970d1d29da 100644 --- a/lib/manager/gitlabci/extract.ts +++ b/lib/manager/gitlabci/extract.ts @@ -7,7 +7,8 @@ function skipCommentLines( lineNumber: number ): { lineNumber: number; line: string } { let ln = lineNumber; - while (ln < lines.length - 1 && lines[ln].match(/^\s*#/)) { + const commentsRe = /^\s*#/; + while (ln < lines.length - 1 && commentsRe.test(lines[ln])) { ln += 1; } return { line: lines[ln], lineNumber: ln }; @@ -19,13 +20,13 @@ export function extractPackageFile(content: string): PackageFile | null { const lines = content.split('\n'); for (let lineNumber = 0; lineNumber < lines.length; lineNumber += 1) { const line = lines[lineNumber]; - const imageMatch = line.match(/^\s*image:\s*'?"?([^\s]+|)'?"?\s*$/); + const imageMatch = /^\s*image:\s*'?"?([^\s]+|)'?"?\s*$/.exec(line); if (imageMatch) { switch (imageMatch[1]) { case '': { const imageNameLine = skipCommentLines(lines, lineNumber + 1); - const imageNameMatch = imageNameLine.line.match( - /^\s*name:\s*'?"?([^\s]+|)'?"?\s*$/ + const imageNameMatch = /^\s*name:\s*'?"?([^\s]+|)'?"?\s*$/.exec( + imageNameLine.line ); if (imageNameMatch) { @@ -49,7 +50,7 @@ export function extractPackageFile(content: string): PackageFile | null { } } } - const services = line.match(/^\s*services:\s*$/); + const services = /^\s*services:\s*$/.test(line); if (services) { logger.trace(`Matched services on line ${lineNumber}`); let foundImage: boolean; @@ -57,8 +58,8 @@ export function extractPackageFile(content: string): PackageFile | null { foundImage = false; const serviceImageLine = skipCommentLines(lines, lineNumber + 1); logger.trace(`serviceImageLine: "${serviceImageLine.line}"`); - const serviceImageMatch = serviceImageLine.line.match( - /^\s*-\s*'?"?([^\s'"]+)'?"?\s*$/ + const serviceImageMatch = /^\s*-\s*'?"?([^\s'"]+)'?"?\s*$/.exec( + serviceImageLine.line ); if (serviceImageMatch) { logger.trace('serviceImageMatch'); diff --git a/lib/manager/gitlabci/update.ts b/lib/manager/gitlabci/update.ts index ec10db76b9f512f12519cf69cd6b80e01823f88f..17d6a57163f3d1c5ae37696302f9538cbf75b703 100644 --- a/lib/manager/gitlabci/update.ts +++ b/lib/manager/gitlabci/update.ts @@ -11,10 +11,8 @@ export function updateDependency( const lines = currentFileContent.split('\n'); const lineToChange = lines[upgrade.managerData.lineNumber]; if (['image', 'image-name'].includes(upgrade.depType)) { - const imageLine = new RegExp( - /^(\s*(?:image|name):\s*'?"?)[^\s'"]+('?"?\s*)$/ - ); - if (!lineToChange.match(imageLine)) { + const imageLine = /^(\s*(?:image|name):\s*'?"?)[^\s'"]+('?"?\s*)$/; + if (!imageLine.test(lineToChange)) { logger.debug('No image line found'); return null; } @@ -26,8 +24,8 @@ export function updateDependency( lines[upgrade.managerData.lineNumber] = newLine; return lines.join('\n'); } - const serviceLine = new RegExp(/^(\s*-\s*'?"?)[^\s'"]+('?"?\s*)$/); - if (!lineToChange.match(serviceLine)) { + const serviceLine = /^(\s*-\s*'?"?)[^\s'"]+('?"?\s*)$/; + if (!serviceLine.test(lineToChange)) { logger.debug('No image line found'); return null; } diff --git a/lib/manager/gomod/extract.ts b/lib/manager/gomod/extract.ts index 53320dfd907406ba1c7d861e52c2b4b737eb7f22..f62326733c215fe82944e56ebfb22a856e613085 100644 --- a/lib/manager/gomod/extract.ts +++ b/lib/manager/gomod/extract.ts @@ -32,7 +32,7 @@ function getDep( } dep.datasource = DATASOURCE_GO; } - const digestMatch = currentValue.match(/v0\.0.0-\d{14}-([a-f0-9]{12})/); + const digestMatch = /v0\.0.0-\d{14}-([a-f0-9]{12})/.exec(currentValue); if (digestMatch) { [, dep.currentDigest] = digestMatch; dep.digestOneAndOnly = true; @@ -47,14 +47,14 @@ export function extractPackageFile(content: string): PackageFile | null { const lines = content.split('\n'); for (let lineNumber = 0; lineNumber < lines.length; lineNumber += 1) { let line = lines[lineNumber]; - const replaceMatch = line.match( - /^replace\s+[^\s]+[\s]+[=][>]\s+([^\s]+)\s+([^\s]+)/ + const replaceMatch = /^replace\s+[^\s]+[\s]+[=][>]\s+([^\s]+)\s+([^\s]+)/.exec( + line ); if (replaceMatch) { const dep = getDep(lineNumber, replaceMatch, 'replace'); deps.push(dep); } - const requireMatch = line.match(/^require\s+([^\s]+)\s+([^\s]+)/); + const requireMatch = /^require\s+([^\s]+)\s+([^\s]+)/.exec(line); if (requireMatch && !line.endsWith('// indirect')) { logger.trace({ lineNumber }, `require line: "${line}"`); const dep = getDep(lineNumber, requireMatch, 'require'); @@ -65,7 +65,7 @@ export function extractPackageFile(content: string): PackageFile | null { do { lineNumber += 1; line = lines[lineNumber]; - const multiMatch = line.match(/^\s+([^\s]+)\s+([^\s]+)/); + const multiMatch = /^\s+([^\s]+)\s+([^\s]+)/.exec(line); logger.trace(`reqLine: "${line}"`); if (multiMatch && !line.endsWith('// indirect')) { logger.trace({ lineNumber }, `require line: "${line}"`); diff --git a/lib/manager/gomod/update.ts b/lib/manager/gomod/update.ts index 14825d83e303d3b7db2f0ad3eef66850fef6134c..32f32d1a69d1032eb156997272f9e77b84dc2198 100644 --- a/lib/manager/gomod/update.ts +++ b/lib/manager/gomod/update.ts @@ -39,7 +39,7 @@ export function updateDependency( updateLineExp = new RegExp(/^(require\s+[^\s]+)(\s+)([^\s]+)/); } } - if (!lineToChange.match(updateLineExp)) { + if (updateLineExp && !updateLineExp.test(lineToChange)) { logger.debug('No image line found'); return null; } @@ -79,7 +79,7 @@ export function updateDependency( ) { // If package has no version, pin to latest one. newLine = newLine.replace(depName, depName + '/v' + upgrade.newMajor); - if (upgrade.currentValue.match(/^v(0|1)\./)) { + if (/^v(0|1)\./.test(upgrade.currentValue)) { // Add version newLine = newLine.replace( updateLineExp, diff --git a/lib/manager/gradle-wrapper/extract.ts b/lib/manager/gradle-wrapper/extract.ts index 80745cee8faa15c3c575282968b2f70d19b46692..fc8843d115d57569bc59159bdb05e7207bb26eac 100644 --- a/lib/manager/gradle-wrapper/extract.ts +++ b/lib/manager/gradle-wrapper/extract.ts @@ -10,8 +10,8 @@ export function extractPackageFile(fileContent: string): PackageFile | null { let lineNumber = 0; for (const line of lines) { - const match = line.match( - /^distributionUrl=.*-((\d|\.)+)-(bin|all)\.zip\s*$/ + const match = /^distributionUrl=.*-((\d|\.)+)-(bin|all)\.zip\s*$/.exec( + line ); if (match) { const dependency: PackageDependency = { @@ -25,7 +25,7 @@ export function extractPackageFile(fileContent: string): PackageFile | null { let shaLineNumber = 0; for (const shaLine of lines) { - const shaMatch = shaLine.match(/^distributionSha256Sum=((\w){64}).*$/); + const shaMatch = /^distributionSha256Sum=((\w){64}).*$/.test(shaLine); if (shaMatch) { dependency.managerData.checksumLineNumber = shaLineNumber; break; diff --git a/lib/manager/gradle/build-gradle.ts b/lib/manager/gradle/build-gradle.ts index 787a6977f5f548201aafb2ba29acda09a53a7341..def16a483b62e3f8eda63db0d798be5d83f3a713 100644 --- a/lib/manager/gradle/build-gradle.ts +++ b/lib/manager/gradle/build-gradle.ts @@ -140,7 +140,7 @@ export function collectVersionVariables( ]; for (const regex of regexes) { - const match = buildGradleContent.match(regex); + const match = regex.exec(buildGradleContent); if (match) { variables[`${dependency.group}:${dependency.name}`] = match[1]; } @@ -165,7 +165,7 @@ function updateVersionLiterals( ...moduleKotlinNamedArgumentVersionFormatMatch(dependency), ]; for (const regex of regexes) { - if (buildGradleContent.match(regex)) { + if (regex.test(buildGradleContent)) { return buildGradleContent.replace(regex, `$1${newVersion}$2`); } } @@ -184,7 +184,7 @@ function updateLocalVariables( ...moduleKotlinNamedArgumentVariableVersionFormatMatch(dependency), ]; for (const regex of regexes) { - const match = buildGradleContent.match(regex); + const match = regex.exec(buildGradleContent); if (match) { return buildGradleContent.replace( variableDefinitionFormatMatch(match[1]), @@ -203,7 +203,7 @@ function updateGlobalVariables( const variable = variables[`${dependency.group}:${dependency.name}`]; if (variable) { const regex = variableDefinitionFormatMatch(variable); - const match = buildGradleContent.match(regex); + const match = regex.exec(buildGradleContent); if (match) { return buildGradleContent.replace( variableDefinitionFormatMatch(variable), @@ -224,7 +224,7 @@ function updateKotlinVariablesByExtra( const regex = new RegExp( `(val ${variable} by extra(?: {|\\()\\s*")(.*)("\\s*[})])` ); - const match = buildGradleContent.match(regex); + const match = regex.exec(buildGradleContent); if (match) { return buildGradleContent.replace(regex, `$1${newVersion}$3`); } @@ -240,7 +240,7 @@ function updatePropertyFileGlobalVariables( const variable = variables[`${dependency.group}:${dependency.name}`]; if (variable) { const regex = new RegExp(`(${variable}\\s*=\\s*)(.*)`); - const match = buildGradleContent.match(regex); + const match = regex.exec(buildGradleContent); if (match) { return buildGradleContent.replace(regex, `$1${newVersion}`); } @@ -262,9 +262,7 @@ export function updateGradleVersion( updateKotlinVariablesByExtra, ]; - // eslint-disable-next-line guard-for-in - for (const updateFunctionIndex in updateFunctions) { - const updateFunction = updateFunctions[updateFunctionIndex]; + for (const updateFunction of updateFunctions) { const gradleContentUpdated = updateFunction( dependency, buildGradleContent, diff --git a/lib/manager/gradle/gradle-updates-report.ts b/lib/manager/gradle/gradle-updates-report.ts index ebf1dd81a8976b91da3b4c5cdd3641cdf119f5c8..b9615d0b3f4fd9d78fbbdfd02ba4b1561bc2b657 100644 --- a/lib/manager/gradle/gradle-updates-report.ts +++ b/lib/manager/gradle/gradle-updates-report.ts @@ -117,7 +117,7 @@ function combineReposOnDuplicatedDependencies( accumulator.push(currentValue); } else { const nonExistingRepos = currentValue.repos.filter( - repo => existingDependency.repos.indexOf(repo) === -1 + repo => !existingDependency.repos.includes(repo) ); existingDependency.repos.push(...nonExistingRepos); } diff --git a/lib/manager/helmfile/extract.spec.ts b/lib/manager/helmfile/extract.spec.ts index d25d072ee1b73fa8d5e555810b24cbea519bae8d..43352e580a09f35bf4d01f0f8018b2764f22ce13 100644 --- a/lib/manager/helmfile/extract.spec.ts +++ b/lib/manager/helmfile/extract.spec.ts @@ -6,14 +6,14 @@ describe('lib/manager/helmfile/extract', () => { jest.resetAllMocks(); }); - it('returns null if no releases', async () => { + it('returns null if no releases', () => { const content = ` repositories: - name: kiwigrid url: https://kiwigrid.github.io `; const fileName = 'helmfile.yaml'; - const result = await extractPackageFile(content, fileName, { + const result = extractPackageFile(content, fileName, { aliases: { stable: 'https://kubernetes-charts.storage.googleapis.com/', }, @@ -21,7 +21,7 @@ describe('lib/manager/helmfile/extract', () => { expect(result).toBeNull(); }); - it('do not crash on invalid helmfile.yaml', async () => { + it('do not crash on invalid helmfile.yaml', () => { const content = ` repositories: - name: kiwigrid @@ -30,7 +30,7 @@ describe('lib/manager/helmfile/extract', () => { releases: [ `; const fileName = 'helmfile.yaml'; - const result = await extractPackageFile(content, fileName, { + const result = extractPackageFile(content, fileName, { aliases: { stable: 'https://kubernetes-charts.storage.googleapis.com/', }, @@ -38,7 +38,7 @@ describe('lib/manager/helmfile/extract', () => { expect(result).toBeNull(); }); - it('skip if repository details are not specified', async () => { + it('skip if repository details are not specified', () => { const content = ` repositories: - name: kiwigrid @@ -49,7 +49,7 @@ describe('lib/manager/helmfile/extract', () => { chart: experimental/example `; const fileName = 'helmfile.yaml'; - const result = await extractPackageFile(content, fileName, { + const result = extractPackageFile(content, fileName, { aliases: { stable: 'https://kubernetes-charts.storage.googleapis.com/', }, @@ -59,7 +59,7 @@ describe('lib/manager/helmfile/extract', () => { expect(result.deps.every(dep => dep.skipReason)); }); - it('skip templetized release with invalid characters', async () => { + it('skip templetized release with invalid characters', () => { const content = ` repositories: - name: kiwigrid @@ -73,7 +73,7 @@ describe('lib/manager/helmfile/extract', () => { chart: stable/example `; const fileName = 'helmfile.yaml'; - const result = await extractPackageFile(content, fileName, { + const result = extractPackageFile(content, fileName, { aliases: { stable: 'https://kubernetes-charts.storage.googleapis.com/', }, @@ -82,7 +82,7 @@ describe('lib/manager/helmfile/extract', () => { expect(result).toMatchSnapshot(); }); - it('skip local charts', async () => { + it('skip local charts', () => { const content = ` repositories: - name: kiwigrid @@ -93,7 +93,7 @@ describe('lib/manager/helmfile/extract', () => { chart: ./charts/example `; const fileName = 'helmfile.yaml'; - const result = await extractPackageFile(content, fileName, { + const result = extractPackageFile(content, fileName, { aliases: { stable: 'https://kubernetes-charts.storage.googleapis.com/', }, @@ -103,7 +103,7 @@ describe('lib/manager/helmfile/extract', () => { expect(result.deps.every(dep => dep.skipReason)); }); - it('skip chart with unknown repository', async () => { + it('skip chart with unknown repository', () => { const content = ` repositories: - name: kiwigrid @@ -114,7 +114,7 @@ describe('lib/manager/helmfile/extract', () => { chart: example `; const fileName = 'helmfile.yaml'; - const result = await extractPackageFile(content, fileName, { + const result = extractPackageFile(content, fileName, { aliases: { stable: 'https://kubernetes-charts.storage.googleapis.com/', }, @@ -124,7 +124,7 @@ describe('lib/manager/helmfile/extract', () => { expect(result.deps.every(dep => dep.skipReason)); }); - it('skip chart with special character in the name', async () => { + it('skip chart with special character in the name', () => { const content = ` repositories: - name: kiwigrid @@ -138,7 +138,7 @@ describe('lib/manager/helmfile/extract', () => { chart: kiwigrid/example?example `; const fileName = 'helmfile.yaml'; - const result = await extractPackageFile(content, fileName, { + const result = extractPackageFile(content, fileName, { aliases: { stable: 'https://kubernetes-charts.storage.googleapis.com/', }, @@ -148,7 +148,7 @@ describe('lib/manager/helmfile/extract', () => { expect(result.deps.every(dep => dep.skipReason)); }); - it('skip chart that does not have specified version', async () => { + it('skip chart that does not have specified version', () => { const content = ` repositories: - name: kiwigrid @@ -158,7 +158,7 @@ describe('lib/manager/helmfile/extract', () => { chart: stable/example `; const fileName = 'helmfile.yaml'; - const result = await extractPackageFile(content, fileName, { + const result = extractPackageFile(content, fileName, { aliases: { stable: 'https://kubernetes-charts.storage.googleapis.com/', }, diff --git a/lib/manager/helmfile/extract.ts b/lib/manager/helmfile/extract.ts index efc02a4a2e95ea83232bd66c16e242dd0256ee12..586773b6fecd529ee377bf60bb88dad768cf4f24 100644 --- a/lib/manager/helmfile/extract.ts +++ b/lib/manager/helmfile/extract.ts @@ -5,7 +5,7 @@ import { logger } from '../../logger'; import { PackageFile, PackageDependency, ExtractConfig } from '../common'; const isValidChartName = (name: string): boolean => { - return name.match(/[!@#$%^&*(),.?":{}/|<>A-Z]/) === null; + return !/[!@#$%^&*(),.?":{}/|<>A-Z]/.test(name); }; export function extractPackageFile( diff --git a/lib/manager/kubernetes/extract.ts b/lib/manager/kubernetes/extract.ts index 9007fa323ecb639e3e3717b44ff0122ca27a2055..8e84bdf4eacde91fbeee613b2bf8bdce6e1f401d 100644 --- a/lib/manager/kubernetes/extract.ts +++ b/lib/manager/kubernetes/extract.ts @@ -8,13 +8,13 @@ export function extractPackageFile(content: string): PackageFile | null { let lineNumber = 0; const isKubernetesManifest = - content.match(/\s*apiVersion\s*:/) && content.match(/\s*kind\s*:/); + /\s*apiVersion\s*:/.test(content) && /\s*kind\s*:/.test(content); if (!isKubernetesManifest) { return null; } for (const line of content.split('\n')) { - const match = line.match(/^\s*-?\s*image:\s*'?"?([^\s'"]+)'?"?\s*$/); + const match = /^\s*-?\s*image:\s*'?"?([^\s'"]+)'?"?\s*$/.exec(line); if (match) { const currentFrom = match[1]; const dep = getDep(currentFrom); diff --git a/lib/manager/kubernetes/update.ts b/lib/manager/kubernetes/update.ts index 0c16c1a23fe27c7148d124a1cdd11aa39fd5207d..a471bd4dcc5001797a549b266e23691a797dc77c 100644 --- a/lib/manager/kubernetes/update.ts +++ b/lib/manager/kubernetes/update.ts @@ -11,8 +11,8 @@ export function updateDependency( logger.debug(`kubernetes.updateDependency(): ${newFrom}`); const lines = fileContent.split('\n'); const lineToChange = lines[upgrade.managerData.lineNumber]; - const imageLine = new RegExp(/^(\s*-?\s*image:\s*'?"?)[^\s'"]+('?"?\s*)$/); - if (!lineToChange.match(imageLine)) { + const imageLine = /^(\s*-?\s*image:\s*'?"?)[^\s'"]+('?"?\s*)$/; + if (!imageLine.test(lineToChange)) { logger.debug('No image line found'); return null; } diff --git a/lib/manager/leiningen/extract.ts b/lib/manager/leiningen/extract.ts index f8df2168af2cbf6ea65a46f0fefac227d5a40495..a815f25bace2f480fc04d986ecb31a51c0565c97 100644 --- a/lib/manager/leiningen/extract.ts +++ b/lib/manager/leiningen/extract.ts @@ -15,7 +15,7 @@ export function trimAtKey(str: string, kwName: string): string | null { } export function expandDepName(name: string): string { - return name.indexOf('/') === -1 ? `${name}:${name}` : name.replace('/', ':'); + return !name.includes('/') ? `${name}:${name}` : name.replace('/', ':'); } export interface ExtractContext { @@ -28,7 +28,7 @@ export function extractFromVectors( offset = 0, ctx: ExtractContext = {} ): PackageDependency[] { - if (str.indexOf('[') !== 0) return []; + if (!str.startsWith('[')) return []; let balance = 0; const result: PackageDependency[] = []; let idx = 0; diff --git a/lib/manager/maven/extract.ts b/lib/manager/maven/extract.ts index e0c4284adadbc6b333cc09ced6ff291407c56d48..d89702f123dcdeaa19ee15d8bb66f68cace32aff 100644 --- a/lib/manager/maven/extract.ts +++ b/lib/manager/maven/extract.ts @@ -39,7 +39,7 @@ interface MavenProp { } function depFromNode(node: XmlElement): PackageDependency | null { - if (!node.valueWithPath) return null; + if (!('valueWithPath' in node)) return null; let groupId = node.valueWithPath('groupId'); const artifactId = node.valueWithPath('artifactId'); const currentValue = node.valueWithPath('version'); @@ -70,7 +70,7 @@ function deepExtract( result: PackageDependency[] = [], isRoot = true ): PackageDependency[] { - const dep = depFromNode(node as XmlElement); + const dep = depFromNode(node); if (dep && !isRoot) { result.push(dep); } @@ -141,7 +141,7 @@ function resolveParentFile(packageFile: string, parentPath: string): string { let parentFile = 'pom.xml'; let parentDir = parentPath; const parentBasename = basename(parentPath); - if (parentBasename === 'pom.xml' || /\.pom\.xml$/.test(parentBasename)) { + if (parentBasename === 'pom.xml' || parentBasename.endsWith('.pom.xml')) { parentFile = parentBasename; parentDir = dirname(parentPath); } diff --git a/lib/manager/meteor/extract.ts b/lib/manager/meteor/extract.ts index 4d4730b805390549fd602b6fe097fdd3bc032adf..227f65d2f56d958c015b7f883a45b4da1356edc2 100644 --- a/lib/manager/meteor/extract.ts +++ b/lib/manager/meteor/extract.ts @@ -4,7 +4,7 @@ import { DATASOURCE_NPM } from '../../constants/data-binary-source'; export function extractPackageFile(content: string): PackageFile | null { let deps: PackageDependency[] = []; - const npmDepends = content.match(/\nNpm\.depends\({([\s\S]*?)}\);/); + const npmDepends = /\nNpm\.depends\({([\s\S]*?)}\);/.exec(content); if (!npmDepends) { return null; } diff --git a/lib/manager/npm/extract/index.ts b/lib/manager/npm/extract/index.ts index 449dc6f03ad8afd8199b75530db4d5679aaaada2..be005fd963f160a7b16f8a91f84b6c2ff54aa878 100644 --- a/lib/manager/npm/extract/index.ts +++ b/lib/manager/npm/extract/index.ts @@ -234,8 +234,8 @@ export async function extractPackageFile( const [githubOwner, githubRepo] = githubRepoSplit; const githubValidRegex = /^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}$/; if ( - !githubOwner.match(githubValidRegex) || - !githubRepo.match(githubValidRegex) + !githubValidRegex.test(githubOwner) || + !githubValidRegex.test(githubRepo) ) { dep.skipReason = 'unknown-version'; return dep; @@ -247,8 +247,8 @@ export async function extractPackageFile( dep.lookupName = githubOwnerRepo; dep.pinDigests = false; } else if ( - depRefPart.match(/^[0-9a-f]{7}$/) || - depRefPart.match(/^[0-9a-f]{40}$/) + /^[0-9a-f]{7}$/.test(depRefPart) || + /^[0-9a-f]{40}$/.test(depRefPart) ) { dep.currentRawValue = dep.currentValue; dep.currentValue = null; diff --git a/lib/manager/npm/extract/monorepo.spec.ts b/lib/manager/npm/extract/monorepo.spec.ts index 0ba304d20c556bd3d064e8500819169d0a669524..d070a224874a96c17344e41442240c3ddf09e506 100644 --- a/lib/manager/npm/extract/monorepo.spec.ts +++ b/lib/manager/npm/extract/monorepo.spec.ts @@ -2,7 +2,7 @@ import { detectMonorepos } from './monorepo'; describe('manager/npm/extract', () => { describe('.extractPackageFile()', () => { - it('uses lerna package settings', async () => { + it('uses lerna package settings', () => { const packageFiles = [ { packageFile: 'package.json', @@ -18,12 +18,12 @@ describe('manager/npm/extract', () => { packageJsonName: '@org/b', }, ]; - await detectMonorepos(packageFiles); + detectMonorepos(packageFiles); expect(packageFiles).toMatchSnapshot(); expect(packageFiles[1].lernaDir).toEqual('.'); expect((packageFiles[1] as any).internalPackages).toEqual(['@org/b']); }); - it('uses yarn workspaces package settings', async () => { + it('uses yarn workspaces package settings', () => { const packageFiles = [ { packageFile: 'package.json', @@ -41,12 +41,12 @@ describe('manager/npm/extract', () => { packageJsonName: '@org/b', }, ]; - await detectMonorepos(packageFiles); + detectMonorepos(packageFiles); expect(packageFiles).toMatchSnapshot(); expect(packageFiles[1].lernaDir).toEqual('.'); expect((packageFiles[1] as any).internalPackages).toEqual(['@org/b']); }); - it('uses yarn workspaces package settings', async () => { + it('uses yarn workspaces package settings', () => { const packageFiles = [ { packageFile: 'package.json', @@ -62,7 +62,7 @@ describe('manager/npm/extract', () => { packageJsonName: '@org/b', }, ]; - await detectMonorepos(packageFiles); + detectMonorepos(packageFiles); expect(packageFiles).toMatchSnapshot(); expect((packageFiles[1] as any).internalPackages).toEqual(['@org/b']); }); diff --git a/lib/manager/nuget/extract.ts b/lib/manager/nuget/extract.ts index 61ebcd45c5aa833eda295ca89fa929be51a5774a..2d3dee1841173fd7b4ce3e8a15170fc5c79fcc68 100644 --- a/lib/manager/nuget/extract.ts +++ b/lib/manager/nuget/extract.ts @@ -27,8 +27,8 @@ export function extractPackageFile( * so we don't include it in the extracting regexp */ - const match = line.match( - /<PackageReference.*Include\s*=\s*"([^"]+)".*Version\s*=\s*"(?:[[])?(?:([^"(,[\]]+)\s*(?:,\s*[)\]]|])?)"/ + const match = /<PackageReference.*Include\s*=\s*"([^"]+)".*Version\s*=\s*"(?:[[])?(?:([^"(,[\]]+)\s*(?:,\s*[)\]]|])?)"/.exec( + line ); if (match) { const depName = match[1]; diff --git a/lib/manager/sbt/extract.ts b/lib/manager/sbt/extract.ts index b4a41c3846b0c4433860bca89835dff9398e6673..5c0fc8653eabb8c058087129dac0d1a0417e5a88 100644 --- a/lib/manager/sbt/extract.ts +++ b/lib/manager/sbt/extract.ts @@ -253,7 +253,7 @@ function parseSbtLine( if (dep) deps.push({ datasource: DATASOURCE_SBT, - registryUrls: registryUrls as string[], + registryUrls, ...dep, }); diff --git a/lib/manager/swift/extract.ts b/lib/manager/swift/extract.ts index fb79829fc452ed5a438221f3e2ad65f965392f86..947c979a8f00a148d4623a9aa502523ca21c3493 100644 --- a/lib/manager/swift/extract.ts +++ b/lib/manager/swift/extract.ts @@ -48,7 +48,7 @@ const searchLabels = { exactVersion: EXACT_VERSION, }; -function searchKeysForState(state): string[] { +function searchKeysForState(state): (keyof typeof regExps)[] { switch (state) { case 'dependencies': return [SPACE, COLON, WILDCARD]; @@ -102,7 +102,7 @@ function getMatch(str: string, state: string): MatchResult | null { const key = keys[i]; const regex = regExps[key]; const label = searchLabels[key]; - const match = str.match(regex); + const match = regex.exec(str); if (match) { const idx = match.index; const substr = match[0]; diff --git a/lib/manager/swift/update.ts b/lib/manager/swift/update.ts index b7725ff06bc9485f48cdf7d9346a8611c6e079e8..e6a6e49dbcc1337fbfa809406077311576f2a0b3 100644 --- a/lib/manager/swift/update.ts +++ b/lib/manager/swift/update.ts @@ -13,17 +13,17 @@ export function updateDependency( const oldVal = isVersion(currentValue) ? `"${currentValue}"` : currentValue; let newVal; if (fromParam.test(oldVal)) { - const [, version] = oldVal.match(fromParam); + const [, version] = fromParam.exec(oldVal); newVal = oldVal.replace(version, newValue); } else if (isVersion(newValue)) { newVal = `"${newValue}"`; } else { newVal = newValue; } - if (rightPart.indexOf(oldVal) === 0) { + if (rightPart.startsWith(oldVal)) { return leftPart + rightPart.replace(oldVal, newVal); } - if (rightPart.indexOf(newVal) === 0) { + if (rightPart.startsWith(newVal)) { return fileContent; } return null; diff --git a/lib/manager/terraform/extract.ts b/lib/manager/terraform/extract.ts index 5a655a8c7f491995087c47dc604b7f52eef429c0..4ee1a2097b91a7c2a349cefa9920c3f91a267dc0 100644 --- a/lib/manager/terraform/extract.ts +++ b/lib/manager/terraform/extract.ts @@ -39,8 +39,8 @@ export function extractPackageFile(content: string): PackageFile | null { const lines = content.split('\n'); for (let lineNumber = 0; lineNumber < lines.length; lineNumber += 1) { let line = lines[lineNumber]; - const terraformDependency = line.match( - /^(module|provider)\s+"([^"]+)"\s+{\s*$/ + const terraformDependency = /^(module|provider)\s+"([^"]+)"\s+{\s*$/.exec( + line ); if (terraformDependency) { logger.trace(`Matched ${terraformDependency[1]} on line ${lineNumber}`); @@ -61,7 +61,7 @@ export function extractPackageFile(content: string): PackageFile | null { do { lineNumber += 1; line = lines[lineNumber]; - const kvMatch = line.match(/^\s*([^\s]+)\s+=\s+"([^"]+)"\s*$/); + const kvMatch = /^\s*([^\s]+)\s+=\s+"([^"]+)"\s*$/.exec(line); if (kvMatch) { const [, key, value] = kvMatch; if (key === 'version') { @@ -85,9 +85,9 @@ export function extractPackageFile(content: string): PackageFile | null { dep.managerData.terraformDependencyType === TerraformDependencyTypes.module ) { - const githubRefMatch = - dep.source && - dep.source.match(/github.com(\/|:)([^/]+\/[a-z0-9-]+).*\?ref=(.*)$/); + const githubRefMatch = /github.com(\/|:)([^/]+\/[a-z0-9-]+).*\?ref=(.*)$/.exec( + dep.source + ); /* eslint-disable no-param-reassign */ if (githubRefMatch) { dep.depType = 'github'; diff --git a/lib/manager/terraform/update.ts b/lib/manager/terraform/update.ts index 56edfc743c8ffde58a76e2703971d043a047879d..eae2b8a0db26c6953f58324969a4723ed8b65520 100644 --- a/lib/manager/terraform/update.ts +++ b/lib/manager/terraform/update.ts @@ -16,7 +16,7 @@ export function updateDependency( } newLine = lineToChange.replace(/\?ref=.*"/, `?ref=${upgrade.newValue}"`); } else if (upgrade.depType === 'terraform') { - if (!lineToChange.match(/version\s*=\s*"/)) { + if (!/version\s*=\s*"/.test(lineToChange)) { return null; } newLine = lineToChange.replace( diff --git a/lib/platform/azure/index.ts b/lib/platform/azure/index.ts index 0b5fad00a2e2c6f1c1708adacb81b57d5e9d6d13..bdbbb3c8a0be20b2b5d96d61cdaa5c9448000e36 100644 --- a/lib/platform/azure/index.ts +++ b/lib/platform/azure/index.ts @@ -80,7 +80,7 @@ export async function getRepos(): Promise<string[]> { logger.info('Autodiscovering Azure DevOps repositories'); const azureApiGit = await azureApi.gitApi(); const repos = await azureApiGit.getRepositories(); - return repos.map(repo => `${repo.project!.name}/${repo.name}`); + return repos.map(repo => `${repo.project.name}/${repo.name}`); } async function getBranchCommit(fullBranchName: string): Promise<string> { @@ -89,7 +89,7 @@ async function getBranchCommit(fullBranchName: string): Promise<string> { config.repoId, azureHelper.getBranchNameWithoutRefsheadsPrefix(fullBranchName)! ); - return commit.commit!.commitId; + return commit.commit.commitId; } export async function initRepo({ @@ -105,16 +105,16 @@ export async function initRepo({ const names = azureHelper.getProjectAndRepo(repository); const repo = repos.filter( c => - c.name!.toLowerCase() === names.repo.toLowerCase() && - c.project!.name!.toLowerCase() === names.project.toLowerCase() + c.name.toLowerCase() === names.repo.toLowerCase() && + c.project.name.toLowerCase() === names.project.toLowerCase() )[0]; logger.debug({ repositoryDetails: repo }, 'Repository details'); - config.repoId = repo.id!; - config.project = repo.project!.name; + config.repoId = repo.id; + config.project = repo.project.name; config.owner = '?owner?'; logger.debug(`${repository} owner = ${config.owner}`); // Use default branch as PR target unless later overridden - config.defaultBranch = repo.defaultBranch!.replace('refs/heads/', ''); + config.defaultBranch = repo.defaultBranch.replace('refs/heads/', ''); config.baseBranch = config.defaultBranch; logger.debug(`${repository} default branch = ${config.defaultBranch}`); config.baseCommitSHA = await getBranchCommit(config.baseBranch); @@ -453,16 +453,17 @@ export async function createPr({ pr.pullRequestId! ); } - // TODO: fixme - await labels.forEach(async label => { - await azureApiGit.createPullRequestLabel( - { - name: label, - }, - config.repoId, - pr.pullRequestId! - ); - }); + await Promise.all( + labels.map(label => + azureApiGit.createPullRequestLabel( + { + name: label, + }, + config.repoId, + pr.pullRequestId! + ) + ) + ); pr.branchName = branchName; return azureHelper.getRenovatePRFormat(pr); } @@ -512,7 +513,7 @@ export async function ensureCommentRemoval( let threadIdFound = null; threads.forEach(thread => { - if (thread.comments![0].content!.startsWith(`### ${topic}\n\n`)) { + if (thread.comments[0].content.startsWith(`### ${topic}\n\n`)) { threadIdFound = thread.id; } }); @@ -544,7 +545,7 @@ export function setBranchStatus({ export async function mergePr(pr: number): Promise<void> { logger.info(`mergePr(pr)(${pr}) - Not supported by Azure DevOps (yet!)`); - await null; + await Promise.resolve(); } export function getPrBody(input: string): string { @@ -610,14 +611,14 @@ export async function addReviewers( const azureApiCore = await azureApi.coreApi(); const repos = await azureApiGit.getRepositories(); const repo = repos.filter(c => c.id === config.repoId)[0]; - const teams = await azureApiCore.getTeams(repo!.project!.id!); + const teams = await azureApiCore.getTeams(repo.project.id); const members = await Promise.all( teams.map( async t => /* eslint-disable no-return-await */ await azureApiCore.getTeamMembersWithExtendedProperties( - repo!.project!.id!, - t.id! + repo.project.id, + t.id ) ) ); @@ -627,11 +628,11 @@ export async function addReviewers( listMembers.forEach(m => { reviewers.forEach(r => { if ( - r.toLowerCase() === m.identity!.displayName!.toLowerCase() || - r.toLowerCase() === m.identity!.uniqueName!.toLowerCase() + r.toLowerCase() === m.identity.displayName.toLowerCase() || + r.toLowerCase() === m.identity.uniqueName.toLowerCase() ) { - if (ids.filter(c => c.id === m.identity!.id).length === 0) { - ids.push({ id: m.identity!.id, name: r }); + if (ids.filter(c => c.id === m.identity.id).length === 0) { + ids.push({ id: m.identity.id, name: r }); } } }); @@ -640,7 +641,7 @@ export async function addReviewers( teams.forEach(t => { reviewers.forEach(r => { - if (r.toLowerCase() === t.name!.toLowerCase()) { + if (r.toLowerCase() === t.name.toLowerCase()) { if (ids.filter(c => c.id === t.id).length === 0) { ids.push({ id: t.id, name: r }); } @@ -678,8 +679,8 @@ export function getPrFiles(prNo: number): string[] { return []; } -export function getVulnerabilityAlerts(): VulnerabilityAlert[] { - return []; +export function getVulnerabilityAlerts(): Promise<VulnerabilityAlert[]> { + return Promise.resolve([]); } export function cleanRepo(): void { diff --git a/lib/platform/bitbucket-server/bb-got-wrapper.ts b/lib/platform/bitbucket-server/bb-got-wrapper.ts index 5ab1a8da5465659e28a0e47240fb8f2358e7bd7c..7650abb80735d6ed744d3065077a00bb49593347 100644 --- a/lib/platform/bitbucket-server/bb-got-wrapper.ts +++ b/lib/platform/bitbucket-server/bb-got-wrapper.ts @@ -31,6 +31,7 @@ for (const x of helpers) { get(url, { ...opts, method: x.toUpperCase() }); } +// eslint-disable-next-line @typescript-eslint/unbound-method api.setBaseUrl = (e: string): void => { baseUrl = e; }; diff --git a/lib/platform/bitbucket-server/index.ts b/lib/platform/bitbucket-server/index.ts index 466d0b874d0f8e3a5f1ff82cdadcdaa359e35e58..79e5a98c7f42b8362e7ca64b7cb7b72327864327 100644 --- a/lib/platform/bitbucket-server/index.ts +++ b/lib/platform/bitbucket-server/index.ts @@ -178,7 +178,7 @@ export async function initRepo({ gitPrivateKey, repository, prVersions: new Map<number, number>(), - username: opts!.username, + username: opts.username, } as any; /* istanbul ignore else */ @@ -189,10 +189,10 @@ export async function initRepo({ const { host, pathname } = url.parse(defaults.endpoint!); const gitUrl = GitStorage.getUrl({ - protocol: defaults.endpoint!.split(':')[0] as any, - auth: `${opts!.username}:${opts!.password}`, + protocol: defaults.endpoint!.split(':')[0], + auth: `${opts.username}:${opts.password}`, host: `${host}${pathname}${ - pathname!.endsWith('/') ? '' : /* istanbul ignore next */ '/' + pathname.endsWith('/') ? '' : /* istanbul ignore next */ '/' }scm`, repository, }); @@ -353,7 +353,7 @@ function matchesState(state: string, desiredState: string): boolean { if (desiredState === 'all') { return true; } - if (desiredState[0] === '!') { + if (desiredState.startsWith('!')) { return state !== desiredState.substring(1); } return state === desiredState; @@ -675,27 +675,28 @@ export /* istanbul ignore next */ function ensureIssue( return null; } -export /* istanbul ignore next */ function getIssueList(): Issue[] { +export /* istanbul ignore next */ function getIssueList(): Promise<Issue[]> { logger.debug(`getIssueList()`); // TODO: Needs implementation - return []; + return Promise.resolve([]); } export /* istanbul ignore next */ function ensureIssueClosing( title: string -): void { +): Promise<void> { logger.debug(`ensureIssueClosing(${title})`); // TODO: Needs implementation // This is used by Renovate when creating its own issues, e.g. for deprecated package warnings, config error notifications, or "masterIssue" // BB Server doesnt have issues + return Promise.resolve(); } -// eslint-disable-next-line no-unused-vars -export function addAssignees(iid: number, assignees: string[]): void { +export function addAssignees(iid: number, assignees: string[]): Promise<void> { logger.debug(`addAssignees(${iid}, ${assignees})`); // TODO: Needs implementation // Currently Renovate does "Create PR" and then "Add assignee" as a two-step process, with this being the second step. // BB Server doesnt support assignees + return Promise.resolve(); } export async function addReviewers( @@ -736,11 +737,11 @@ export async function addReviewers( } } -// eslint-disable-next-line no-unused-vars -export function deleteLabel(issueNo: number, label: string): void { +export function deleteLabel(issueNo: number, label: string): Promise<void> { logger.debug(`deleteLabel(${issueNo}, ${label})`); // TODO: Needs implementation // Only used for the "request Renovate to rebase a PR using a label" feature + return Promise.resolve(); } type Comment = { text: string; id: number }; @@ -1083,7 +1084,7 @@ export function getCommitMessages(): Promise<string[]> { return config.storage.getCommitMessages(); } -export function getVulnerabilityAlerts(): VulnerabilityAlert[] { +export function getVulnerabilityAlerts(): Promise<VulnerabilityAlert[]> { logger.debug(`getVulnerabilityAlerts()`); - return []; + return Promise.resolve([]); } diff --git a/lib/platform/bitbucket/index.ts b/lib/platform/bitbucket/index.ts index 1f2cdde9ce7a1436e573d16e6c9960b6126163a7..8216c2e80ef87e43e989dfea63b13b82e94bb551 100644 --- a/lib/platform/bitbucket/index.ts +++ b/lib/platform/bitbucket/index.ts @@ -88,7 +88,7 @@ export async function initRepo({ }); config = { repository, - username: opts!.username, + username: opts.username, bbUseDefaultReviewers: bbUseDefaultReviewers !== false, } as any; let info: utils.RepoInfo; @@ -136,7 +136,7 @@ export async function initRepo({ const url = GitStorage.getUrl({ protocol: 'https', - auth: `${opts!.username}:${opts!.password}`, + auth: `${opts.username}:${opts.password}`, hostname: 'bitbucket.org', repository, }); @@ -213,7 +213,7 @@ function matchesState(state: string, desiredState: string): boolean { if (desiredState === 'all') { return true; } - if (desiredState[0] === '!') { + if (desiredState.startsWith('!')) { return state !== desiredState.substring(1); } return state === desiredState; @@ -829,6 +829,6 @@ export function cleanRepo(): void { config = {} as any; } -export function getVulnerabilityAlerts(): VulnerabilityAlert[] { - return []; +export function getVulnerabilityAlerts(): Promise<VulnerabilityAlert[]> { + return Promise.resolve([]); } diff --git a/lib/platform/git/storage.ts b/lib/platform/git/storage.ts index c6d29fef63de7211d65f3d38e8557446380b05e9..0ff4ee9b4603667c08872718d653dc38ae28f01e 100644 --- a/lib/platform/git/storage.ts +++ b/lib/platform/git/storage.ts @@ -106,14 +106,14 @@ export class Storage { private async _resetToBranch(branchName: string): Promise<void> { logger.debug(`resetToBranch(${branchName})`); - await this._git!.raw(['reset', '--hard']); - await this._git!.checkout(branchName); - await this._git!.raw(['reset', '--hard', 'origin/' + branchName]); - await this._git!.raw(['clean', '-fd']); + await this._git.raw(['reset', '--hard']); + await this._git.checkout(branchName); + await this._git.raw(['reset', '--hard', 'origin/' + branchName]); + await this._git.raw(['clean', '-fd']); } private async _cleanLocalBranches(): Promise<void> { - const existingBranches = (await this._git!.raw(['branch'])) + const existingBranches = (await this._git.raw(['branch'])) .split('\n') .map(branch => branch.trim()) .filter(branch => branch.length) @@ -203,7 +203,7 @@ export class Storage { } } try { - const latestCommitDate = (await this._git!.log({ n: 1 })).latest.date; + const latestCommitDate = (await this._git.log({ n: 1 })).latest.date; logger.debug({ latestCommitDate }, 'latest commit'); } catch (err) /* istanbul ignore next */ { checkForPlatformFailure(err); @@ -217,14 +217,14 @@ export class Storage { logger.debug('Git private key configured, but not being set'); } else { logger.debug('No git private key present - commits will be unsigned'); - await this._git!.raw(['config', 'commit.gpgsign', 'false']); + await this._git.raw(['config', 'commit.gpgsign', 'false']); } if (global.gitAuthor) { logger.info({ gitAuthor: global.gitAuthor }, 'Setting git author'); try { - await this._git!.raw(['config', 'user.name', global.gitAuthor.name]); - await this._git!.raw(['config', 'user.email', global.gitAuthor.email]); + await this._git.raw(['config', 'user.name', global.gitAuthor.name]); + await this._git.raw(['config', 'user.email', global.gitAuthor.email]); } catch (err) /* istanbul ignore next */ { checkForPlatformFailure(err); logger.debug({ err }, 'Error setting git config'); @@ -232,20 +232,20 @@ export class Storage { } } - await determineBaseBranch(this._git!); + await determineBaseBranch(this._git); } // istanbul ignore next getRepoStatus(): Promise<StatusResult> { - return this._git!.status(); + return this._git.status(); } async createBranch(branchName: string, sha: string): Promise<void> { logger.debug(`createBranch(${branchName})`); - await this._git!.reset('hard'); - await this._git!.raw(['clean', '-fd']); - await this._git!.checkout(['-B', branchName, sha]); - await this._git!.push('origin', branchName, { '--force': true }); + await this._git.reset('hard'); + await this._git.raw(['clean', '-fd']); + await this._git.checkout(['-B', branchName, sha]); + await this._git.push('origin', branchName, { '--force': true }); this._config.branchExists[branchName] = true; } @@ -256,13 +256,13 @@ export class Storage { 'Cannot fetch commit for branch that does not exist: ' + branchName ); } - const res = await this._git!.revparse(['origin/' + branchName]); + const res = await this._git.revparse(['origin/' + branchName]); return res.trim(); } async getCommitMessages(): Promise<string[]> { logger.debug('getCommitMessages'); - const res = await this._git!.log({ + const res = await this._git.log({ n: 10, format: { message: '%s' }, }); @@ -279,12 +279,12 @@ export class Storage { try { if (branchName !== 'master') { this._config.baseBranchSha = ( - await this._git!.raw(['rev-parse', 'origin/' + branchName]) + await this._git.raw(['rev-parse', 'origin/' + branchName]) ).trim(); } - await this._git!.checkout([branchName, '-f']); - await this._git!.reset('hard'); - const latestCommitDate = (await this._git!.log({ n: 1 })).latest.date; + await this._git.checkout([branchName, '-f']); + await this._git.reset('hard'); + const latestCommitDate = (await this._git.log({ n: 1 })).latest.date; logger.debug({ branchName, latestCommitDate }, 'latest commit'); } catch (err) /* istanbul ignore next */ { checkForPlatformFailure(err); @@ -309,7 +309,7 @@ export class Storage { this._config.branchPrefix = branchPrefix; const ref = `refs/heads/${branchPrefix}*:refs/remotes/origin/${branchPrefix}*`; try { - await this._git!.fetch(['origin', ref, '--depth=2', '--force']); + await this._git.fetch(['origin', ref, '--depth=2', '--force']); } catch (err) /* istanbul ignore next */ { checkForPlatformFailure(err); throw err; @@ -323,7 +323,7 @@ export class Storage { return []; } const submodules = await this.getSubmodules(); - const files: string = await this._git!.raw([ + const files: string = await this._git.raw([ 'ls-tree', '-r', '--name-only', @@ -343,7 +343,7 @@ export class Storage { async getSubmodules(): Promise<string[]> { return ( - (await this._git!.raw([ + (await this._git.raw([ 'config', '--file', '.gitmodules', @@ -364,20 +364,20 @@ export class Storage { if (!branchName.startsWith(this._config.branchPrefix)) { // fetch the branch only if it's not part of the existing branchPrefix try { - await this._git!.raw([ + await this._git.raw([ 'remote', 'set-branches', '--add', 'origin', branchName, ]); - await this._git!.fetch(['origin', branchName, '--depth=2']); + await this._git.fetch(['origin', branchName, '--depth=2']); } catch (err) { checkForPlatformFailure(err); } } try { - await this._git!.raw(['show-branch', 'origin/' + branchName]); + await this._git.raw(['show-branch', 'origin/' + branchName]); this._config.branchExists[branchName] = true; return true; } catch (err) { @@ -388,7 +388,7 @@ export class Storage { } async getAllRenovateBranches(branchPrefix: string): Promise<string[]> { - const branches = await this._git!.branch(['--remotes', '--verbose']); + const branches = await this._git.branch(['--remotes', '--verbose']); return branches.all .map(localName) .filter(branchName => branchName.startsWith(branchPrefix)); @@ -400,7 +400,7 @@ export class Storage { 'Cannot check staleness for branch that does not exist: ' + branchName ); } - const branches = await this._git!.branch([ + const branches = await this._git.branch([ '--remotes', '--verbose', '--contains', @@ -410,12 +410,12 @@ export class Storage { } private async _deleteLocalBranch(branchName: string): Promise<void> { - await this._git!.branch(['-D', branchName]); + await this._git.branch(['-D', branchName]); } async deleteBranch(branchName: string): Promise<void> { try { - await this._git!.raw(['push', '--delete', 'origin', branchName]); + await this._git.raw(['push', '--delete', 'origin', branchName]); logger.debug({ branchName }, 'Deleted remote branch'); } catch (err) /* istanbul ignore next */ { checkForPlatformFailure(err); @@ -433,17 +433,17 @@ export class Storage { } async mergeBranch(branchName: string): Promise<void> { - await this._git!.reset('hard'); - await this._git!.checkout(['-B', branchName, 'origin/' + branchName]); - await this._git!.checkout(this._config.baseBranch); - await this._git!.merge(['--ff-only', branchName]); - await this._git!.push('origin', this._config.baseBranch); + await this._git.reset('hard'); + await this._git.checkout(['-B', branchName, 'origin/' + branchName]); + await this._git.checkout(this._config.baseBranch); + await this._git.merge(['--ff-only', branchName]); + await this._git.push('origin', this._config.baseBranch); limits.incrementLimit('prCommitsPerRunLimit'); } async getBranchLastCommitTime(branchName: string): Promise<Date> { try { - const time = await this._git!.show([ + const time = await this._git.show([ '-s', '--format=%ai', 'origin/' + branchName, @@ -464,7 +464,7 @@ export class Storage { } } try { - const content = await this._git!.show([ + const content = await this._git.show([ 'origin/' + (branchName || this._config.baseBranch) + ':' + filePath, ]); return content; @@ -476,7 +476,7 @@ export class Storage { async hasDiff(branchName: string): Promise<boolean> { try { - return (await this._git!.diff(['HEAD', branchName])) !== ''; + return (await this._git.diff(['HEAD', branchName])) !== ''; } catch (err) { return true; } @@ -490,22 +490,22 @@ export class Storage { }: CommitFilesConfig): Promise<void> { logger.debug(`Committing files to branch ${branchName}`); try { - await this._git!.reset('hard'); - await this._git!.raw(['clean', '-fd']); - await this._git!.checkout(['-B', branchName, 'origin/' + parentBranch]); + await this._git.reset('hard'); + await this._git.raw(['clean', '-fd']); + await this._git.checkout(['-B', branchName, 'origin/' + parentBranch]); const fileNames = []; const deleted = []; for (const file of files) { // istanbul ignore if if (file.name === '|delete|') { deleted.push(file.contents); - } else if (await isDirectory(join(this._cwd!, file.name))) { + } else if (await isDirectory(join(this._cwd, file.name))) { fileNames.push(file.name); - await this._git!.add(file.name); + await this._git.add(file.name); } else { fileNames.push(file.name); await fs.outputFile( - join(this._cwd!, file.name), + join(this._cwd, file.name), Buffer.from(file.contents) ); } @@ -514,18 +514,18 @@ export class Storage { if (fileNames.length === 1 && fileNames[0] === 'renovate.json') { fileNames.unshift('-f'); } - if (fileNames.length) await this._git!.add(fileNames); + if (fileNames.length) await this._git.add(fileNames); if (deleted.length) { for (const f of deleted) { try { - await this._git!.rm([f]); + await this._git.rm([f]); } catch (err) /* istanbul ignore next */ { checkForPlatformFailure(err); logger.debug({ err }, 'Cannot delete ' + f); } } } - await this._git!.commit(message); + await this._git.commit(message); if (!(await this.hasDiff(`origin/${branchName}`))) { logger.info( { branchName, fileNames }, @@ -533,13 +533,13 @@ export class Storage { ); return; } - await this._git!.push('origin', `${branchName}:${branchName}`, { + await this._git.push('origin', `${branchName}:${branchName}`, { '--force': true, '-u': true, }); // Fetch it after create const ref = `refs/heads/${branchName}:refs/remotes/origin/${branchName}`; - await this._git!.fetch(['origin', ref, '--depth=2', '--force']); + await this._git.fetch(['origin', ref, '--depth=2', '--force']); this._config.branchExists[branchName] = true; limits.incrementLimit('prCommitsPerRunLimit'); } catch (err) /* istanbul ignore next */ { diff --git a/lib/platform/github/index.ts b/lib/platform/github/index.ts index 79cac92d967c52bb233be105a799d22c7c339800..ea865ca9d67262d120fbd255073edaf3aa5e000c 100644 --- a/lib/platform/github/index.ts +++ b/lib/platform/github/index.ts @@ -396,7 +396,7 @@ export async function initRepo({ logger.info({ err }, 'Error forking repository'); throw new Error(REPOSITORY_CANNOT_FORK); } - if (existingRepos.includes(config.repository!)) { + if (existingRepos.includes(config.repository)) { logger.info( { repository_fork: config.repository }, 'Found existing fork' @@ -449,7 +449,7 @@ export async function initRepo({ logger.debug('Using personal access token for git init'); parsedEndpoint.auth = opts.token; } - parsedEndpoint.host = parsedEndpoint.host!.replace( + parsedEndpoint.host = parsedEndpoint.host.replace( 'api.github.com', 'github.com' ); @@ -963,7 +963,7 @@ function matchesState(state: string, desiredState: string): boolean { if (desiredState === 'all') { return true; } - if (desiredState[0] === '!') { + if (desiredState.startsWith('!')) { return state !== desiredState.substring(1); } return state === desiredState; @@ -1002,9 +1002,9 @@ export async function getPrList(): Promise<Pr[]> { pr.head && pr.head.repo ? pr.head.repo.full_name : undefined, }) ); - logger.debug(`Retrieved ${config.prList!.length} Pull Requests`); + logger.debug(`Retrieved ${config.prList.length} Pull Requests`); } - return config.prList!; + return config.prList; } export async function findPr({ @@ -1632,7 +1632,7 @@ export async function createPr({ const body = sanitize(rawBody); const base = useDefaultBranch ? config.defaultBranch : config.baseBranch; // Include the repository owner to handle forkMode and regular mode - const head = `${config.repository!.split('/')[0]}:${branchName}`; + const head = `${config.repository.split('/')[0]}:${branchName}`; const options: any = { body: { title, diff --git a/lib/platform/gitlab/gl-got-wrapper.ts b/lib/platform/gitlab/gl-got-wrapper.ts index 5ac54d14bc5fc16c65b33a7abbfe2dca2955c9d3..3888b4eb0eda86b8484a98bfbc259a0d4fc0bbe3 100644 --- a/lib/platform/gitlab/gl-got-wrapper.ts +++ b/lib/platform/gitlab/gl-got-wrapper.ts @@ -65,6 +65,7 @@ for (const x of helpers) { get(url, { ...opts, method: x.toUpperCase() }); } +// eslint-disable-next-line @typescript-eslint/unbound-method api.setBaseUrl = (e: string): void => { baseUrl = e; }; diff --git a/lib/platform/gitlab/index.ts b/lib/platform/gitlab/index.ts index d3de42bb4bd98c2ecd14bd0b71e9756b657118fe..b22edbfc2f7cadf5dc5f72d60639b9b7a7657564 100644 --- a/lib/platform/gitlab/index.ts +++ b/lib/platform/gitlab/index.ts @@ -215,7 +215,7 @@ export async function initRepo({ logger.debug('no http_url_to_repo found. Falling back to old behaviour.'); const { host, protocol } = URL.parse(defaults.endpoint); url = GitStorage.getUrl({ - protocol: protocol!.slice(0, -1) as any, + protocol: protocol.slice(0, -1) as any, auth: 'oauth2:' + opts.token, host, repository, @@ -793,9 +793,10 @@ export async function addAssignees( } } -export function addReviewers(iid: number, reviewers: string[]): void { +export function addReviewers(iid: number, reviewers: string[]): Promise<void> { logger.debug(`addReviewers('${iid}, '${reviewers})`); logger.warn('Unimplemented in GitLab: approvals'); + return Promise.resolve(); } export async function deleteLabel( @@ -967,7 +968,7 @@ function matchesState(state: string, desiredState: string): boolean { if (desiredState === 'all') { return true; } - if (desiredState[0] === '!') { + if (desiredState.startsWith('!')) { return state !== desiredState.substring(1); } return state === desiredState; @@ -992,6 +993,6 @@ export function getCommitMessages(): Promise<string[]> { return config.storage.getCommitMessages(); } -export function getVulnerabilityAlerts(): VulnerabilityAlert[] { - return []; +export function getVulnerabilityAlerts(): Promise<VulnerabilityAlert[]> { + return Promise.resolve([]); } diff --git a/lib/platform/utils/pr-body.ts b/lib/platform/utils/pr-body.ts index 47e80766fcc2792b194efe3780b1aec1a6b5174e..d0fcf824d190e7f6366d79bcd5abd1a7a4d03104 100644 --- a/lib/platform/utils/pr-body.ts +++ b/lib/platform/utils/pr-body.ts @@ -1,10 +1,10 @@ +const re = new RegExp(`### Release Notes.*### Renovate configuration`, 'ms'); + export function smartTruncate(input: string, len: number): string { if (input.length < len) { return input; } - const releaseNotesMatch = input.match( - new RegExp(`### Release Notes.*### Renovate configuration`, 'ms') - ); + const releaseNotesMatch = re.exec(input); if (releaseNotesMatch) { const divider = `</details>\n\n---\n\n### Renovate configuration`; const [releaseNotes] = releaseNotesMatch; diff --git a/lib/util/ignore.ts b/lib/util/ignore.ts index 789f9aeb000b562bf40422c2a668df71850db1cd..d0d69042940866782de32016918be13e034f8313 100644 --- a/lib/util/ignore.ts +++ b/lib/util/ignore.ts @@ -1,7 +1,7 @@ import { logger } from '../logger'; export function isSkipComment(comment?: string): boolean { - if (comment && comment.match(/^(renovate|pyup):/)) { + if (/^(renovate|pyup):/.test(comment)) { const command = comment .split('#')[0] .split(':')[1] diff --git a/lib/util/package-rules.ts b/lib/util/package-rules.ts index a9e4171b5f99360acbb45b8c8adf7946e22c9b7c..253e2c4d3ab17c55f4554092961795fb8f65ce54 100644 --- a/lib/util/package-rules.ts +++ b/lib/util/package-rules.ts @@ -146,7 +146,7 @@ function matchesRule(inputConfig: Config, packageRule: PackageRule): boolean { ? '.*' : packagePattern ); - if (depName && depName.match(packageRegex)) { + if (packageRegex.test(depName)) { logger.trace(`${depName} matches against ${packageRegex}`); isMatch = true; } @@ -170,7 +170,7 @@ function matchesRule(inputConfig: Config, packageRule: PackageRule): boolean { const packageRegex = regEx( pattern === '^*$' || pattern === '*' ? '.*' : pattern ); - if (depName && depName.match(packageRegex)) { + if (packageRegex.test(depName)) { logger.trace(`${depName} matches against ${packageRegex}`); isMatch = true; } diff --git a/lib/versioning/composer/index.ts b/lib/versioning/composer/index.ts index bf7cdc5cd8fe0d7082fdbd4d3e2d8bf54981f954..721c58515ff7de27c7a7b93ccb7980529ae9ff16 100644 --- a/lib/versioning/composer/index.ts +++ b/lib/versioning/composer/index.ts @@ -91,17 +91,17 @@ function getNewValue({ fromVersion, toVersion: padZeroes(toVersion), }); - } else if (currentValue.match(/^~(0\.[1-9][0-9]*)$/)) { + } else if (/^~(0\.[1-9][0-9]*)$/.test(currentValue)) { // handle ~0.4 case first if (toMajor === 0) { newValue = `~0.${toMinor}`; } else { newValue = `~${toMajor}.0`; } - } else if (currentValue.match(/^~([0-9]*)$/)) { + } else if (/^~([0-9]*)$/.test(currentValue)) { // handle ~4 case newValue = `~${toMajor}`; - } else if (currentValue.match(/^~([0-9]*(?:\.[0-9]*)?)$/)) { + } else if (/^~([0-9]*(?:\.[0-9]*)?)$/.test(currentValue)) { // handle ~4.1 case if (fromVersion && toMajor > getMajor(fromVersion)) { newValue = `~${toMajor}.0`; diff --git a/lib/versioning/docker/index.ts b/lib/versioning/docker/index.ts index 00b6f64f089347140009128779e782dc8e8fc724..62a6536f550705bcacb800c33118adf737cb6165 100644 --- a/lib/versioning/docker/index.ts +++ b/lib/versioning/docker/index.ts @@ -6,6 +6,7 @@ function parse(version: string): any { const prefix = versionPieces.shift(); const suffix = versionPieces.join('-'); const release = prefix.split('.').map(Number); + // eslint-disable-next-line @typescript-eslint/unbound-method if (release.some(Number.isNaN)) { return null; } diff --git a/lib/versioning/hashicorp/index.ts b/lib/versioning/hashicorp/index.ts index faf9d3f47142bbb983e54556ab5cbcf36a395d72..b60f42d8cc702c7c2f7218435ac67432c24904fb 100644 --- a/lib/versioning/hashicorp/index.ts +++ b/lib/versioning/hashicorp/index.ts @@ -28,7 +28,7 @@ function getNewValue({ toVersion, }: NewValueConfig): string { // handle specia. ~> 1.2 case - if (currentValue.match(/(~>\s*)\d+\.\d+$/)) { + if (/(~>\s*)\d+\.\d+$/.test(currentValue)) { return currentValue.replace( /(~>\s*)\d+\.\d+$/, `$1${npm.getMajor(toVersion)}.0` @@ -52,6 +52,6 @@ export const api: VersioningApi = { getNewValue, }; -export const isVersion = api.isVersion; +export const { isVersion } = api; export default api; diff --git a/lib/versioning/hex/index.ts b/lib/versioning/hex/index.ts index fb595dd1daf41c54a20165949cd80a776c696f3a..b7a7894ee9a978cbdc7dad02671c25bc10185a39 100644 --- a/lib/versioning/hex/index.ts +++ b/lib/versioning/hex/index.ts @@ -59,7 +59,7 @@ const getNewValue = ({ toVersion, }); newSemver = npm2hex(newSemver); - if (currentValue.match(/~>\s*(\d+\.\d+)$/)) { + if (/~>\s*(\d+\.\d+)$/.test(currentValue)) { newSemver = newSemver.replace( /\^\s*(\d+\.\d+(\.\d)?)/, (_str, p1) => '~> ' + p1.slice(0, -2) diff --git a/lib/versioning/ivy/parse.ts b/lib/versioning/ivy/parse.ts index e5123baf52f61aaaa6cbc4984d6def673bcea2ac..b26b847133f0e72c6b00bdfd614cae7b4f22b854 100644 --- a/lib/versioning/ivy/parse.ts +++ b/lib/versioning/ivy/parse.ts @@ -23,7 +23,7 @@ function parseDynamicRevision(str: string): Revision { } const SUBREV_REGEX = /\.\+$/; - if (SUBREV_REGEX.test(str)) { + if (str.endsWith('.+')) { const value = str.replace(SUBREV_REGEX, ''); if (isSingleVersion(value)) { return { diff --git a/lib/versioning/maven/compare.ts b/lib/versioning/maven/compare.ts index 38bb1b8e81d3f7dfc73b9f69d42725fab2c28987..ef89b9a2d8826b5f9950ac53f29ff15a06940f88 100644 --- a/lib/versioning/maven/compare.ts +++ b/lib/versioning/maven/compare.ts @@ -292,12 +292,12 @@ function parseRange(rangeStr: string): any { rightBracket: ']', }); interval = emptyInterval(); - } else if (subStr[0] === '[') { + } else if (subStr.startsWith('[')) { const ver = subStr.slice(1); interval.leftType = INCLUDING_POINT; interval.leftValue = ver; interval.leftBracket = '['; - } else if (subStr[0] === '(' || subStr[0] === ']') { + } else if (subStr.startsWith('(') || subStr.startsWith(']')) { const ver = subStr.slice(1); interval.leftType = EXCLUDING_POINT; interval.leftValue = ver; @@ -305,18 +305,18 @@ function parseRange(rangeStr: string): any { } else { result = null; } - } else if (/]$/.test(subStr)) { + } else if (subStr.endsWith(']')) { const ver = subStr.slice(0, -1); interval.rightType = INCLUDING_POINT; interval.rightValue = ver; interval.rightBracket = ']'; result.push(interval); interval = emptyInterval(); - } else if (/\)$/.test(subStr) || /\[$/.test(subStr)) { + } else if (subStr.endsWith(')') || subStr.endsWith('[')) { const ver = subStr.slice(0, -1); interval.rightType = EXCLUDING_POINT; interval.rightValue = ver; - interval.rightBracket = /\)$/.test(subStr) ? ')' : '['; + interval.rightBracket = subStr.endsWith(')') ? ')' : '['; result.push(interval); interval = emptyInterval(); } else { diff --git a/lib/versioning/regex/index.ts b/lib/versioning/regex/index.ts index 9a4a6f788216350a87f1c357a6f5b8953904ebce..78c69579b6b7e435de8b978e051b7fd6f4667466 100644 --- a/lib/versioning/regex/index.ts +++ b/lib/versioning/regex/index.ts @@ -69,7 +69,7 @@ export class RegExpVersioningApi extends GenericVersioningApi<RegExpVersion> { // convenience method for passing a string into a Version given current config. protected _parse(version: string): RegExpVersion | null { - const match = version ? version.match(this._config) : null; + const match = this._config.exec(version); if (match === null) { return null; } diff --git a/lib/versioning/ruby/range.ts b/lib/versioning/ruby/range.ts index 088c0e4fb1164ef2c8fef40d32aa4db2235d53cd..a7923b66d2dbc9d4ffddbabc638bc1a1d35b3424 100644 --- a/lib/versioning/ruby/range.ts +++ b/lib/versioning/ruby/range.ts @@ -14,7 +14,7 @@ const parse = (range: string): Range => { const value = (range || '').trim(); - const match = value.match(regExp); + const match = regExp.exec(value); if (match) { const { version = null, operator = null, delimiter = ' ' } = match.groups; return { version, operator, delimiter }; diff --git a/lib/versioning/swift/range.ts b/lib/versioning/swift/range.ts index cca8135e8b3f9f7c371ba46758830e3bf7815d21..f9fba015f123d9e66512f498f23980fa486c3e14 100644 --- a/lib/versioning/swift/range.ts +++ b/lib/versioning/swift/range.ts @@ -8,25 +8,25 @@ const toRange = /^\s*(\.\.[.<])\s*"([^"]+)"\s*$/; function toSemverRange(range: string): string { if (fromParam.test(range)) { - const [, version] = range.match(fromParam); + const [, version] = fromParam.exec(range); if (semver.valid(version)) { const nextMajor = `${semver.major(version) + 1}.0.0`; return `>=${version} <${nextMajor}`; } } else if (fromRange.test(range)) { - const [, version] = range.match(fromRange); + const [, version] = fromRange.exec(range); if (semver.valid(version)) { return `>=${version}`; } } else if (binaryRange.test(range)) { - const [, fromVersion, op, toVersion] = range.match(binaryRange); + const [, fromVersion, op, toVersion] = binaryRange.exec(range); if (semver.valid(fromVersion) && semver.valid(toVersion)) { return op === '..<' ? `>=${fromVersion} <${toVersion}` : `>=${fromVersion} <=${toVersion}`; } } else if (toRange.test(range)) { - const [, op, toVersion] = range.match(toRange); + const [, op, toVersion] = toRange.exec(range); if (semver.valid(toVersion)) { return op === '..<' ? `<${toVersion}` : `<=${toVersion}`; } @@ -39,15 +39,15 @@ function getNewValue({ currentValue, toVersion }: NewValueConfig): string { return toVersion.replace(/^v/, ''); } if (fromRange.test(currentValue)) { - const [, version] = currentValue.match(fromRange); + const [, version] = fromRange.exec(currentValue); return currentValue.replace(version, toVersion); } if (binaryRange.test(currentValue)) { - const [, , , version] = currentValue.match(binaryRange); + const [, , , version] = binaryRange.exec(currentValue); return currentValue.replace(version, toVersion); } if (toRange.test(currentValue)) { - const [, , version] = currentValue.match(toRange); + const [, , version] = toRange.exec(currentValue); return currentValue.replace(version, toVersion); } return currentValue; diff --git a/lib/workers/branch/index.ts b/lib/workers/branch/index.ts index e5bbc2c1809a0763de88c7aed46d9f29abd5810b..86c6b2af0760657e65b16a50b07ed4b0673b22b6 100644 --- a/lib/workers/branch/index.ts +++ b/lib/workers/branch/index.ts @@ -1,6 +1,4 @@ import { DateTime } from 'luxon'; - -import _ from 'lodash'; import { readFile } from 'fs-extra'; import is from '@sindresorhus/is'; import minimatch from 'minimatch'; @@ -36,6 +34,7 @@ import { } from '../../constants/error-messages'; import { BRANCH_STATUS_FAILURE } from '../../constants/branch-constants'; import { exec } from '../../util/exec'; +import { regEx } from '../../util/regex'; export type ProcessBranchResult = | 'already-existed' @@ -344,8 +343,8 @@ export async function processBranch( if (is.nonEmptyArray(commands)) { for (const cmd of commands) { if ( - !_.some(config.allowedPostUpgradeCommands, (pattern: string) => - cmd.match(pattern) + !config.allowedPostUpgradeCommands.some(pattern => + regEx(pattern).test(cmd) ) ) { logger.warn( diff --git a/lib/workers/pr/changelog/release-notes.ts b/lib/workers/pr/changelog/release-notes.ts index 17b599085a3e78a524c811e4c051090628374f50..6585d3865c77139c3617c94303fa3814c6425ad9 100644 --- a/lib/workers/pr/changelog/release-notes.ts +++ b/lib/workers/pr/changelog/release-notes.ts @@ -6,7 +6,7 @@ import { api } from '../../../platform/github/gh-got-wrapper'; import { logger } from '../../../logger'; import { ChangeLogResult, ChangeLogNotes } from './common'; -const ghGot = api.get; +const { get: ghGot } = api; const markdown = new MarkdownIt('zero'); markdown.enable(['heading', 'lheading']); diff --git a/lib/workers/pr/changelog/source-github.ts b/lib/workers/pr/changelog/source-github.ts index 1c0dac81b8bfdafe896d8a6ba197ec0810237616..188465d10edd00cb0ffe3f3f58ef701a1e59069f 100644 --- a/lib/workers/pr/changelog/source-github.ts +++ b/lib/workers/pr/changelog/source-github.ts @@ -12,7 +12,7 @@ import { } from './common'; import { Release } from '../../../datasource'; -const ghGot = api.get; +const { get: ghGot } = api; async function getTags( endpoint: string, diff --git a/lib/workers/pr/index.ts b/lib/workers/pr/index.ts index 5b25356bd4ade99d8c0d07e135bbb00c7e223b97..f577f4ea9df24fb7cc343f8cba167ffee8ffcf14 100644 --- a/lib/workers/pr/index.ts +++ b/lib/workers/pr/index.ts @@ -26,7 +26,7 @@ function noWhitespace(input: string): string { } function noLeadingAtSymbol(input: string): string { - return input.length && input[0] === '@' ? input.slice(1) : input; + return input.length && input.startsWith('@') ? input.slice(1) : input; } async function addAssigneesReviewers(config, pr: Pr): Promise<void> { diff --git a/lib/workers/repository/extract/file-match.ts b/lib/workers/repository/extract/file-match.ts index cd5db719a5057884016d8a96ea2c50354bb98001..15790652ef770b11832e87e124e43659c6feea2e 100644 --- a/lib/workers/repository/extract/file-match.ts +++ b/lib/workers/repository/extract/file-match.ts @@ -41,9 +41,8 @@ export function getMatchingFiles( let matchedFiles = []; for (const fileMatch of fileMatchList) { logger.debug(`Using file match: ${fileMatch} for manager ${manager}`); - matchedFiles = matchedFiles.concat( - fileList.filter(file => file.match(new RegExp(fileMatch))) - ); + const re = new RegExp(fileMatch); + matchedFiles = matchedFiles.concat(fileList.filter(file => re.test(file))); } // filter out duplicates return [...new Set(matchedFiles)]; diff --git a/lib/workers/repository/finalise/validate.ts b/lib/workers/repository/finalise/validate.ts index 0740550c5acea6bb068de0f9fc8610305a7f23a7..163a3c521d2f725276214e5b70f58a146f467fa7 100644 --- a/lib/workers/repository/finalise/validate.ts +++ b/lib/workers/repository/finalise/validate.ts @@ -14,7 +14,7 @@ async function getRenovatePrs(branchPrefix: string): Promise<Pr[]> { return (await platform.getPrList()) .filter(pr => pr.state === 'open') .filter(pr => pr.branchName && !pr.branchName.startsWith(branchPrefix)) - .filter(pr => pr.title && pr.title.match(new RegExp('renovate', 'i'))); + .filter(pr => new RegExp('renovate', 'i').test(pr.title)); } async function getRenovateFiles(prNo: number): Promise<string[]> { diff --git a/lib/workers/repository/process/index.ts b/lib/workers/repository/process/index.ts index d386df4c8107338ab324830fc02643d4dc8a818e..873b64a8362b129ea241987e00ad62a7d1904e50 100644 --- a/lib/workers/repository/process/index.ts +++ b/lib/workers/repository/process/index.ts @@ -28,13 +28,15 @@ export async function processRepo( const checkMatch = ' - \\[x\\] <!-- ([a-zA-Z]+)-branch=([^\\s]+) -->'; const checked = issue.body.match(new RegExp(checkMatch, 'g')); if (checked && checked.length) { + const re = new RegExp(checkMatch); checked.forEach(check => { - const [, type, branchName] = check.match(new RegExp(checkMatch)); + const [, type, branchName] = re.exec(check); config.masterIssueChecks[branchName] = type; }); } - const checkAllMatch = ' - \\[x\\] <!-- rebase-all-open-prs -->'; - const checkedRebaseAll = issue.body.match(new RegExp(checkAllMatch)); + const checkedRebaseAll = issue.body.includes( + ' - [x] <!-- rebase-all-open-prs -->' + ); if (checkedRebaseAll) { config.masterIssueRebaseAllOpen = true; /* eslint-enable no-param-reassign */ diff --git a/lib/workers/repository/process/lookup/rollback.ts b/lib/workers/repository/process/lookup/rollback.ts index a16a480647374af26c72539ceb8592664524a123..6b7b07bcce1f74ff3d13bebe35f8d71747e394ca 100644 --- a/lib/workers/repository/process/lookup/rollback.ts +++ b/lib/workers/repository/process/lookup/rollback.ts @@ -16,7 +16,7 @@ export function getRollbackUpdate( const { packageFile, versionScheme, depName, currentValue } = config; const version = versioning.get(versionScheme); // istanbul ignore if - if (!version.isLessThanRange) { + if (!('isLessThanRange' in version)) { logger.info( { versionScheme }, 'Current version scheme does not support isLessThanRange()' diff --git a/test/datasource/index.spec.ts b/test/datasource/index.spec.ts index a6ed23db894129efc38dfbebf64e93b23baddbe6..38263d28bc6862ced8a71294f1a3be4d8a1de364 100644 --- a/test/datasource/index.spec.ts +++ b/test/datasource/index.spec.ts @@ -12,10 +12,10 @@ jest.mock('../../lib/datasource/npm'); const npmDatasource: any = _npm; describe('datasource/index', () => { - it('returns if digests are supported', async () => { - expect( - await datasource.supportsDigests({ datasource: DATASOURCE_GITHUB }) - ).toBe(true); + it('returns if digests are supported', () => { + expect(datasource.supportsDigests({ datasource: DATASOURCE_GITHUB })).toBe( + true + ); }); it('returns null for no datasource', async () => { expect( diff --git a/test/platform/azure/azure-got-wrapper.spec.ts b/test/platform/azure/azure-got-wrapper.spec.ts index 85a2c4b1f000627f4839d9989033ee47613f8d6a..963ca80fbdeab33b8c4a15c7bdefa1e854d9caf8 100644 --- a/test/platform/azure/azure-got-wrapper.spec.ts +++ b/test/platform/azure/azure-got-wrapper.spec.ts @@ -16,7 +16,7 @@ describe('platform/azure/azure-got-wrapper', () => { expect(azure.coreApi).toThrow('No token found for azure'); expect(azure.policyApi).toThrow('No token found for azure'); }); - it('should set token and endpoint', async () => { + it('should set token and endpoint', () => { hostRules.add({ hostType: 'azure', token: 'token', @@ -24,7 +24,7 @@ describe('platform/azure/azure-got-wrapper', () => { }); azure.setEndpoint('https://dev.azure.com/renovate12345'); - const res = await azure.azureObj(); + const res = azure.azureObj(); delete res.rest.client.userAgent; delete res.vsoClient.restClient.client.userAgent; diff --git a/test/platform/azure/azure-helper.spec.ts b/test/platform/azure/azure-helper.spec.ts index fc631a784d85cd07b31bc7f012217568d4589839..b0c6d083b36e0c2ffcc374c8ff9a3a66058bf833 100644 --- a/test/platform/azure/azure-helper.spec.ts +++ b/test/platform/azure/azure-helper.spec.ts @@ -266,12 +266,12 @@ describe('platform/azure/helpers', () => { }); describe('getProjectAndRepo', () => { - it('should return the object with same strings', async () => { - const res = await azureHelper.getProjectAndRepo('myRepoName'); + it('should return the object with same strings', () => { + const res = azureHelper.getProjectAndRepo('myRepoName'); expect(res).toMatchSnapshot(); }); - it('should return the object with project and repo', async () => { - const res = await azureHelper.getProjectAndRepo('prjName/myRepoName'); + it('should return the object with project and repo', () => { + const res = azureHelper.getProjectAndRepo('prjName/myRepoName'); expect(res).toMatchSnapshot(); }); it('should return an error', () => { diff --git a/test/platform/bitbucket/comments.spec.ts b/test/platform/bitbucket/comments.spec.ts index cf31b77e4c4c318e3d465a5817ab58dbf8cb3278..4ed1043f9c26f292fa037e3c7efd3afe61f706b4 100644 --- a/test/platform/bitbucket/comments.spec.ts +++ b/test/platform/bitbucket/comments.spec.ts @@ -11,7 +11,7 @@ describe('platform/comments', () => { const config: comments.CommentsConfig = { repository: 'some/repo' }; async function mockedGet(path: string) { - const uri = URL.parse(path).pathname!; + const uri = URL.parse(path).pathname; let body = (responses as any)[uri]; if (!body) { throw new Error('Missing request'); diff --git a/test/platform/bitbucket/index.spec.ts b/test/platform/bitbucket/index.spec.ts index e46fc97a40ca7993f766b0a9555d199874baf0a2..a641900d1df52b615540d85a243adaf090246138 100644 --- a/test/platform/bitbucket/index.spec.ts +++ b/test/platform/bitbucket/index.spec.ts @@ -56,7 +56,7 @@ describe('platform/bitbucket', () => { }); async function mockedGet(path: string) { - let body = (responses as any)[URL.parse(path).pathname!] || { values: [] }; + let body = (responses as any)[URL.parse(path).pathname] || { values: [] }; if (typeof body === 'function') { body = await body(); } diff --git a/test/util/exec.spec.ts b/test/util/exec.spec.ts index dc38a1b55cd7edda4729fd709c43618dde768813..15f6e4378ab8549c5e14b12e9c982d0afe678157 100644 --- a/test/util/exec.spec.ts +++ b/test/util/exec.spec.ts @@ -371,7 +371,7 @@ describe(`Child process execution wrapper`, () => { return undefined; }); - await exec(cmd as string, inOpts as ExecOptions); + await exec(cmd as string, inOpts); expect(actualCmd).toEqual(outCommand); expect(actualOpts).toEqual(outOpts); diff --git a/test/versioning/index.spec.ts b/test/versioning/index.spec.ts index 1574c38bb9ba93daaf6487518c13a3a59caf2ea6..6a07d4ec2d954b60c0ce5625e2b25fd1cbfb9094 100644 --- a/test/versioning/index.spec.ts +++ b/test/versioning/index.spec.ts @@ -51,7 +51,7 @@ describe('versioning.get(versionScheme)', () => { do { Object.getOwnPropertyNames(o).forEach(prop => { - if (props.indexOf(prop) === -1) { + if (!props.includes(prop)) { props.push(prop); } }); diff --git a/test/versioning/loose/utils.spec.ts b/test/versioning/loose/utils.spec.ts index 4e21ac9c255f0b80f6f589c29cf15954313db20e..8dda29c9626706810a1bbb3be198b863785bd493 100644 --- a/test/versioning/loose/utils.spec.ts +++ b/test/versioning/loose/utils.spec.ts @@ -22,7 +22,7 @@ describe('loose/utils', () => { do { Object.getOwnPropertyNames(o).forEach(prop => { - if (props.indexOf(prop) === -1) { + if (!props.includes(prop)) { props.push(prop); } }); diff --git a/test/workers/repository/updates/flatten.spec.ts b/test/workers/repository/updates/flatten.spec.ts index e799e68564522427cc52ede1b1b0e35a2856316c..5cffe899baaa996fa048bc61e76023d1c0d64dad 100644 --- a/test/workers/repository/updates/flatten.spec.ts +++ b/test/workers/repository/updates/flatten.spec.ts @@ -13,7 +13,7 @@ beforeEach(() => { describe('workers/repository/updates/flatten', () => { describe('flattenUpdates()', () => { - it('flattens', async () => { + it('flattens', () => { config.lockFileMaintenance.enabled = true; config.packageRules = [ { @@ -72,7 +72,7 @@ describe('workers/repository/updates/flatten', () => { }, ], }; - const res = await flattenUpdates(config, packageFiles); + const res = flattenUpdates(config, packageFiles); expect(res).toHaveLength(9); expect( res.filter(r => r.updateType === 'lockFileMaintenance')