Skip to content

Commit

Permalink
refactor: fix prefer-nullish-coalescing (#16171)
Browse files Browse the repository at this point in the history
  • Loading branch information
viceice committed Jun 21, 2022
1 parent e5c6f38 commit 10302eb
Show file tree
Hide file tree
Showing 36 changed files with 75 additions and 75 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ module.exports = {
},
],
'@typescript-eslint/prefer-optional-chain': 2,
'@typescript-eslint/prefer-nullish-coalescing': 1, // TODO: Temporary (#7154)
'@typescript-eslint/prefer-nullish-coalescing': 2,
curly: [2, 'all'],
'require-await': 2,
// next 2 rules disabled due to https://github.com/microsoft/TypeScript/issues/20024
Expand Down
2 changes: 1 addition & 1 deletion lib/config/massage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export function massageConfig(config: RenovateConfig): RenovateConfig {
delete newRule[newKey];
}
});
newRule.matchUpdateTypes = rule.matchUpdateTypes || [];
newRule.matchUpdateTypes = rule.matchUpdateTypes ?? [];
newRule.matchUpdateTypes.push(key);
newRule = { ...newRule, ...val };
newRules.push(newRule);
Expand Down
4 changes: 2 additions & 2 deletions lib/config/migrate-validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ export async function migrateAndValidate(
if (is.nonEmptyArray(errors)) {
logger.info({ errors }, 'Found renovate config errors');
}
massagedConfig.errors = (config.errors || []).concat(errors);
massagedConfig.errors = (config.errors ?? []).concat(errors);
if (!config.repoIsOnboarded) {
massagedConfig.warnings = (config.warnings || []).concat(warnings);
massagedConfig.warnings = (config.warnings ?? []).concat(warnings);
}
return massagedConfig;
} catch (err) /* istanbul ignore next */ {
Expand Down
6 changes: 3 additions & 3 deletions lib/config/presets/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,9 @@ export function parsePreset(input: string): ParsedPreset {
throw new Error(PRESET_INVALID);
}
({ repo, presetPath, presetName, tag } =
nonScopedPresetWithSubdirRegex.exec(str)?.groups || {});
nonScopedPresetWithSubdirRegex.exec(str)?.groups ?? {});
} else {
({ repo, presetName, tag } = gitPresetRegex.exec(str)?.groups || {});
({ repo, presetName, tag } = gitPresetRegex.exec(str)?.groups ?? {});

if (presetSource === 'npm' && !repo.startsWith('renovate-config-')) {
repo = `renovate-config-${repo}`;
Expand Down Expand Up @@ -270,7 +270,7 @@ export async function resolveConfigPresets(
): Promise<AllConfig> {
let ignorePresets = clone(_ignorePresets);
if (!ignorePresets || ignorePresets.length === 0) {
ignorePresets = inputConfig.ignorePresets || [];
ignorePresets = inputConfig.ignorePresets ?? [];
}
logger.trace(
{ config: inputConfig, existingPresets },
Expand Down
4 changes: 2 additions & 2 deletions lib/modules/datasource/conan/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export class ConanDatasource extends Datasource {
json: true,
}) as ConanYAML;
return {
releases: Object.keys(doc?.versions || {}).map((version) => ({
releases: Object.keys(doc?.versions ?? {}).map((version) => ({
version,
})),
};
Expand Down Expand Up @@ -80,7 +80,7 @@ export class ConanDatasource extends Datasource {
logger.trace({ lookupUrl }, 'Got conan api result');
const dep: ReleaseResult = { releases: [] };

for (const resultString of Object.values(versions.results || {})) {
for (const resultString of Object.values(versions.results ?? {})) {
const fromMatch = conanDatasourceRegex.exec(resultString);
if (fromMatch?.groups?.version && fromMatch?.groups?.userChannel) {
const version = fromMatch.groups.version;
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/datasource/git-tags/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export class GitTagsDatasource extends GitDatasource {
newValue?: string
): Promise<string | null> {
const rawRefs = await this.getRawRefs({ packageName });
const findValue = newValue || 'HEAD';
const findValue = newValue ?? 'HEAD';
const ref = rawRefs?.find((rawRef) => rawRef.value === findValue);
if (ref) {
return ref.hash;
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/datasource/go/releases-goproxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ export class GoProxyDatasource extends Datasource {
static parsedNoproxy: Record<string, RegExp | null> = {};

static parseNoproxy(
input: unknown = process.env.GONOPROXY || process.env.GOPRIVATE
input: unknown = process.env.GONOPROXY ?? process.env.GOPRIVATE
): RegExp | null {
if (!is.string(input)) {
return null;
Expand Down
4 changes: 2 additions & 2 deletions lib/modules/datasource/npm/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ export async function getDependency(
}

const latestVersion = res.versions[res['dist-tags']?.latest ?? ''];
res.repository = res.repository || latestVersion?.repository;
res.homepage = res.homepage || latestVersion?.homepage;
res.repository ??= latestVersion?.repository;
res.homepage ??= latestVersion?.homepage;

const { sourceUrl, sourceDirectory } = getPackageSource(res.repository);

Expand Down
6 changes: 3 additions & 3 deletions lib/modules/datasource/pypi/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export class PypiDatasource extends Datasource {
override readonly customRegistrySupport = true;

override readonly defaultRegistryUrls = [
process.env.PIP_INDEX_URL || 'https://pypi.org/pypi/',
process.env.PIP_INDEX_URL ?? 'https://pypi.org/pypi/',
];

override readonly defaultVersioning = pep440.id;
Expand Down Expand Up @@ -146,7 +146,7 @@ export class PypiDatasource extends Datasource {
if (dep.releases) {
const versions = Object.keys(dep.releases);
dependency.releases = versions.map((version) => {
const releases = dep.releases?.[version] || [];
const releases = dep.releases?.[version] ?? [];
const { upload_time: releaseTimestamp } = releases[0] || {};
const isDeprecated = releases.some(({ yanked }) => yanked);
const result: Release = {
Expand Down Expand Up @@ -260,7 +260,7 @@ export class PypiDatasource extends Datasource {
}
const versions = Object.keys(releases);
dependency.releases = versions.map((version) => {
const versionReleases = releases[version] || [];
const versionReleases = releases[version] ?? [];
const isDeprecated = versionReleases.some(({ yanked }) => yanked);
const result: Release = { version };
if (isDeprecated) {
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/manager/bazel/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ export function extractPackageFile(
(currentValue || commit)
) {
dep.depName = depName;
dep.currentValue = currentValue || commit?.substring(0, 7);
dep.currentValue = currentValue ?? commit?.substring(0, 7);
dep.datasource = GoDatasource.id;
dep.packageName = importpath;
if (remote) {
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/manager/bazel/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export async function updateDependency({
}: UpdateDependencyConfig<BazelManagerData>): Promise<string | null> {
try {
logger.debug(
`bazel.updateDependency(): ${upgrade.newValue || upgrade.newDigest}`
`bazel.updateDependency(): ${upgrade.newValue ?? upgrade.newDigest}`
);
let newDef: string | undefined;
if (upgrade.depType === 'container_pull' && upgrade.managerData?.def) {
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/manager/bundler/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export async function extractPackageFile(
let sourceMatch: RegExpMatchArray | null = null;
for (const delimiter of delimiters) {
sourceMatch =
sourceMatch ||
sourceMatch ??
regEx(`^source ${delimiter}([^${delimiter}]+)${delimiter}\\s*$`).exec(
line
);
Expand Down
10 changes: 5 additions & 5 deletions lib/modules/manager/composer/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,13 @@ function getAuthJson(): string | null {
.findAll({ hostType: PlatformId.Gitlab })
?.forEach((gitlabHostRule) => {
if (gitlabHostRule?.token) {
const host = gitlabHostRule.resolvedHost || 'gitlab.com';
authJson['gitlab-token'] = authJson['gitlab-token'] || {};
const host = gitlabHostRule.resolvedHost ?? 'gitlab.com';
authJson['gitlab-token'] = authJson['gitlab-token'] ?? {};
authJson['gitlab-token'][host] = gitlabHostRule.token;
// https://getcomposer.org/doc/articles/authentication-for-private-packages.md#gitlab-token
authJson['gitlab-domains'] = [
host,
...(authJson['gitlab-domains'] || []),
...(authJson['gitlab-domains'] ?? []),
];
}
});
Expand All @@ -63,10 +63,10 @@ function getAuthJson(): string | null {
?.forEach((hostRule) => {
const { resolvedHost, username, password, token } = hostRule;
if (resolvedHost && username && password) {
authJson['http-basic'] = authJson['http-basic'] || {};
authJson['http-basic'] = authJson['http-basic'] ?? {};
authJson['http-basic'][resolvedHost] = { username, password };
} else if (resolvedHost && token) {
authJson.bearer = authJson.bearer || {};
authJson.bearer = authJson.bearer ?? {};
authJson.bearer[resolvedHost] = token;
}
});
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/manager/docker-compose/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export function extractPackageFile(
// since docker-compose spec version 1.27, the 'version' key has
// become optional and can no longer be used to differentiate
// between v1 and v2.
const services = config.services || config;
const services = config.services ?? config;

// Image name/tags for services are only eligible for update if they don't
// use variables and if the image is not built locally
Expand Down
6 changes: 3 additions & 3 deletions lib/modules/manager/gradle/extract/catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,8 +233,8 @@ export function parseCatalog(
content: string
): PackageDependency<GradleManagerData>[] {
const tomlContent = parse(content) as GradleCatalog;
const versions = tomlContent.versions || {};
const libs = tomlContent.libraries || {};
const versions = tomlContent.versions ?? {};
const libs = tomlContent.libraries ?? {};
const libStartIndex = content.indexOf('libraries');
const libSubContent = content.slice(libStartIndex);
const versionStartIndex = content.indexOf('versions');
Expand All @@ -254,7 +254,7 @@ export function parseCatalog(
extractedDeps.push(dependency);
}

const plugins = tomlContent.plugins || {};
const plugins = tomlContent.plugins ?? {};
const pluginsStartIndex = content.indexOf('[plugins]');
const pluginsSubContent = content.slice(pluginsStartIndex);
for (const pluginName of Object.keys(plugins)) {
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/manager/leiningen/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ function extractLeinRepos(content: string): string[] {
}
const repoSectionContent = repoContent.slice(0, endIdx);
const matches =
repoSectionContent.match(regEx(/"https?:\/\/[^"]*"/g)) || [];
repoSectionContent.match(regEx(/"https?:\/\/[^"]*"/g)) ?? [];
const urls = matches.map((x) =>
x.replace(regEx(/^"/), '').replace(regEx(/"$/), '')
);
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/manager/mix/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export async function extractPackageFile(
}
const res: PackageFile = { deps };
const lockFileName =
(await findLocalSiblingOrParent(fileName, 'mix.lock')) || 'mix.lock';
(await findLocalSiblingOrParent(fileName, 'mix.lock')) ?? 'mix.lock';
// istanbul ignore if
if (await localPathExists(lockFileName)) {
res.lockFiles = [lockFileName];
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/manager/nuget/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ async function addSourceCmds(
nugetConfigFile: string
): Promise<string[]> {
const registries =
(await getConfiguredRegistries(packageFileName)) || getDefaultRegistries();
(await getConfiguredRegistries(packageFileName)) ?? getDefaultRegistries();
const result: string[] = [];
for (const registry of registries) {
const { username, password } = hostRules.find({
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/manager/poetry/update-locked.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export function updateLockedDependency(
logger.debug(
`poetry.updateLockedDependency: ${depName}@${currentVersion} -> ${newVersion} [${lockFile}]`
);
const locked = extractLockFileEntries(lockFileContent || '');
const locked = extractLockFileEntries(lockFileContent ?? '');
if (depName && locked[depName] === newVersion) {
return { status: 'already-updated' };
}
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/manager/regex/strategies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export function handleRecursive(
packageFile,
config,
index + 1,
mergeGroups(combinedGroups, match.groups || {})
mergeGroups(combinedGroups, match.groups ?? {})
);
})
.filter(is.truthy);
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/manager/regex/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function createDependency(
config: CustomExtractConfig,
dep?: PackageDependency
): PackageDependency | null {
const dependency = dep || {};
const dependency = dep ?? {};
const { groups, replaceString } = extractionTemplate;

function updateDependency(field: ValidMatchFields, value: string): void {
Expand Down
6 changes: 3 additions & 3 deletions lib/modules/manager/setup-cfg/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ import { PypiDatasource } from '../../datasource/pypi';
import type { PackageDependency, PackageFile, Result } from '../types';

function getSectionName(str: string): string {
const [, sectionName] = regEx(/^\[\s*([^\s]+)\s*]\s*$/).exec(str) || [];
const [, sectionName] = regEx(/^\[\s*([^\s]+)\s*]\s*$/).exec(str) ?? [];
return sectionName;
}

function getSectionRecord(str: string): string {
const [, sectionRecord] = regEx(/^([^\s]+)\s+=/).exec(str) || [];
const [, sectionRecord] = regEx(/^([^\s]+)\s+=/).exec(str) ?? [];
return sectionRecord;
}

Expand Down Expand Up @@ -62,7 +62,7 @@ function parseDep(

const [lineNoEnvMarkers] = line.split(';').map((part) => part.trim());
const packageMatches =
pkgValRegex.exec(lineNoEnvMarkers) || pkgRegex.exec(lineNoEnvMarkers);
pkgValRegex.exec(lineNoEnvMarkers) ?? pkgRegex.exec(lineNoEnvMarkers);

if (!packageMatches) {
return null;
Expand Down
4 changes: 2 additions & 2 deletions lib/modules/manager/terraform/extract/kubernetes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ export function extractTerraformKubernetesResource(
// istanbul ignore else
if (is.string(line)) {
// `{` will be counted with +1 and `}` with -1. Therefore if we reach braceCounter == 0. We have found the end of the terraform block
const openBrackets = (line.match(regEx(/\{/g)) || []).length;
const closedBrackets = (line.match(regEx(/\}/g)) || []).length;
const openBrackets = (line.match(regEx(/\{/g)) ?? []).length;
const closedBrackets = (line.match(regEx(/\}/g)) ?? []).length;
braceCounter = braceCounter + openBrackets - closedBrackets;

if (line.match(regEx(/^\s*(?:init_)?container(?:\s*\{|$)/s))) {
Expand Down
4 changes: 2 additions & 2 deletions lib/modules/manager/terraform/required-version.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ export function extractTerraformRequiredVersion(

const line = lines[lineNumber];
// `{` will be counted wit +1 and `}` with -1. Therefore if we reach braceCounter == 0. We have found the end of the terraform block
const openBrackets = (line.match(regEx(/\{/g)) || []).length;
const closedBrackets = (line.match(regEx(/\}/g)) || []).length;
const openBrackets = (line.match(regEx(/\{/g)) ?? []).length;
const closedBrackets = (line.match(regEx(/\}/g)) ?? []).length;
braceCounter = braceCounter + openBrackets - closedBrackets;

const kvMatch = keyValueExtractionRegex.exec(line);
Expand Down
4 changes: 2 additions & 2 deletions lib/modules/platform/bitbucket/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,9 @@ describe('modules/platform/bitbucket/index', () => {
repoResp?: any,
existingScope?: httpMock.Scope
): Promise<httpMock.Scope> {
const repository = config?.repository || 'some/repo';
const repository = config?.repository ?? 'some/repo';

const scope = existingScope || httpMock.scope(baseUrl);
const scope = existingScope ?? httpMock.scope(baseUrl);

scope.get(`/2.0/repositories/${repository}`).reply(200, {
owner: {},
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/platform/gitlab/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ describe('modules/platform/gitlab/index', () => {
const justRepo = repo.split('/').slice(0, 2).join('/');
scope.get(`/api/v4/projects/${encodeURIComponent(repo)}`).reply(
200,
repoResp || {
repoResp ?? {
default_branch: 'master',
http_url_to_repo: `https://gitlab.com/${justRepo}.git`,
}
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/versioning/conan/range.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export function fixParsedRange(range: string): any {
major,
};

let full = `${operator || ''}${major}`;
let full = `${operator ?? ''}${major}`;
if (minor) {
NewSemVer.minor = minor;
full = `${full}.${minor}`;
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/versioning/node/schedule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ for (const version of Object.keys(nodeSchedule)) {
export function findScheduleForCodename(
codename: string
): NodeJsScheduleWithVersion | null {
return nodeCodenames.get(codename?.toUpperCase()) || null;
return nodeCodenames.get(codename?.toUpperCase()) ?? null;
}

export function findScheduleForVersion(version: string): NodeJsSchedule | null {
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/versioning/pep440/range.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ function getFutureVersion(
): number[] {
const toRelease: number[] = parseVersion(newVersion)?.release ?? [];
const baseRelease: number[] =
parseVersion(baseVersion || newVersion)?.release ?? [];
parseVersion(baseVersion ?? newVersion)?.release ?? [];
return baseRelease.map((_, index) => {
const toPart: number = toRelease[index] ?? 0;
if (index < policy) {
Expand Down

0 comments on commit 10302eb

Please sign in to comment.