Skip to content

Commit

Permalink
refactor: fix nullable types (#16156)
Browse files Browse the repository at this point in the history
* refactor: fix nullable types

* chore: revert changes

* chore: fix lint comments

* chore: revert changes
  • Loading branch information
viceice committed Jun 20, 2022
1 parent b431992 commit 0a582d3
Show file tree
Hide file tree
Showing 26 changed files with 107 additions and 61 deletions.
4 changes: 3 additions & 1 deletion lib/modules/manager/batect/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,9 @@ export async function extractAllPackageFiles(
filesAlreadyExamined.add(packageFile);

const content = await readLocalFile(packageFile, 'utf8');
const result = extractPackageFile(content, packageFile);
// TODO #7154
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const result = extractPackageFile(content!, packageFile);

if (result !== null) {
result.referencedConfigFiles.forEach((f) => {
Expand Down
14 changes: 7 additions & 7 deletions lib/modules/manager/bundler/artifacts.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ describe('modules/manager/bundler/artifacts', () => {

it('returns null if Gemfile.lock was not changed', async () => {
fs.readLocalFile.mockResolvedValueOnce('Current Gemfile.lock');
fs.writeLocalFile.mockResolvedValueOnce(null as never);
fs.writeLocalFile.mockResolvedValueOnce();
const execSnapshots = mockExecAll(exec);
git.getRepoStatus.mockResolvedValueOnce({
modified: [] as string[],
Expand All @@ -89,13 +89,13 @@ describe('modules/manager/bundler/artifacts', () => {

it('works for default binarySource', async () => {
fs.readLocalFile.mockResolvedValueOnce('Current Gemfile.lock');
fs.writeLocalFile.mockResolvedValueOnce(null as never);
fs.readLocalFile.mockResolvedValueOnce(null as never);
fs.writeLocalFile.mockResolvedValueOnce();
fs.readLocalFile.mockResolvedValueOnce(null);
const execSnapshots = mockExecAll(exec);
git.getRepoStatus.mockResolvedValueOnce({
modified: ['Gemfile.lock'],
} as StatusResult);
fs.readLocalFile.mockResolvedValueOnce('Updated Gemfile.lock' as any);
fs.readLocalFile.mockResolvedValueOnce('Updated Gemfile.lock');
expect(
await updateArtifacts({
packageFileName: 'Gemfile',
Expand All @@ -110,13 +110,13 @@ describe('modules/manager/bundler/artifacts', () => {
it('works explicit global binarySource', async () => {
GlobalConfig.set({ ...adminConfig, binarySource: 'global' });
fs.readLocalFile.mockResolvedValueOnce('Current Gemfile.lock');
fs.writeLocalFile.mockResolvedValueOnce(null as never);
fs.readLocalFile.mockResolvedValueOnce(null as never);
fs.writeLocalFile.mockResolvedValueOnce();
fs.readLocalFile.mockResolvedValueOnce(null);
const execSnapshots = mockExecAll(exec);
git.getRepoStatus.mockResolvedValueOnce({
modified: ['Gemfile.lock'],
} as StatusResult);
fs.readLocalFile.mockResolvedValueOnce('Updated Gemfile.lock' as any);
fs.readLocalFile.mockResolvedValueOnce('Updated Gemfile.lock');
expect(
await updateArtifacts({
packageFileName: 'Gemfile',
Expand Down
6 changes: 4 additions & 2 deletions lib/modules/manager/flux/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ function resolveManifest(
rep.kind === release.spec.chart.spec.sourceRef?.kind &&
rep.metadata.name === release.spec.chart.spec.sourceRef.name &&
rep.metadata.namespace ===
(release.spec.chart.spec.sourceRef.namespace ||
(release.spec.chart.spec.sourceRef.namespace ??
release.metadata?.namespace)
);
if (matchingRepositories.length) {
Expand Down Expand Up @@ -140,7 +140,9 @@ export async function extractAllPackageFiles(

for (const file of packageFiles) {
const content = await readLocalFile(file, 'utf8');
const manifest = readManifest(content, file);
// TODO #7154
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const manifest = readManifest(content!, file);
if (manifest) {
manifests.push(manifest);
}
Expand Down
3 changes: 2 additions & 1 deletion lib/modules/manager/gomod/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,8 @@ export async function updateArtifacts({
}
}

const finalGoModContent = (await readLocalFile(goModFileName, 'utf8'))
// TODO #7154
const finalGoModContent = (await readLocalFile(goModFileName, 'utf8'))!
.replace(regEx(/\/\/ renovate-replace /g), '')
.replace(regEx(/renovate-replace-bracket/g), ')');
if (finalGoModContent !== newGoModContent) {
Expand Down
5 changes: 3 additions & 2 deletions lib/modules/manager/gradle/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ export async function extractAllPackageFiles(
};

try {
const content = await readLocalFile(packageFile, 'utf8');
// TODO #7154
const content = (await readLocalFile(packageFile, 'utf8'))!;
const dir = upath.dirname(toAbsolutePath(packageFile));

const updateVars = (newVars: PackageVariables): void => {
Expand Down Expand Up @@ -106,7 +107,7 @@ export async function extractAllPackageFiles(
registryUrls: [
...new Set([
...defaultRegistryUrls,
...(dep.registryUrls || []),
...(dep.registryUrls ?? []),
...registryUrls,
]),
],
Expand Down
12 changes: 10 additions & 2 deletions lib/modules/manager/jsonnet-bundler/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,20 @@ export async function updateArtifacts(

for (const f of status.modified ?? []) {
res.push({
file: { type: 'addition', path: f, contents: await readLocalFile(f) },
file: {
type: 'addition',
path: f,
contents: await readLocalFile(f),
},
});
}
for (const f of status.not_added ?? []) {
res.push({
file: { type: 'addition', path: f, contents: await readLocalFile(f) },
file: {
type: 'addition',
path: f,
contents: await readLocalFile(f),
},
});
}
for (const f of status.deleted ?? []) {
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/manager/mix/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export async function updateArtifacts({
}

const lockFileName =
(await findLocalSiblingOrParent(packageFileName, 'mix.lock')) || 'mix.lock';
(await findLocalSiblingOrParent(packageFileName, 'mix.lock')) ?? 'mix.lock';
try {
await writeLocalFile(packageFileName, newPackageFileContent);
} catch (err) {
Expand Down
7 changes: 4 additions & 3 deletions lib/modules/manager/npm/extract/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export async function extractPackageFile(
lockFiles[key] = undefined;
}
}
lockFiles.npmLock = lockFiles.packageLock || lockFiles.shrinkwrapJson;
lockFiles.npmLock = lockFiles.packageLock ?? lockFiles.shrinkwrapJson;
delete lockFiles.packageLock;
delete lockFiles.shrinkwrapJson;

Expand All @@ -109,7 +109,7 @@ export async function extractPackageFile(
'Repo .npmrc file is ignored due to config.npmrc with config.npmrcMerge=false'
);
} else {
npmrc = config.npmrc || '';
npmrc = config.npmrc ?? '';
if (npmrc.length) {
if (!npmrc.endsWith('\n')) {
npmrc += '\n';
Expand Down Expand Up @@ -152,7 +152,8 @@ export async function extractPackageFile(
| undefined;
try {
lernaJsonFile = getSiblingFileName(fileName, 'lerna.json');
lernaJson = JSON.parse(await readLocalFile(lernaJsonFile, 'utf8'));
// TODO #7154
lernaJson = JSON.parse((await readLocalFile(lernaJsonFile, 'utf8'))!);
} catch (err) /* istanbul ignore next */ {
logger.warn({ err }, 'Could not parse lerna.json');
}
Expand Down
3 changes: 2 additions & 1 deletion lib/modules/manager/npm/extract/npm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { readLocalFile } from '../../../../util/fs';
import type { LockFile, LockFileEntry } from './types';

export async function getNpmLock(filePath: string): Promise<LockFile> {
const lockRaw = await readLocalFile(filePath, 'utf8');
// TODO #7154
const lockRaw = (await readLocalFile(filePath, 'utf8'))!;
try {
const lockParsed = JSON.parse(lockRaw);
const lockedVersions: Record<string, string> = {};
Expand Down
3 changes: 2 additions & 1 deletion lib/modules/manager/npm/extract/pnpm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ export async function extractPnpmFilters(
fileName: string
): Promise<string[] | undefined> {
try {
const contents = load(await readLocalFile(fileName, 'utf8'), {
// TODO #7154
const contents = load((await readLocalFile(fileName, 'utf8'))!, {
json: true,
}) as PnpmWorkspaceFile;
if (
Expand Down
3 changes: 2 additions & 1 deletion lib/modules/manager/npm/extract/yarn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import {
import type { LockFile } from './types';

export async function getYarnLock(filePath: string): Promise<LockFile> {
const yarnLockRaw = await readLocalFile(filePath, 'utf8');
// TODO #7154
const yarnLockRaw = (await readLocalFile(filePath, 'utf8'))!;
try {
const parsed = parseSyml(yarnLockRaw);
const lockedVersions: Record<string, string> = {};
Expand Down
34 changes: 22 additions & 12 deletions lib/modules/manager/npm/post-update/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ export async function writeExistingFiles(
const basedir =
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
upath.dirname(packageFile.packageFile!);
const npmrc: string = packageFile.npmrc || config.npmrc;
const npmrc: string = packageFile.npmrc ?? config.npmrc;
const npmrcFilename = upath.join(basedir, '.npmrc');
if (is.string(npmrc)) {
try {
Expand Down Expand Up @@ -257,16 +257,23 @@ export async function writeUpdatedPackageFiles(
supportedLockFiles.some((fileName) => packageFile.path.endsWith(fileName))
) {
logger.debug(`Writing lock file: ${packageFile.path}`);
await writeLocalFile(packageFile.path, packageFile.contents);
// TODO #7154
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
await writeLocalFile(packageFile.path, packageFile.contents!);
continue;
}
if (!packageFile.path.endsWith('package.json')) {
continue;
}
logger.debug(`Writing ${packageFile.path}`);
const detectedIndent =
detectIndent(packageFile.contents.toString()).indent || ' ';
const massagedFile = JSON.parse(packageFile.contents.toString());
// TODO #7154
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
detectIndent(packageFile.contents!.toString()).indent || ' ';

// TODO #7154
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const massagedFile = JSON.parse(packageFile.contents!.toString());
try {
const { token } = hostRules.find({
hostType: 'github',
Expand Down Expand Up @@ -406,8 +413,8 @@ async function updateYarnOffline(
export async function updateYarnBinary(
lockFileDir: string,
updatedArtifacts: FileChange[],
existingYarnrcYmlContent: string | undefined
): Promise<string | undefined> {
existingYarnrcYmlContent: string | undefined | null
): Promise<string | undefined | null> {
let yarnrcYml = existingYarnrcYmlContent;
try {
const yarnrcYmlFilename = upath.join(lockFileDir, '.yarnrc.yml');
Expand Down Expand Up @@ -465,7 +472,7 @@ export async function getAdditionalFiles(
!config.updatedPackageFiles?.length &&
config.transitiveRemediation &&
config.upgrades?.every(
(upgrade) => upgrade.isRemediation || upgrade.isVulnerabilityAlert
(upgrade) => upgrade.isRemediation ?? upgrade.isVulnerabilityAlert
)
) {
logger.debug('Skipping lock file generation for remediations');
Expand Down Expand Up @@ -581,7 +588,7 @@ export async function getAdditionalFiles(
const npmrcContent = await getNpmrcContent(lockFileDir);
await updateNpmrcContent(lockFileDir, npmrcContent, additionalNpmrcContent);
let yarnRcYmlFilename: string | undefined;
let existingYarnrcYmlContent: string | undefined;
let existingYarnrcYmlContent: string | undefined | null;
// istanbul ignore if: needs test
if (additionalYarnRcYml) {
yarnRcYmlFilename = getSiblingFileName(yarnLock, '.yarnrc.yml');
Expand Down Expand Up @@ -635,6 +642,8 @@ export async function getAdditionalFiles(
}
artifactErrors.push({
lockFile: yarnLock,
// TODO #7154

stderr: res.stderr || res.stdout,
});
} else {
Expand Down Expand Up @@ -706,6 +715,7 @@ export async function getAdditionalFiles(
}
artifactErrors.push({
lockFile: pnpmShrinkwrap,
// TODO #7154
stderr: res.stderr || res.stdout,
});
} else {
Expand Down Expand Up @@ -742,9 +752,9 @@ export async function getAdditionalFiles(
throw new Error('lerna-no-lockfile');
}
if (lernaPackageFile.lernaClient === 'npm') {
lockFile = config.npmLock || 'package-lock.json';
lockFile = config.npmLock ?? 'package-lock.json';
} else {
lockFile = config.yarnLock || 'yarn.lock';
lockFile = config.yarnLock ?? 'yarn.lock';
}
const skipInstalls =
lockFile === 'npm-shrinkwrap.json' ? false : config.skipInstalls;
Expand Down Expand Up @@ -811,8 +821,8 @@ export async function getAdditionalFiles(
});
} else {
for (const packageFile of packageFiles.npm) {
const filename = packageFile.npmLock || packageFile.yarnLock;
logger.trace('Checking for ' + filename);
const filename = packageFile.npmLock ?? packageFile.yarnLock;
logger.trace(`Checking for ${filename}`);
const existingContent = await getFile(
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
filename!,
Expand Down
7 changes: 4 additions & 3 deletions lib/modules/manager/npm/post-update/node-version.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import type { PostUpdateConfig, Upgrade } from '../../types';

async function getNodeFile(filename: string): Promise<string | null> {
try {
const constraint = (await readLocalFile(filename, 'utf8'))
// TODO #7154
const constraint = (await readLocalFile(filename, 'utf8'))!
.split(newlineRegex)[0]
.replace(regEx(/^v/), '');
if (semver.validRange(constraint)) {
Expand Down Expand Up @@ -35,8 +36,8 @@ export async function getNodeConstraint(
): Promise<string | null> {
const { packageFile } = config;
const constraint =
(await getNodeFile(getSiblingFileName(packageFile, '.nvmrc'))) ||
(await getNodeFile(getSiblingFileName(packageFile, '.node-version'))) ||
(await getNodeFile(getSiblingFileName(packageFile, '.nvmrc'))) ??
(await getNodeFile(getSiblingFileName(packageFile, '.node-version'))) ??
getPackageJsonConstraint(config);
if (!constraint) {
logger.debug('No node constraint found - using latest');
Expand Down
6 changes: 5 additions & 1 deletion lib/modules/manager/npm/post-update/npm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,11 @@ export async function generateLockFile(
}

// Read the result
lockFile = await readLocalFile(upath.join(lockFileDir, filename), 'utf8');
// TODO #7154
lockFile = (await readLocalFile(
upath.join(lockFileDir, filename),
'utf8'
))!;

// Massage lockfile counterparts of package.json that were modified
// because npm install was called with an explicit version for rangeStrategy=update-lockfile
Expand Down
4 changes: 3 additions & 1 deletion lib/modules/manager/nuget/package-tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ export async function getDependentPackageFiles(
for (const f of packageFiles) {
const packageFileContent = await readLocalFile(f, 'utf8');

const doc = new xmldoc.XmlDocument(packageFileContent);
// TODO #7154
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const doc = new xmldoc.XmlDocument(packageFileContent!);
const projectReferenceAttributes = doc
.childrenNamed('ItemGroup')
.map((ig) => ig.childrenNamed('ProjectReference'))
Expand Down
3 changes: 2 additions & 1 deletion lib/modules/manager/nuget/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ async function readFileAsXmlDocument(
file: string
): Promise<XmlDocument | undefined> {
try {
return new XmlDocument(await readLocalFile(file, 'utf8'));
// TODO #7154
return new XmlDocument((await readLocalFile(file, 'utf8'))!);
} catch (err) {
logger.debug({ err }, `failed to parse '${file}' as XML document`);
return undefined;
Expand Down
4 changes: 2 additions & 2 deletions lib/modules/manager/poetry/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ function getPoetrySources(content: string, fileName: string): PoetrySource[] {
return [];
}

const sources = pyprojectFile.tool?.poetry?.source || [];
const sources = pyprojectFile.tool?.poetry?.source ?? [];
const sourceArray: PoetrySource[] = [];
for (const source of sources) {
if (source.name && source.url) {
Expand Down Expand Up @@ -174,7 +174,7 @@ export async function updateArtifacts({
}
const tagConstraint = getPythonConstraint(existingLockFileContent, config);
const constraint =
config.constraints?.poetry || getPoetryRequirement(newPackageFileContent);
config.constraints?.poetry ?? getPoetryRequirement(newPackageFileContent);
const extraEnv = getSourceCredentialVars(
newPackageFileContent,
packageFileName
Expand Down
5 changes: 3 additions & 2 deletions lib/modules/manager/poetry/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ function extractRegistries(pyprojectfile: PoetryFile): string[] | undefined {
registryUrls.add(source.url);
}
}
registryUrls.add(process.env.PIP_INDEX_URL || 'https://pypi.org/pypi/');
registryUrls.add(process.env.PIP_INDEX_URL ?? 'https://pypi.org/pypi/');

return Array.from(registryUrls);
}
Expand All @@ -115,7 +115,8 @@ export async function extractPackageFile(

// handle the lockfile
const lockfileName = getSiblingFileName(fileName, 'poetry.lock');
const lockContents = await readLocalFile(lockfileName, 'utf8');
// TODO #7154
const lockContents = (await readLocalFile(lockfileName, 'utf8'))!;

const lockfileMapping = extractLockFileEntries(lockContents);

Expand Down
2 changes: 1 addition & 1 deletion lib/modules/manager/terraform/lockfile/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export function findLockFile(packageFilePath: string): string {
return getSiblingFileName(packageFilePath, lockFile);
}

export function readLockFile(lockFilePath: string): Promise<string> {
export function readLockFile(lockFilePath: string): Promise<string | null> {
return readLocalFile(lockFilePath, 'utf8');
}

Expand Down

0 comments on commit 0a582d3

Please sign in to comment.