From a6ff1699c7d4fcc309bc69634ef8ed660f471d45 Mon Sep 17 00:00:00 2001 From: mshanemc Date: Wed, 31 May 2023 18:15:55 -0500 Subject: [PATCH] refactor: narrower catch to just the fs read, plus ut for no file --- .../accessors/aliasAccessor.ts | 6 ++--- .../accessors/aliasAccessorTest.ts | 23 ++++++++++++++++++- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/src/stateAggregator/accessors/aliasAccessor.ts b/src/stateAggregator/accessors/aliasAccessor.ts index e89a9a4a24..b5701f53f9 100644 --- a/src/stateAggregator/accessors/aliasAccessor.ts +++ b/src/stateAggregator/accessors/aliasAccessor.ts @@ -216,10 +216,10 @@ export class AliasAccessor extends AsyncOptionalCreatable { * if the file doesn't exist, create it empty */ private async readFileToAliasStore(useLock = false): Promise { + if (useLock) { + await lock(this.fileLocation, lockRetryOptions); + } try { - if (useLock) { - await lock(this.fileLocation, lockRetryOptions); - } this.aliasStore = fileContentsRawToAliasStore(await readFile(this.fileLocation, 'utf-8')); } catch (e) { if (e instanceof Error && 'code' in e && e.code === 'ENOENT') { diff --git a/test/unit/stateAggregator/accessors/aliasAccessorTest.ts b/test/unit/stateAggregator/accessors/aliasAccessorTest.ts index a60dcbca8e..77629f7da2 100644 --- a/test/unit/stateAggregator/accessors/aliasAccessorTest.ts +++ b/test/unit/stateAggregator/accessors/aliasAccessorTest.ts @@ -4,9 +4,14 @@ * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ +import { join } from 'node:path'; +import { existsSync } from 'node:fs'; +import { rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; import { expect } from 'chai'; -import { StateAggregator } from '../../../../src/stateAggregator'; +import { FILENAME, StateAggregator } from '../../../../src/stateAggregator'; import { MockTestOrgData, TestContext, uniqid } from '../../../../src/testSetup'; +import { Global } from '../../../../src/global'; const username1 = 'espresso@coffee.com'; const username2 = 'foobar@salesforce.com'; @@ -174,6 +179,20 @@ describe('AliasAccessor', () => { }); }); + describe('lockfile concerns', () => { + it('no aliases file, creates empty file', async () => { + const fileLocation = getAliasFileLocation(); + await rm(fileLocation); + expect(existsSync(fileLocation)).to.be.false; + const stateAggregator = await StateAggregator.getInstance(); + const aliases = stateAggregator.aliases.getAll(username1); + expect(aliases).to.deep.equal([]); + const all = stateAggregator.aliases.getAll(); + expect(all).to.deep.equal({}); + expect(existsSync(fileLocation)).to.be.true; + }); + }); + describe('concurrent access', () => { const quantity = 50; @@ -237,3 +256,5 @@ describe('AliasAccessor', () => { }); }); }); + +const getAliasFileLocation = (): string => join(tmpdir(), Global.SFDX_STATE_FOLDER, FILENAME);