Skip to content

Commit

Permalink
fix: enable prefer-nullish-coalescing eslint rule (podman-desktop#7442)
Browse files Browse the repository at this point in the history
Signed-off-by: lstocchi <[email protected]>
  • Loading branch information
lstocchi authored Jun 5, 2024
1 parent 7729ac2 commit 61eefc7
Show file tree
Hide file tree
Showing 73 changed files with 208 additions and 199 deletions.
1 change: 1 addition & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"@typescript-eslint/no-misused-promises": "error",
"@typescript-eslint/prefer-optional-chain": "error",
"no-null/no-null": "error",
"@typescript-eslint/prefer-nullish-coalescing": ["error", { "ignoreConditionalTests": true }],

/**
* Having a semicolon helps the optimizer interpret your code correctly.
Expand Down
2 changes: 1 addition & 1 deletion extensions/compose/src/compose-github-releases.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export class ComposeGitHubReleases {

return lastReleases.data.map(release => {
return {
label: release.name || release.tag_name,
label: release.name ?? release.tag_name,
tag: release.tag_name,
id: release.id,
};
Expand Down
2 changes: 1 addition & 1 deletion extensions/kind/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ async function updateClusters(
return {
name: clusterName,
status,
apiPort: listeningPort?.PublicPort || 0,
apiPort: listeningPort?.PublicPort ?? 0,
engineType: container.engineType,
engineId: container.engineId,
id: container.Id,
Expand Down
2 changes: 1 addition & 1 deletion extensions/kubectl-cli/src/kubectl-github-releases.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export class KubectlGitHubReleases {
.filter(release => !release.prerelease)
.map(release => {
return {
label: release.name || release.tag_name,
label: release.name ?? release.tag_name,
tag: release.tag_name,
id: release.id,
};
Expand Down
6 changes: 3 additions & 3 deletions extensions/lima/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,9 @@ function registerProvider(
}

export async function activate(extensionContext: extensionApi.ExtensionContext): Promise<void> {
const engineType: string = configuration.getConfiguration('lima').get('type') || 'podman';
const instanceName: string = configuration.getConfiguration('lima').get('name') || engineType;
const socketName: string = configuration.getConfiguration('lima').get('socket') || engineType + '.sock';
const engineType: string = configuration.getConfiguration('lima').get('type') ?? 'podman';
const instanceName: string = configuration.getConfiguration('lima').get('name') ?? engineType;
const socketName: string = configuration.getConfiguration('lima').get('socket') ?? engineType + '.sock';

const limaHome = 'LIMA_HOME' in process.env ? process.env['LIMA_HOME'] : os.homedir() + '/.lima';
const socketPath = path.resolve(limaHome ?? '', instanceName + '/sock/' + socketName);
Expand Down
6 changes: 3 additions & 3 deletions extensions/podman/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1412,7 +1412,7 @@ export async function activate(extensionContext: extensionApi.ExtensionContext):
extensionApi.context.setValue('podmanIsNotInstalled', !installed, 'onboarding');
telemetryLogger?.logUsage('podman.onboarding.checkInstalledCommand', {
status: installed,
version: installation?.version || '',
version: installation?.version ?? '',
});
},
);
Expand All @@ -1424,7 +1424,7 @@ export async function activate(extensionContext: extensionApi.ExtensionContext):
const onboardingCheckReqsCommand = extensionApi.commands.registerCommand(
'podman.onboarding.checkRequirementsCommand',
async () => {
const checks = podmanInstall.getInstallChecks() || [];
const checks = podmanInstall.getInstallChecks() ?? [];
const result = [];
let successful = true;
for (const check of checks) {
Expand Down Expand Up @@ -1494,7 +1494,7 @@ export async function activate(extensionContext: extensionApi.ExtensionContext):
extensionApi.context.setValue('podmanIsNotInstalled', true, 'onboarding');
telemetryOptions.error = e;
} finally {
telemetryOptions.version = installation?.version || '';
telemetryOptions.version = installation?.version ?? '';
telemetryOptions.installed = installed;
telemetryLogger?.logUsage('podman.onboarding.installPodman', telemetryOptions);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/main/src/plugin/authentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ export class AuthenticationImpl {
// request was added already by this extension
return;
}
const requestId = `${providerId}:${requestingExtension.id}:signIn${Object.keys(providerRequests || []).length}`;
const requestId = `${providerId}:${requestingExtension.id}:signIn${Object.keys(providerRequests ?? []).length}`;
this._signInRequestsData.set(requestId, {
id: requestId,
providerId,
Expand Down
6 changes: 3 additions & 3 deletions packages/main/src/plugin/container-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -541,7 +541,7 @@ export class ContainerProviderRegistry {
engineName: provider.name,
engineId: provider.id,
engineType: provider.connection.type,
StartedAt: container.StartedAt || '',
StartedAt: container.StartedAt ?? '',
Status: container.Status,
ImageBase64RepoTag: Buffer.from(container.Image, 'binary').toString('base64'),
};
Expand Down Expand Up @@ -1094,7 +1094,7 @@ export class ContainerProviderRegistry {
try {
const engine = this.getMatchingEngine(engineId);
const image = engine.getImage(imageTag);
const authconfig = authInfo || this.imageRegistry.getAuthconfigForImage(imageTag);
const authconfig = authInfo ?? this.imageRegistry.getAuthconfigForImage(imageTag);
const pushStream = await image.push({
authconfig,
abortSignal: abortController?.signal,
Expand Down Expand Up @@ -1911,7 +1911,7 @@ export class ContainerProviderRegistry {
const envFiles = options.EnvFiles || [];
const envFileContent = await this.getEnvFileParser().parseEnvFiles(envFiles);

const env = options.Env || [];
const env = options.Env ?? [];
env.push(...envFileContent);
options.Env = env;
// remove EnvFiles from options
Expand Down
8 changes: 4 additions & 4 deletions packages/main/src/plugin/contribution-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -585,7 +585,7 @@ export class ContributionManager {
const service = services[serviceKey];

// add custom labels
service.labels = service.labels || {};
service.labels = service.labels ?? {};
service.labels['io.podman_desktop.PodmanDesktop.extension'] = 'true';
service.labels['io.podman_desktop.PodmanDesktop.extensionName'] = extensionName;

Expand All @@ -601,15 +601,15 @@ export class ContributionManager {
}

// apply restart policy if not specified
service.deploy = service.deploy || {};
service.deploy.restart_policy = service.deploy.restart_policy || {};
service.deploy = service.deploy ?? {};
service.deploy.restart_policy = service.deploy.restart_policy ?? {};
if (!service.deploy.restart_policy.condition) {
service.deploy.restart_policy.condition = 'always';
}

// add the volume from the podman-desktop-socket (only if not inside the service itself)
if (serviceKey !== PODMAN_DESKTOP_SOCKET_SERVICE) {
service.volumes_from = service.volumes_from || [];
service.volumes_from = service.volumes_from ?? [];
service.volumes_from.push(PODMAN_DESKTOP_SOCKET_SERVICE);
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/main/src/plugin/directories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export class Directories {
constructor() {
// read ENV VAR to override the Desktop App Home Dir
this.desktopAppHomeDir =
process.env[Directories.PODMAN_DESKTOP_HOME_DIR] || path.resolve(os.homedir(), Directories.XDG_DATA_DIRECTORY);
process.env[Directories.PODMAN_DESKTOP_HOME_DIR] ?? path.resolve(os.homedir(), Directories.XDG_DATA_DIRECTORY);

// create the Desktop App Home Dir if it does not exist
if (!fs.existsSync(this.desktopAppHomeDir)) {
Expand Down
2 changes: 1 addition & 1 deletion packages/main/src/plugin/dockerode/libpod-dockerode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -690,7 +690,7 @@ export class LibpodDockerode {
404: 'no such pod',
500: 'server error',
},
options: options || {},
options: options ?? {},
};

return new Promise((resolve, reject) => {
Expand Down
6 changes: 3 additions & 3 deletions packages/main/src/plugin/events/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class CallbackList implements Iterable<Callback> {
private _contexts: any[] | undefined;

get length(): number {
return this._callbacks?.length || 0;
return this._callbacks?.length ?? 0;
}

public add(callback: Function, context: any = undefined, bucket?: IDisposable[]): void {
Expand Down Expand Up @@ -243,7 +243,7 @@ export class Emitter<T = any> {
}
const stack = new Error().stack?.split('\n').slice(3).join('\n');
if (stack) {
const count = this._leakingStacks.get(stack) || 0;
const count = this._leakingStacks.get(stack) ?? 0;
this._leakingStacks.set(stack, count + 1);
return () => this.popLeakingStack(stack);
}
Expand All @@ -254,7 +254,7 @@ export class Emitter<T = any> {
if (!this._leakingStacks) {
return;
}
const count = this._leakingStacks.get(stack) || 0;
const count = this._leakingStacks.get(stack) ?? 0;
this._leakingStacks.set(stack, count - 1);
}

Expand Down
12 changes: 6 additions & 6 deletions packages/main/src/plugin/extension-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ export class ExtensionLoader {
description: extension.manifest.description,
version: extension.manifest.version,
publisher: extension.manifest.publisher,
state: this.extensionState.get(extension.id) || 'stopped',
state: this.extensionState.get(extension.id) ?? 'stopped',
error: this.mapError(this.extensionStateErrors.get(extension.id)),
id: extension.id,
path: extension.path,
Expand Down Expand Up @@ -915,8 +915,8 @@ export class ExtensionLoader {
return this.notificationRegistry.addNotification({
...notificationInfo,
extensionId: extensionInfo.id,
type: notificationInfo.type || 'info',
title: notificationInfo.title || extensionInfo.name,
type: notificationInfo.type ?? 'info',
title: notificationInfo.title ?? extensionInfo.name,
});
},

Expand Down Expand Up @@ -1167,7 +1167,7 @@ export class ExtensionLoader {
const url = uri.toString();
try {
const result = await securityRestrictionCurrentHandler.handler?.(url);
return result || false;
return !!result;
} catch (error) {
console.error(`Unable to open external link ${uri.toString()} from extension ${extensionInfo.id}`, error);
return false;
Expand Down Expand Up @@ -1346,7 +1346,7 @@ export class ExtensionLoader {
}

// remove children that are part of the plug-in
let i = mod?.children?.length || 0;
let i = mod?.children?.length ?? 0;
while (i--) {
const childMod: NodeJS.Module | undefined = mod?.children[i];
// ensure the child module is not null, is in the plug-in folder, and is not a native module (see above)
Expand All @@ -1364,7 +1364,7 @@ export class ExtensionLoader {
if (key.startsWith(extension.path)) {
// delete the entry
delete require.cache[key];
const ix = mod?.parent?.children.indexOf(mod) || 0;
const ix = mod?.parent?.children.indexOf(mod) ?? 0;
if (ix >= 0) {
mod?.parent?.children.splice(ix, 1);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/main/src/plugin/icon-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export class IconRegistry {
}

// get file extension of the font path
const format = defaultAttributes.fontPath.split('.').pop() || '';
const format = defaultAttributes.fontPath.split('.').pop() ?? '';
if (format !== 'woff2') {
console.warn(
`Expected contributes.icons.default.fontPath to have file extension 'woff2' but found '${format}'."`,
Expand Down
8 changes: 4 additions & 4 deletions packages/main/src/plugin/image-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -513,7 +513,7 @@ export class ImageRegistry {
logger: (message: string) => void,
): Promise<void> {
const options = this.getOptions();
options.headers = options.headers || {};
options.headers = options.headers ?? {};

// add the Bearer token
options.headers.Authorization = `Bearer ${token}`;
Expand Down Expand Up @@ -548,7 +548,7 @@ export class ImageRegistry {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
protected async fetchOciImageConfig(imageData: ImageRegistryNameTag, digest: string, token: string): Promise<any> {
const options = this.getOptions();
options.headers = options.headers || {};
options.headers = options.headers ?? {};
// add the Bearer token
options.headers.Authorization = `Bearer ${token}`;

Expand Down Expand Up @@ -579,7 +579,7 @@ export class ImageRegistry {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<any> {
const options = this.getOptions();
options.headers = options.headers || {};
options.headers = options.headers ?? {};

// add the Bearer token
options.headers.Authorization = `Bearer ${token}`;
Expand Down Expand Up @@ -801,7 +801,7 @@ export class ImageRegistry {
// if we have auth for this registry, add basic auth to the headers
const authServer = this.getAuthconfigForServer(imageData.registry);
if (authServer) {
options.headers = options.headers || {};
options.headers = options.headers ?? {};
const loginAndPassWord = `${authServer.username}:${authServer.password}`;
options.headers.Authorization = `Basic ${Buffer.from(loginAndPassWord).toString('base64')}`;
}
Expand Down
50 changes: 25 additions & 25 deletions packages/main/src/plugin/kubernetes-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,22 +92,22 @@ function toPodInfo(pod: V1Pod, contextName?: string): PodInfo {
const containers =
pod.status?.containerStatuses?.map(status => {
return {
Id: status.containerID || '',
Id: status.containerID ?? '',
Names: status.name,
Status: toContainerStatus(status.state),
};
}) || [];
}) ?? [];
return {
Cgroup: '',
Containers: containers,
Created: (pod.metadata?.creationTimestamp || '').toString(),
Id: pod.metadata?.uid || '',
Created: (pod.metadata?.creationTimestamp ?? '').toString(),
Id: pod.metadata?.uid ?? '',
InfraId: '',
Labels: pod.metadata?.labels || {},
Name: pod.metadata?.name || '',
Namespace: pod.metadata?.namespace || '',
Labels: pod.metadata?.labels ?? {},
Name: pod.metadata?.name ?? '',
Namespace: pod.metadata?.namespace ?? '',
Networks: [],
Status: pod.metadata?.deletionTimestamp ? 'DELETING' : pod.status?.phase || '',
Status: pod.metadata?.deletionTimestamp ? 'DELETING' : pod.status?.phase ?? '',
engineId: contextName ?? 'kubernetes',
engineName: 'Kubernetes',
kind: 'kubernetes',
Expand Down Expand Up @@ -918,47 +918,47 @@ export class KubernetesClient {
if (manifest.kind === 'Namespace') {
return client.createNamespace(manifest);
} else if (manifest.kind === 'Pod') {
return client.createNamespacedPod(optionalNamespace || manifest.metadata.namespace, manifest);
return client.createNamespacedPod(optionalNamespace ?? manifest.metadata.namespace, manifest);
} else if (manifest.kind === 'Service') {
return client.createNamespacedService(optionalNamespace || manifest.metadata.namespace, manifest);
return client.createNamespacedService(optionalNamespace ?? manifest.metadata.namespace, manifest);
} else if (manifest.kind === 'Binding') {
return client.createNamespacedBinding(optionalNamespace || manifest.metadata.namespace, manifest);
return client.createNamespacedBinding(optionalNamespace ?? manifest.metadata.namespace, manifest);
} else if (manifest.kind === 'Event') {
return client.createNamespacedEvent(optionalNamespace || manifest.metadata.namespace, manifest);
return client.createNamespacedEvent(optionalNamespace ?? manifest.metadata.namespace, manifest);
} else if (manifest.kind === 'Endpoints') {
return client.createNamespacedEndpoints(optionalNamespace || manifest.metadata.namespace, manifest);
return client.createNamespacedEndpoints(optionalNamespace ?? manifest.metadata.namespace, manifest);
} else if (manifest.kind === 'ConfigMap') {
return client.createNamespacedConfigMap(optionalNamespace || manifest.metadata.namespace, manifest);
return client.createNamespacedConfigMap(optionalNamespace ?? manifest.metadata.namespace, manifest);
} else if (manifest.kind === 'LimitRange') {
return client.createNamespacedLimitRange(optionalNamespace || manifest.metadata.namespace, manifest);
return client.createNamespacedLimitRange(optionalNamespace ?? manifest.metadata.namespace, manifest);
} else if (manifest.kind === 'PersistentVolumeClaim') {
return client.createNamespacedPersistentVolumeClaim(optionalNamespace || manifest.metadata.namespace, manifest);
return client.createNamespacedPersistentVolumeClaim(optionalNamespace ?? manifest.metadata.namespace, manifest);
} else if (manifest.kind === 'PodBinding') {
return client.createNamespacedPodBinding(
manifest.metadata.name,
optionalNamespace || manifest.metadata.namespace,
optionalNamespace ?? manifest.metadata.namespace,
manifest,
);
} else if (manifest.kind === 'PodEviction') {
return client.createNamespacedPodEviction(
manifest.metadata.name,
optionalNamespace || manifest.metadata.namespace,
optionalNamespace ?? manifest.metadata.namespace,
manifest,
);
} else if (manifest.kind === 'PodTemplate') {
return client.createNamespacedPodTemplate(optionalNamespace || manifest.metadata.namespace, manifest);
return client.createNamespacedPodTemplate(optionalNamespace ?? manifest.metadata.namespace, manifest);
} else if (manifest.kind === 'ReplicationController') {
return client.createNamespacedReplicationController(optionalNamespace || manifest.metadata.namespace, manifest);
return client.createNamespacedReplicationController(optionalNamespace ?? manifest.metadata.namespace, manifest);
} else if (manifest.kind === 'ResourceQuota') {
return client.createNamespacedResourceQuota(optionalNamespace || manifest.metadata.namespace, manifest);
return client.createNamespacedResourceQuota(optionalNamespace ?? manifest.metadata.namespace, manifest);
} else if (manifest.kind === 'Secret') {
return client.createNamespacedSecret(optionalNamespace || manifest.metadata.namespace, manifest);
return client.createNamespacedSecret(optionalNamespace ?? manifest.metadata.namespace, manifest);
} else if (manifest.kind === 'ServiceAccount') {
return client.createNamespacedServiceAccount(optionalNamespace || manifest.metadata.namespace, manifest);
return client.createNamespacedServiceAccount(optionalNamespace ?? manifest.metadata.namespace, manifest);
} else if (manifest.kind === 'ServiceAccountToken') {
return client.createNamespacedServiceAccountToken(
manifest.metadata.name,
optionalNamespace || manifest.metadata.namespace,
optionalNamespace ?? manifest.metadata.namespace,
manifest,
);
}
Expand Down Expand Up @@ -1164,7 +1164,7 @@ export class KubernetesClient {
spec.metadata.annotations['kubectl.kubernetes.io/last-applied-configuration'] = JSON.stringify(spec);

if (!spec.metadata.namespace) {
spec.metadata.namespace = namespace || DEFAULT_NAMESPACE;
spec.metadata.namespace = namespace ?? DEFAULT_NAMESPACE;
}
try {
// try to get the resource, if it does not exist an error will be thrown and we will
Expand Down
8 changes: 4 additions & 4 deletions packages/main/src/plugin/provider-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,10 @@ export class ProviderImpl implements Provider, IDisposable {
this._status = providerOptions.status;
this._version = providerOptions.version;

this._links = providerOptions.links || [];
this._detectionChecks = providerOptions.detectionChecks || [];
this._images = providerOptions.images || {};
this._warnings = providerOptions.warnings || [];
this._links = providerOptions.links ?? [];
this._detectionChecks = providerOptions.detectionChecks ?? [];
this._images = providerOptions.images ?? {};
this._warnings = providerOptions.warnings ?? [];

// monitor connection statuses
setInterval(() => {
Expand Down
Loading

0 comments on commit 61eefc7

Please sign in to comment.