Skip to content

Commit

Permalink
refactor(manager): more strict null checks (#15168)
Browse files Browse the repository at this point in the history
  • Loading branch information
viceice committed Apr 20, 2022
1 parent 7c8c9da commit f5f06c7
Show file tree
Hide file tree
Showing 39 changed files with 314 additions and 243 deletions.
7 changes: 6 additions & 1 deletion lib/modules/manager/composer/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,12 @@ export async function updateArtifacts({
} else {
args =
(
'update ' + updatedDeps.map((dep) => quote(dep.depName)).join(' ')
'update ' +
updatedDeps
.map((dep) => dep.depName)
.filter(is.string)
.map((dep) => quote(dep))
.join(' ')
).trim() + ' --with-dependencies';
}
args += getComposerArguments(config, composerToolConstraint);
Expand Down
14 changes: 8 additions & 6 deletions lib/modules/manager/composer/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type {
ComposerConfig,
ComposerLock,
ComposerManagerData,
ComposerRepositories,
Repo,
} from './types';

Expand All @@ -31,7 +32,7 @@ function transformRegUrl(url: string): string {
* other entries will be added to registryUrls
*/
function parseRepositories(
repoJson: ComposerConfig['repositories'],
repoJson: ComposerRepositories,
repositories: Record<string, Repo>,
registryUrls: string[]
): void {
Expand All @@ -44,7 +45,8 @@ function parseRepositories(
switch (repo.type) {
case 'vcs':
case 'git':
repositories[name] = repo;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
repositories[name!] = repo;
break;
case 'composer':
registryUrls.push(transformRegUrl(repo.url));
Expand Down Expand Up @@ -95,7 +97,7 @@ export async function extractPackageFile(
// handle lockfile
const lockfilePath = fileName.replace(regEx(/\.json$/), '.lock');
const lockContents = await readLocalFile(lockfilePath, 'utf8');
let lockParsed: ComposerLock;
let lockParsed: ComposerLock | undefined;
if (lockContents) {
logger.debug({ packageFile: fileName }, 'Found composer lock file');
res.lockFiles = [lockfilePath];
Expand All @@ -114,13 +116,13 @@ export async function extractPackageFile(
res.registryUrls = registryUrls;
}

const deps = [];
const depTypes = ['require', 'require-dev'];
const deps: PackageDependency[] = [];
const depTypes: ('require' | 'require-dev')[] = ['require', 'require-dev'];
for (const depType of depTypes) {
if (composerJson[depType]) {
try {
for (const [depName, version] of Object.entries(
composerJson[depType] as Record<string, string>
composerJson[depType]!
)) {
const currentValue = version.trim();
// Default datasource and packageName
Expand Down
5 changes: 4 additions & 1 deletion lib/modules/manager/composer/range.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,10 @@ export function getRangeStrategy(config: RangeConfig): RangeStrategy {
logger.trace({ dependency: depName }, 'Pinning app require');
return 'pin';
}
if (isComplexRange || ['typo3-cms-extension'].includes(composerJsonType)) {
if (
isComplexRange ||
(composerJsonType && ['typo3-cms-extension'].includes(composerJsonType))
) {
return 'widen';
}
return 'replace';
Expand Down
4 changes: 3 additions & 1 deletion lib/modules/manager/composer/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ export interface Repo {
'packagist.org'?: boolean;
url: string;
}
export type ComposerRepositories = Record<string, Repo | boolean> | Repo[];

export interface ComposerConfig {
type?: string;
/**
Expand All @@ -25,7 +27,7 @@ export interface ComposerConfig {
* (Yes this can be confusing, as it is also not properly documented in the composer docs)
* See https://getcomposer.org/doc/05-repositories.md#disabling-packagist-org
*/
repositories?: Record<string, Repo | boolean> | Repo[];
repositories?: ComposerRepositories;

require?: Record<string, string>;
'require-dev'?: Record<string, string>;
Expand Down
6 changes: 4 additions & 2 deletions lib/modules/manager/composer/update-locked.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@ export function updateLockedDependency(
`composer.updateLockedDependency: ${depName}@${currentVersion} -> ${newVersion} [${lockFile}]`
);
try {
const locked = JSON.parse(lockFileContent) as ComposerLock;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const locked = JSON.parse(lockFileContent!) as ComposerLock;
if (
locked.packages?.find(
(entry) =>
entry.name === depName &&
composer.equals(entry.version || '', newVersion)
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
composer.equals(entry.version || '', newVersion!)
)
) {
return { status: 'already-updated' };
Expand Down
11 changes: 8 additions & 3 deletions lib/modules/manager/composer/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,11 @@ export function getComposerArguments(

if (config.composerIgnorePlatformReqs) {
if (config.composerIgnorePlatformReqs.length === 0) {
const major = api.getMajor(toolConstraint.constraint);
const minor = api.getMinor(toolConstraint.constraint);
// TODO: toolConstraint.constraint can be null or undefined?
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const major = api.getMajor(toolConstraint.constraint!);
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const minor = api.getMinor(toolConstraint.constraint!);
args += api.matches(`${major}.${minor}`, '^2.2')
? " --ignore-platform-req='ext-*' --ignore-platform-req='lib-*'"
: ' --ignore-platform-reqs';
Expand All @@ -42,7 +45,9 @@ export function getComposerArguments(
return args;
}

export function getPhpConstraint(constraints: Record<string, string>): string {
export function getPhpConstraint(
constraints: Record<string, string>
): string | null {
const { php } = constraints;

if (php) {
Expand Down
3 changes: 2 additions & 1 deletion lib/modules/manager/git-submodules/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ export default function updateArtifacts({
updatedDeps.forEach((dep) => {
logger.info('Updating submodule ' + dep.depName);
res.push({
file: { type: 'addition', path: dep.depName, contents: '' },
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
file: { type: 'addition', path: dep.depName!, contents: '' },
});
});
return res;
Expand Down
6 changes: 4 additions & 2 deletions lib/modules/manager/git-submodules/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ export default async function updateDependency({
const submoduleGit = Git(upath.join(localDir, upgrade.depName));

try {
await git.submoduleUpdate(['--init', upgrade.depName]);
await submoduleGit.checkout([upgrade.newDigest]);
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
await git.submoduleUpdate(['--init', upgrade.depName!]);
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
await submoduleGit.checkout([upgrade.newDigest!]);
return fileContent;
} catch (err) {
logger.debug({ err }, 'submodule checkout error');
Expand Down
20 changes: 12 additions & 8 deletions lib/modules/manager/gomod/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ function getGitEnvironmentVariables(): NodeJS.ProcessEnv {
// get extra host rules for other git-based Go Module hosts
const hostRules = getAll() || [];

const goGitAllowedHostType: string[] = [
const goGitAllowedHostType: (string | undefined)[] = [
// All known git platforms
PlatformId.Azure,
PlatformId.Bitbucket,
Expand All @@ -62,13 +62,15 @@ function getGitEnvironmentVariables(): NodeJS.ProcessEnv {
hostRule.matchHost &&
goGitAllowedHostType.includes(hostRule.hostType)
) {
const httpUrl = createURLFromHostOrURL(hostRule.matchHost).toString();
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const httpUrl = createURLFromHostOrURL(hostRule.matchHost!)?.toString();
if (validateUrl(httpUrl)) {
logger.debug(
`Adding Git authentication for Go Module retrieval for ${httpUrl} using token auth.`
);
environmentVariables = getGitAuthenticatedEnvironmentVariables(
httpUrl,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
httpUrl!,
hostRule,
environmentVariables
);
Expand All @@ -87,7 +89,8 @@ function getUpdateImportPathCmds(
{ constraints, newMajor }: UpdateArtifactsConfig
): string[] {
const updateImportCommands = updatedDeps
.map((dep) => dep.depName)
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
.map((dep) => dep.depName!)
.filter((x) => !x.startsWith('gopkg.in'))
.map((depName) => `mod upgrade --mod-name=${depName} -t=${newMajor}`);

Expand Down Expand Up @@ -121,7 +124,7 @@ function getUpdateImportPathCmds(
return updateImportCommands;
}

function useModcacherw(goVersion: string): boolean {
function useModcacherw(goVersion: string | undefined): boolean {
if (!is.string(goVersion)) {
return true;
}
Expand Down Expand Up @@ -179,7 +182,7 @@ export async function updateArtifacts({
* @param match A string representing a golang replace directive block
* @returns A commented out block with // renovate-replace
*/
const blockCommentOut = (match): string =>
const blockCommentOut = (match: string): string =>
match.replace(/(\r?\n)/g, '$1// renovate-replace ');

// Comment out golang replace directives
Expand Down Expand Up @@ -213,7 +216,7 @@ export async function updateArtifacts({
},
};

const execCommands = [];
const execCommands: string[] = [];

let args = 'get -d -t ./...';
logger.debug({ cmd, args }, 'go get command included');
Expand All @@ -223,7 +226,8 @@ export async function updateArtifacts({
const isImportPathUpdateRequired =
config.postUpdateOptions?.includes('gomodUpdateImportPaths') &&
config.updateType === 'major' &&
config.newMajor > 1;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
config.newMajor! > 1;
if (isImportPathUpdateRequired) {
const updateImportCmds = getUpdateImportPathCmds(updatedDeps, config);
if (updateImportCmds.length > 0) {
Expand Down
3 changes: 2 additions & 1 deletion lib/modules/manager/gomod/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ export function extractPackageFile(content: string): PackageFile | null {
if (multiMatch && !line.endsWith('// indirect')) {
logger.trace({ lineNumber }, `require line: "${line}"`);
const dep = getDep(lineNumber, multiMatch, 'require');
dep.managerData.multiLine = true;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
dep.managerData!.multiLine = true;
deps.push(dep);
} else if (line.trim() !== ')') {
logger.debug(`No multi-line match: ${line}`);
Expand Down
29 changes: 21 additions & 8 deletions lib/modules/manager/gomod/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ export function updateDependency({
logger.warn('gomod manager does not support replacement updates yet');
return null;
}
// istanbul ignore if: should never happen
if (!depName || !upgrade.managerData) {
return null;
}
const depNameNoVersion = getDepNameWithNoVersion(depName);
const lines = fileContent.split(newlineRegex);
const lineToChange = lines[upgrade.managerData.lineNumber];
Expand All @@ -34,7 +38,7 @@ export function updateDependency({
);
return null;
}
let updateLineExp: RegExp;
let updateLineExp: RegExp | undefined;
if (depType === 'replace') {
updateLineExp = regEx(
/^(?<depPart>replace\s+[^\s]+[\s]+[=][>]+\s+)(?<divider>[^\s]+\s+)[^\s]+/
Expand All @@ -54,9 +58,11 @@ export function updateDependency({
}
let newLine: string;
if (upgrade.updateType === 'digest') {
const newDigestRightSized = upgrade.newDigest.substring(
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const newDigestRightSized = upgrade.newDigest!.substring(
0,
upgrade.currentDigest.length
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
upgrade.currentDigest!.length
);
if (lineToChange.includes(newDigestRightSized)) {
return fileContent;
Expand All @@ -66,12 +72,16 @@ export function updateDependency({
'gomod: need to update digest'
);
newLine = lineToChange.replace(
updateLineExp,
// TODO: can be undefined?
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
updateLineExp!,
`$<depPart>$<divider>${newDigestRightSized}`
);
} else {
newLine = lineToChange.replace(
updateLineExp,
// TODO: can be undefined?
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
updateLineExp!,
`$<depPart>$<divider>${upgrade.newValue}`
);
}
Expand All @@ -86,15 +96,17 @@ export function updateDependency({
'rethinkdb/rethinkdb-go.v5'
);
} else if (
upgrade.newMajor > 1 &&
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
upgrade.newMajor! > 1 &&
!newLine.includes(`/v${upgrade.newMajor}`)
) {
if (depName === depNameNoVersion) {
// If package currently has no version, pin to latest one.
newLine = newLine.replace(depName, `${depName}/v${upgrade.newMajor}`);
} else {
// Replace version
const [oldV] = upgrade.currentValue.split('.');
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const [oldV] = upgrade.currentValue!.split('.');
newLine = newLine.replace(
regEx(`/${oldV}(\\s+)`, undefined, false),
`/v${upgrade.newMajor}$1`
Expand All @@ -105,7 +117,8 @@ export function updateDependency({
if (lineToChange.endsWith('+incompatible')) {
let toAdd = '+incompatible';

if (upgrade.updateType === 'major' && upgrade.newMajor >= 2) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
if (upgrade.updateType === 'major' && upgrade.newMajor! >= 2) {
toAdd = '';
}
newLine += toAdd;
Expand Down
16 changes: 10 additions & 6 deletions lib/modules/manager/gradle-wrapper/artifacts.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import is from '@sindresorhus/is';
import { quote } from 'shlex';
import upath from 'upath';
import { GlobalConfig } from '../../../config/global';
Expand Down Expand Up @@ -37,7 +38,7 @@ async function addIfUpdated(
return null;
}

function getDistributionUrl(newPackageFileContent: string): string {
function getDistributionUrl(newPackageFileContent: string): string | null {
const distributionUrlLine = newPackageFileContent
.split(newlineRegex)
.find((line) => line.startsWith('distributionUrl='));
Expand Down Expand Up @@ -67,7 +68,8 @@ export async function updateArtifacts({
const gradlewPath = upath.resolve(projectDir, `./${gradlew}`);
let cmd = await prepareGradleCommand(
gradlew,
projectDir,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
projectDir!,
await stat(gradlewPath).catch(() => null),
`wrapper`
);
Expand All @@ -91,14 +93,16 @@ export async function updateArtifacts({
cmd += ` --gradle-distribution-sha256-sum ${quote(checksum)}`;
}
} else {
cmd += ` --gradle-version ${quote(config.newValue)}`;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
cmd += ` --gradle-version ${quote(config.newValue!)}`;
}
logger.debug(`Updating gradle wrapper: "${cmd}"`);
const execOptions: ExecOptions = {
docker: {
image: 'java',
tagConstraint:
config.constraints?.java ?? getJavaContraint(config.currentValue),
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
config.constraints?.java ?? getJavaContraint(config.currentValue!),
tagScheme: getJavaVersioning(),
},
extraEnv,
Expand Down Expand Up @@ -133,9 +137,9 @@ export async function updateArtifacts({
addIfUpdated(status, fileProjectPath)
)
)
).filter(Boolean);
).filter(is.truthy);
logger.debug(
{ files: updateArtifactsResult.map((r) => r.file.path) },
{ files: updateArtifactsResult.map((r) => r.file?.path) },
`Returning updated gradle-wrapper files`
);
return updateArtifactsResult;
Expand Down

0 comments on commit f5f06c7

Please sign in to comment.