Repository: lerna-lite/lerna-lite
Pull request #1011 (2025-04-12 21:08:43)

refactor: improve codes
This PR removes some unnecessary checks/optional-chaining and wrong await 

codecov[bot]: ## [Codecov](https://app.codecov.io/gh/lerna-lite/lerna-lite/pull/1011?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=lerna-lite) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 97.85%. Comparing base [(`b35bee4`)](https://app.codecov.io/gh/lerna-lite/lerna-lite/commit/b35bee42d6e0e6414f4d5bb7f606bf7961bb0ce0?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=lerna-lite) to head [(`860f891`)](https://app.codecov.io/gh/lerna-lite/lerna-lite/commit/860f8918dc69bf1f2bd1d0c3c764e43eb52acbe3?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=lerna-lite).

<details><summary>Additional details and impacted files</summary>


```diff
@@            Coverage Diff             @@
##             main    #1011      +/-   ##
==========================================
- Coverage   97.93%   97.85%   -0.07%     
==========================================
  Files         153      153              
  Lines        9064     9062       -2     
  Branches     2316     2315       -1     
==========================================
- Hits         8876     8867       -9     
- Misses        187      194       +7     
  Partials        1        1              
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/lerna-lite/lerna-lite/pull/1011?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=lerna-lite).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=lerna-lite).

<details><summary> :rocket: New features to boost your workflow: </summary>

- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>

Patch:
diff --git a/packages/core/src/package.ts b/packages/core/src/package.ts
index 9ed7fd71..e2401750 100644
--- a/packages/core/src/package.ts
+++ b/packages/core/src/package.ts
@@ -82,9 +82,9 @@ export class Package {
    */
   constructor(pkg: RawManifest, location: string, rootPath = location) {
     // npa will throw an error if the name is invalid
-    const resolved = npa.resolve(pkg?.name ?? '', `file:${relative(rootPath, location)}`, rootPath);
+    const resolved = npa.resolve(pkg.name ?? '', `file:${relative(rootPath, location)}`, rootPath);
 
-    this.name = pkg?.name ?? '';
+    this.name = pkg.name ?? '';
     this[PKG] = pkg;
 
     // omit raw pkg from default util.inspect() output, but preserve internal mutability
@@ -260,7 +260,7 @@ export class Package {
    */
   removeDependencyWorkspaceProtocolPrefix(pkgName: string, resolved: NpaResolveResult) {
     const depName = resolved.name as string;
-    const workspaceSpec = resolved?.workspaceSpec ?? '';
+    const workspaceSpec = resolved.workspaceSpec ?? '';
     const inspectDependencies = this.retrieveAllDependenciesWithName(depName, [
       'dependencies',
       'devDependencies',
@@ -363,9 +363,9 @@ export class Package {
 
         // when using explicit `workspace:` protocol
         if (resolved.workspaceSpec) {
-          const workspaceSpec = resolved?.workspaceSpec ?? '';
+          const workspaceSpec = resolved.workspaceSpec ?? '';
           const [_, _wsTxt, operatorPrefix, rangePrefix, semver] =
-            workspaceSpec.match(/^(workspace:)?([<>=]{0,2})?([*|~|^])?(.*)$/) || [];
+            workspaceSpec.match(/^(workspace:)?([<>=]{0,2})?([*~^])?(.*)$/) || [];
 
           if (operatorPrefix) {
             // package with range operator should never be bumped, we'll use same version range but without prefix "workspace:>=1.2.3" will assign ">=1.2.3"
@@ -391,7 +391,7 @@ export class Package {
             // when versioning we'll only bump workspace protocol that have semver range like `workspace:^1.2.3`
             // any other workspace will remain the same in `package.json` file, for example `workspace:^`
             // keep target workspace or bump when it's a workspace semver range (like `workspace:^1.2.3`)
-            depCollection[depName] = /^workspace:[*|~|^]{1}$/.test(workspaceSpec)
+            depCollection[depName] = /^workspace:[*~^]{1}$/.test(workspaceSpec)
               ? (resolved.workspaceSpec as string) // target like `workspace:^` => `workspace:^` (remains untouched in package.json)
               : `workspace:${depCollection[depName]}`; // range like `workspace:^1.2.3` => `workspace:^1.3.3` (bump minor example)
           }
diff --git a/packages/core/src/utils/describe-ref.ts b/packages/core/src/utils/describe-ref.ts
index 5ef1d0e3..579b5def 100644
--- a/packages/core/src/utils/describe-ref.ts
+++ b/packages/core/src/utils/describe-ref.ts
@@ -48,8 +48,8 @@ function describeRef(
   return promise.then(({ stdout } = { stdout: '' }) => {
     const result = parse(stdout, options.cwd, options.separator);
 
-    if (options?.match) {
-      log.verbose('git-describe', '%j => %j', options?.match, stdout);
+    if (options.match) {
+      log.verbose('git-describe', '%j => %j', options.match, stdout);
     }
     if (stdout) {
       log.silly('git-describe', 'parsed => %j', result);
@@ -71,8 +71,8 @@ function describeRefSync(
   const stdout = execSync('git', getArgs(options, includeMergedTags), options, dryRun);
   const result = parse(stdout, options.cwd, options.separator);
 
-  if (options?.match) {
-    log.verbose('git-describe.sync', '%j => %j', options?.match, stdout);
+  if (options.match) {
+    log.verbose('git-describe.sync', '%j => %j', options.match, stdout);
   }
   if (stdout) {
     log.silly('git-describe', 'parsed => %j', result);
diff --git a/packages/publish/src/lib/npm-publish.ts b/packages/publish/src/lib/npm-publish.ts
index 088a57dc..929aa76f 100644
--- a/packages/publish/src/lib/npm-publish.ts
+++ b/packages/publish/src/lib/npm-publish.ts
@@ -38,7 +38,7 @@ export async function npmPublish(
   otpCache?: OneTimePasswordCache
 ): Promise<void | Response> {
   const { dryRun, ...remainingOptions } = flattenOptions(options);
-  const { scope } = npa(pkg?.name ?? '');
+  const { scope } = npa(pkg.name ?? '');
   // pass only the package scope to libnpmpublish
   const opts = {
     log,
diff --git a/packages/publish/src/publish-command.ts b/packages/publish/src/publish-command.ts
index af083ac4..f15a25f5 100644
--- a/packages/publish/src/publish-command.ts
+++ b/packages/publish/src/publish-command.ts
@@ -285,7 +285,7 @@ export class PublishCommand extends Command<PublishCommandOption> {
     if (this.options.publishConfigOverrides !== false) {
       await this.applyPublishConfigOverrides();
     }
-    await this.annotateGitHead();
+    this.annotateGitHead();
     await this.serializeChanges();
     await this.packUpdated();
     await this.publishPacked();
diff --git a/packages/version/src/lib/update-lockfile-version.ts b/packages/version/src/lib/update-lockfile-version.ts
index 5337a13d..1b628857 100644
--- a/packages/version/src/lib/update-lockfile-version.ts
+++ b/packages/version/src/lib/update-lockfile-version.ts
@@ -110,9 +110,7 @@ export function updateNpmLockFileVersion2(obj: any, pkgName: string, newVersion:
           obj[k] = `${versionPrefix}${newVersion}`;
         } else if (k === 'name' && obj[k] === pkgName && obj['version'] !== undefined) {
           // e.g. "packages/version": { "name": "@lerna-lite/version", "version": "0.1.2" }
-          if (obj['version'] !== undefined) {
-            obj['version'] = newVersion;
-          }
+          obj['version'] = newVersion;
         }
       }
     }
diff --git a/packages/version/src/version-command.ts b/packages/version/src/version-command.ts
index 97bb7cec..01b814ff 100644
--- a/packages/version/src/version-command.ts
+++ b/packages/version/src/version-command.ts
@@ -374,7 +374,7 @@ export class VersionCommand extends Command<VersionCommandOption> {
     }
 
     const versionsForUpdate = await this.getVersionsForUpdates();
-    await this.setUpdatesForVersions(versionsForUpdate);
+    this.setUpdatesForVersions(versionsForUpdate);
     return this.confirmVersions();
   }
 
@@ -620,7 +620,7 @@ export class VersionCommand extends Command<VersionCommandOption> {
 
   confirmVersions(): Promise<boolean> | boolean {
     const changes = this.packagesToVersion.map((pkg) => {
-      let line = ` - ${pkg.name ?? '[n/a]'}: ${pkg.version} => ${c.cyan(this.updatesVersions?.get(pkg?.name ?? ''))}`;
+      let line = ` - ${pkg.name ?? '[n/a]'}: ${pkg.version} => ${c.cyan(this.updatesVersions?.get(pkg.name ?? ''))}`;
       if (pkg.private) {
         line += ` (${c.red('private')})`;
       }
@@ -671,7 +671,7 @@ export class VersionCommand extends Command<VersionCommandOption> {
       (pkg: Package) => pkg.refresh(),
       (pkg: Package) => {
         // set new version
-        pkg.set('version', this.updatesVersions?.get(pkg?.name ?? ''));
+        pkg.set('version', this.updatesVersions?.get(pkg.name ?? ''));
 
         // update pkg dependencies
         for (const [depName, resolved] of this.packageGraph?.get(pkg.name)!.localDependencies) {
diff --git a/packages/watch/src/watch-command.ts b/packages/watch/src/watch-command.ts
index 0b0c56ef..b5094b5f 100644
--- a/packages/watch/src/watch-command.ts
+++ b/packages/watch/src/watch-command.ts
@@ -85,7 +85,7 @@ export class WatchCommand extends Command<WatchCommandOption & FilterOptions> {
     );
 
     try {
-      const { ignored = [], ...otherOptions } = this.options ?? {};
+      const { ignored = [], ...otherOptions } = this.options;
       this._ignoredGlobs = ['**/.git/**', '**/dist/**', '**/node_modules/**', ...(Array.isArray(ignored) ? ignored : [ignored])];
 
       const chokidarOptions: ChokidarOptions = {
diff --git a/scripts/cleanup-temp-files.mjs b/scripts/cleanup-temp-files.mjs
index 31fb649d..f5f32e7b 100644
--- a/scripts/cleanup-temp-files.mjs
+++ b/scripts/cleanup-temp-files.mjs
@@ -9,7 +9,7 @@ glob(normalizePath(pathJoin(tempDir, '/lerna-*')), { absolute: true, cwd: tempDi
   .then((deleteFolders) => {
     // silently delete all files/folders that startsWith "lerna-"
     console.log(`Found ${deleteFolders.length} temp folders to cleanup.`);
-    (deleteFolders || []).forEach((folder) => removeSync(folder));
+    deleteFolders.forEach((folder) => removeSync(folder));
   })
   .catch((error) => {
     console.error('Error occurred while cleaning up temp folders:', error);


Test patch:
diff --git a/packages/core/src/corepack/__tests__/exec-package-manager.spec.ts b/packages/core/src/corepack/__tests__/exec-package-manager.spec.ts
index 918e21a4..ed184e00 100644
--- a/packages/core/src/corepack/__tests__/exec-package-manager.spec.ts
+++ b/packages/core/src/corepack/__tests__/exec-package-manager.spec.ts
@@ -29,7 +29,6 @@ describe('.execPackageManagerSync()', () => {
     });
 
     it('calls execSync with corepack when enabled', () => {
-      Object.assign({}, process.env);
       process.env.COREPACK_ROOT = 'pnpm';
 
       execPackageManagerSync('echo', ['execPackageManagerSync']);
@@ -72,7 +71,6 @@ describe('.execPackageManager()', () => {
     });
 
     it('calls exec with corepack when enabled', () => {
-      Object.assign({}, process.env);
       process.env.COREPACK_ROOT = 'pnpm';
 
       execPackageManager('echo', ['execPackageManager']);
diff --git a/packages/core/src/utils/__tests__/env-replace.spec.ts b/packages/core/src/utils/__tests__/env-replace.spec.ts
index aedc00c1..8a61f05b 100644
--- a/packages/core/src/utils/__tests__/env-replace.spec.ts
+++ b/packages/core/src/utils/__tests__/env-replace.spec.ts
@@ -10,7 +10,6 @@ describe('env-replace()', () => {
   });
 
   it('should return the same input when not a string', () => {
-    Object.assign({}, process.env);
     process.env.SOME_TOKEN = '123';
     const input = undefined;
     const output = envReplace(input);
@@ -19,7 +18,6 @@ describe('env-replace()', () => {
   });
 
   it('should replace any {ENV} variable found in the string', () => {
-    Object.assign({}, process.env);
     process.env.SOME_TOKEN = '123';
     const input = 'http://registry.npmjs.org/:_authToken=${SOME_TOKEN}';
     const output = envReplace(input);
diff --git a/packages/core/src/utils/__tests__/parse-field.spec.ts b/packages/core/src/utils/__tests__/parse-field.spec.ts
index 2ce2c263..5780fbaa 100644
--- a/packages/core/src/utils/__tests__/parse-field.spec.ts
+++ b/packages/core/src/utils/__tests__/parse-field.spec.ts
@@ -12,35 +12,35 @@ describe('parseField()', () => {
 
   it("should return True when input field is 'true'", () => {
     const input = true;
-    const output = parseField(`${input}`, 'version');
+    const output = parseField(input, 'version');
 
     expect(output).toBeTruthy();
   });
 
   it("should return False when input field is 'false'", () => {
     const input = false;
-    const output = parseField(`${input}`, 'version');
+    const output = parseField(input, 'version');
 
     expect(output).toBeFalsy();
   });
 
   it("should return Null when input field is 'null'", () => {
     const input = null;
-    const output = parseField(`${input}`, 'version');
+    const output = parseField(input, 'version');
 
     expect(output).toBeNull();
   });
 
   it("should return Undefined when input field is 'undefined'", () => {
     const input = undefined;
-    const output = parseField(`${input}`, 'version');
+    const output = parseField(input, 'version');
 
     expect(output).toBeUndefined();
   });
 
   it('should return number when key is found to be a Number in types.ts filed', () => {
     const input = 123;
-    const output = parseField(`${input}`, 'searchlimit');
+    const output = parseField(input, 'searchlimit');
 
     expect(output).toBe(123);
   });
diff --git a/packages/version/src/__tests__/update-lockfile-version.spec.ts b/packages/version/src/__tests__/update-lockfile-version.spec.ts
index adf48037..6895a285 100644
--- a/packages/version/src/__tests__/update-lockfile-version.spec.ts
+++ b/packages/version/src/__tests__/update-lockfile-version.spec.ts
@@ -106,7 +106,7 @@ describe('npm modern lock file', () => {
     if (lockFileOutput!.json) {
       for (const pkg of packages) {
         pkg.version = mockVersion;
-        await updateTempModernLockfileVersion(pkg as unknown as Package, lockFileOutput!.json);
+        updateTempModernLockfileVersion(pkg as unknown as Package, lockFileOutput!.json);
       }
       await saveUpdatedLockJsonFile(lockFileOutput!.path, lockFileOutput!.json);
     }
diff --git a/packages/version/src/conventional-commits/__tests__/get-commits-since-last-release.spec.ts b/packages/version/src/conventional-commits/__tests__/get-commits-since-last-release.spec.ts
index 72751f43..a3375ff2 100644
--- a/packages/version/src/conventional-commits/__tests__/get-commits-since-last-release.spec.ts
+++ b/packages/version/src/conventional-commits/__tests__/get-commits-since-last-release.spec.ts
@@ -76,25 +76,25 @@ describe('getOldestCommitSinceLastTag', () => {
       });
     });
 
-    it('should return first commit date format as ISO+offset when describeRefSync() did not return a tag date', async () => {
+    it('should return first commit date format as ISO+offset when describeRefSync() did not return a tag date', () => {
       const execSpy = (execSync as Mock).mockReturnValueOnce('"abcbeef 2022-07-01T00:01:02-04:00"');
-      const result = await getOldestCommitSinceLastTag(execOpts);
+      const result = getOldestCommitSinceLastTag(execOpts);
 
       expect(execSpy).toHaveBeenCalledWith('git', ['log', '--oneline', '--format="%h %aI"', '--reverse', '--max-parents=0', 'HEAD'], execOpts);
       expect(result).toEqual({ commitDate: '2022-07-01T00:01:02-04:00', commitHash: 'abcbeef' });
     });
 
-    it('should return first commit date with a TZ format when describeRefSync() did not return a tag date', async () => {
+    it('should return first commit date with a TZ format when describeRefSync() did not return a tag date', () => {
       const execSpy = (execSync as Mock).mockReturnValueOnce('"abcbeef 2024-05-16T10:37:42Z"');
-      const result = await getOldestCommitSinceLastTag(execOpts);
+      const result = getOldestCommitSinceLastTag(execOpts);
 
       expect(execSpy).toHaveBeenCalledWith('git', ['log', '--oneline', '--format="%h %aI"', '--reverse', '--max-parents=0', 'HEAD'], execOpts);
       expect(result).toEqual({ commitDate: '2024-05-16T10:37:42Z', commitHash: 'abcbeef' });
     });
 
-    it('should return first commit date with a TZ and microsecond format when describeRefSync() did not return a tag date', async () => {
+    it('should return first commit date with a TZ and microsecond format when describeRefSync() did not return a tag date', () => {
       const execSpy = (execSync as Mock).mockReturnValueOnce('"abcbeef 2024-05-16T10:37:42.234Z"');
-      const result = await getOldestCommitSinceLastTag(execOpts);
+      const result = getOldestCommitSinceLastTag(execOpts);
 
       expect(execSpy).toHaveBeenCalledWith('git', ['log', '--oneline', '--format="%h %aI"', '--reverse', '--max-parents=0', 'HEAD'], execOpts);
       expect(result).toEqual({ commitDate: '2024-05-16T10:37:42.234Z', commitHash: 'abcbeef' });
@@ -114,11 +114,11 @@ describe('getOldestCommitSinceLastTag', () => {
       (execSync as Mock).mockReset();
     });
 
-    it('should expect a tag date & hash but queried with a particular tag match pattern when using independent mode', async () => {
+    it('should expect a tag date & hash but queried with a particular tag match pattern when using independent mode', () => {
       const isIndependent = true;
       const mockExecSyncResult = '"deadabcd 2022-07-01T00:01:02-06:00"';
       (execSync as Mock).mockReturnValue(mockExecSyncResult);
-      const result = await getOldestCommitSinceLastTag(execOpts, isIndependent, false);
+      const result = getOldestCommitSinceLastTag(execOpts, isIndependent, false);
       const execSpy = (execSync as Mock).mockReturnValueOnce(mockExecSyncResult);
 
       expect(describeRefSync).toHaveBeenCalledWith({ cwd: '/test', match: '*@*' }, false);
@@ -126,10 +126,10 @@ describe('getOldestCommitSinceLastTag', () => {
       expect(result).toEqual({ commitDate: '2022-07-01T00:01:02-06:00', commitHash: 'deadabcd' });
     });
 
-    it('should expect a commit date and hash when using different time zone', async () => {
+    it('should expect a commit date and hash when using different time zone', () => {
       const isIndependent = true;
       (execSync as Mock).mockReturnValue('"deadbeef 2022-07-01T00:01:02+01:00"');
-      const result = await getOldestCommitSinceLastTag(execOpts, isIndependent, false);
+      const result = getOldestCommitSinceLastTag(execOpts, isIndependent, false);
       const execSpy = (execSync as Mock).mockReturnValueOnce('"deadbeef 2022-07-01T00:01:02+01:00"');
 
       expect(describeRefSync).toHaveBeenCalledWith({ cwd: '/test', match: '*@*' }, false);
@@ -143,19 +143,19 @@ describe('getOldestCommitSinceLastTag', () => {
       (describeRefSync as Mock).mockReturnValue(tagStub);
     });
 
-    it('should return first commit date and hash when last tag is not found', async () => {
+    it('should return first commit date and hash when last tag is not found', () => {
       const execSpy = (execSync as Mock).mockReturnValueOnce('').mockReturnValueOnce('"deedbeaf 2022-07-01T00:01:02-04:00"');
 
-      const result = await getOldestCommitSinceLastTag(execOpts);
+      const result = getOldestCommitSinceLastTag(execOpts);
 
       expect(execSpy).toHaveBeenCalledWith('git', ['log', 'v1.0.0..HEAD', '--format="%h %aI"', '--reverse'], execOpts);
       expect(execSpy).toHaveBeenCalledWith('git', ['log', '-1', '--format="%h %aI"', 'v1.0.0'], execOpts);
       expect(result).toEqual({ commitDate: '2022-07-01T00:01:02-04:00', commitHash: 'deedbeaf' });
     });
 
-    it('should expect a result with a tag date, hash and ref count when last tag is found', async () => {
+    it('should expect a result with a tag date, hash and ref count when last tag is found', () => {
       const execSpy = (execSync as Mock).mockReturnValueOnce('"deadbeef 2022-07-01T00:01:02-04:00"');
-      const result = await getOldestCommitSinceLastTag(execOpts, false, false);
+      const result = getOldestCommitSinceLastTag(execOpts, false, false);
 
       expect(describeRefSync).toHaveBeenCalledWith({ cwd: '/test' }, false);
       expect(execSpy).toHaveBeenCalledWith('git', ['log', 'v1.0.0..HEAD', '--format="%h %aI"', '--reverse'], execOpts);