fs-extra#pathExistsSync TypeScript Examples

The following examples show how to use fs-extra#pathExistsSync. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: config.spec.ts    From cli with Apache License 2.0 5 votes vote down vote up
mockedPathExists = jest.mocked(pathExistsSync)
Example #2
Source File: config.ts    From cli with Apache License 2.0 5 votes vote down vote up
private ensureExists() {
    const exists = pathExistsSync(this.configPath);
    if (!exists) {
      createFileSync(this.configPath);
      writeJSONSync(this.configPath, DefaultConfig);
    }
  }
Example #3
Source File: project.spec.ts    From cli with Apache License 2.0 5 votes vote down vote up
mockedPathExistsSync = jest.mocked(pathExistsSync)
Example #4
Source File: DownloadedUpdateHelper.ts    From electron-differential-updater with MIT License 5 votes vote down vote up
/**
   * Returns "update-info.json" which is created in the update cache directory's "pending" subfolder after the first update is downloaded.  If the update file does not exist then the cache is cleared and recreated.  If the update file exists then its properties are validated.
   * @param fileInfo
   * @param logger
   */
  private async getValidCachedUpdateFile(fileInfo: ResolvedUpdateFileInfo, logger: Logger): Promise<string | null> {
    const updateInfoFilePath: string = this.getUpdateInfoFile()

    const doesUpdateInfoFileExist = await pathExistsSync(updateInfoFilePath);
    if(!doesUpdateInfoFileExist) {
      return null;
    }


    let cachedInfo: CachedUpdateInfo
    try {
      cachedInfo = await readJson(updateInfoFilePath)
    }
    catch (error) {
      let message = `No cached update info available`
      if (error.code !== "ENOENT") {
        await this.cleanCacheDirForPendingUpdate()
        message += ` (error on read: ${error.message})`
      }
      logger.info(message)
      return null
    }

    const isCachedInfoFileNameValid = cachedInfo?.fileName !== null ?? false
    if (!isCachedInfoFileNameValid) {
      logger.warn(`Cached update info is corrupted: no fileName, directory for cached update will be cleaned`)
      await this.cleanCacheDirForPendingUpdate()
      return null
    }

    if (fileInfo.info.sha512 !== cachedInfo.sha512) {
      logger.info(`Cached update sha512 checksum doesn't match the latest available update. New update must be downloaded. Cached: ${cachedInfo.sha512}, expected: ${fileInfo.info.sha512}. Directory for cached update will be cleaned`)
      await this.cleanCacheDirForPendingUpdate()
      return null
    }

    const updateFile = path.join(this.cacheDirForPendingUpdate, cachedInfo.fileName)
    if (!(await pathExists(updateFile))) {
      logger.info("Cached update file doesn't exist, directory for cached update will be cleaned")
      await this.cleanCacheDirForPendingUpdate()
      return null
    }

    const sha512 = await hashFile(updateFile)
    if (fileInfo.info.sha512 !== sha512) {
      logger.warn(`Sha512 checksum doesn't match the latest available update. New update must be downloaded. Cached: ${sha512}, expected: ${fileInfo.info.sha512}`)
      await this.cleanCacheDirForPendingUpdate()
      return null
    }
    this._downloadedFileInfo = cachedInfo
    return updateFile
  }
Example #5
Source File: fs.ts    From DefinitelyTyped-tools with MIT License 5 votes vote down vote up
exists(path: string): boolean {
    return pathExistsSync(this.getPath(path));
  }
Example #6
Source File: ResourceApi.test.ts    From joplin-utils with MIT License 4 votes vote down vote up
describe('test ResourceApi', () => {
  let id: string
  beforeAll(async () => {
    id = (await createTestResource()).id
  })
  afterAll(async () => {
    await resourceApi.remove(id)
  })
  const tempPath = path.resolve(__dirname, '.temp')
  beforeEach(async () => {
    await remove(tempPath)
    await mkdirp(tempPath)
  })
  it('test list', async () => {
    const res = await resourceApi.list({ fields: ['id', 'title'] })
    console.log(res)
    expect(res.items.length).toBeGreaterThan(0)
  })
  it('test get', async () => {
    const res = await resourceApi.get(id)
    console.log(res)
    expect(res.id).toBe(id)
  })
  /**
   * TODO 一个官方未修复的 bug,参考:https://github.com/laurent22/joplin/issues/4575
   */
  it.skip('test get filename', async () => {
    const res = await resourceApi.get(id, ['id', 'filename'])
    console.log(res)
    expect(res.filename).not.toBe('')
  })

  describe('diff fetch and axios', () => {
    const path = resolve(__dirname, '../resource/resourcesByFileId.png')
    it('test create', async () => {
      const title = 'image title'
      const json = await resourceApi.create({
        title,
        data: createReadStream(path),
      })
      expect(json.title).toBe(title)
    })
  })
  describe('test update', () => {
    it('basic example', async () => {
      const title = `new title ${Date.now()}`
      const updateRes = await resourceApi.update({ id, title })
      expect(updateRes.title).toBe(title)
    })
    it('update file', async () => {
      const content = 'test'
      const txtPath = path.resolve(tempPath, 'test.txt')
      await writeFile(txtPath, content)
      await resourceApi.update({ id, data: createReadStream(txtPath) })
      const res = await resourceApi.fileByResourceId(id)
      expect(res.toString()).toBe(content)
    })
    it('update properties and file', async () => {
      const title = `new title ${Date.now()}`
      const content = 'test'
      const txtPath = path.resolve(tempPath, 'test.txt')
      await writeFile(txtPath, content)
      const updateRes = await resourceApi.update({ id, title, data: createReadStream(txtPath) })
      expect(updateRes.title).toBe(title)
      const res = await resourceApi.fileByResourceId(id)
      expect(res.toString()).toBe(content)
    })
    it('update file only', async () => {
      const content = 'test'
      const txtPath = path.resolve(tempPath, 'test.txt')
      await writeFile(txtPath, content)
      const { title } = await resourceApi.get(id)
      await resourceApi.update({ id, data: createReadStream(txtPath) })
      const res = await resourceApi.fileByResourceId(id)
      expect(res.toString()).toBe(content)
      expect((await resourceApi.get(id)).title).toBe(title)
    })
  })
  /**
   * 已知错误
   * https://discourse.joplinapp.org/t/pre-release-v2-8-is-now-available-updated-14-april/25158/10?u=rxliuli
   */
  it.skip('test remove ', async () => {
    const id = (await createTestResource()).id
    await resourceApi.remove(id)
    await expect(resourceApi.get(id)).rejects.toThrowError()
  })
  it('test fileByResourceId', async () => {
    const res = await resourceApi.fileByResourceId(id)
    console.log(typeof res)
    const path = resolve(tempPath, 'resourcesByFileId.png')
    await writeFile(path, res)
    expect(pathExistsSync(path)).toBeTruthy()
  })
  it('test to get the size of the attachment resource', async () => {
    const id = (await createTestResource()).id
    const res = await resourceApi.get(id, ['id', 'title', 'size'])
    const stats = await stat(path.resolve(__dirname, '../resource/resourcesByFileId.png'))
    expect(res.size).toEqual(stats.size)
  })
})
Example #7
Source File: dryrun.ts    From algo-builder with Apache License 2.0 4 votes vote down vote up
describe("Debugging TEAL code using tealdbg", () => {
	useFixtureProject("config-project");
	let deployer: Deployer;
	let algod: AlgoOperatorDryRunImpl;
	let txParam: ExecParams;
	let tealDebugger: TealDbgMock;

	beforeEach(async () => {
		const env = mkEnv("network1");
		algod = new AlgoOperatorDryRunImpl();
		const deployerCfg = new DeployerConfig(env, algod);
		deployer = new DeployerRunMode(deployerCfg);
		stub(algod.algodClient, "getTransactionParams").returns({
			do: async () => mockSuggestedParam,
		} as ReturnType<algosdk.Algodv2["getTransactionParams"]>);
		stub(algod.algodClient, "genesis").returns({
			do: async () => mockGenesisInfo,
		} as ReturnType<algosdk.Algodv2["genesis"]>);

		(stub(algod.algodClient, "dryrun") as any).returns({
			do: async () => mockDryRunResponse,
		}) as ReturnType<algosdk.Algodv2["dryrun"]>;

		(stub(algod.algodClient, "accountInformation") as any).returns({
			do: async () => mockAccountInformation,
		}) as ReturnType<algosdk.Algodv2["accountInformation"]>;

		(stub(algod.algodClient, "getApplicationByID") as any).returns({
			do: async () => mockApplicationResponse,
		}) as ReturnType<algosdk.Algodv2["getApplicationByID"]>;

		txParam = {
			type: types.TransactionType.TransferAsset,
			sign: types.SignType.LogicSignature,
			fromAccountAddr: generateAccount().addr,
			toAccountAddr: generateAccount().addr,
			amount: 500,
			assetID: 1,
			lsig: mockLsig,
			payFlags: { totalFee: 1000 },
		};
		tealDebugger = new TealDbgMock(deployer, txParam);
	});

	afterEach(async () => {
		(algod.algodClient.getTransactionParams as SinonStub).restore();
		(algod.algodClient.dryrun as SinonStub).restore();
		(algod.algodClient.accountInformation as SinonStub).restore();
		(algod.algodClient.getApplicationByID as SinonStub).restore();
		(algod.algodClient.genesis as SinonStub).restore();
	});

	it("dump dryrunResponse in assets/<file>", async () => {
		const resp = await tealDebugger.dryRunResponse();

		// assert recieved response
		assert.deepEqual(resp, mockDryRunResponse);

		// dump response to  file in assets
		await tealDebugger.dryRunResponse("dryrun-resp.json");

		// verify path and data
		const outPath = path.join(process.cwd(), ASSETS_DIR, "dryrun-resp.json");
		assert.isTrue(pathExistsSync(outPath));
		const data = fs.readFileSync(outPath);
		assert.deepEqual(JSON.parse(Buffer.from(data).toString()), mockDryRunResponse);

		fs.rmSync(outPath);
	});

	it("should warn or overwrite existing dryRunResponse based on --force flag", async () => {
		const stub = console.error as SinonStub;
		stub.reset();

		await tealDebugger.dryRunResponse("response.json");
		await tealDebugger.dryRunResponse("response.json"); // running again with same outfile

		const warnMsg =
			"File assets/response.json already exists. Aborting. Use --force flag if you want to overwrite it";
		assert.isTrue(stub.calledWith(warnMsg));

		// if --force == true is passed then file is overwritten
		await tealDebugger.dryRunResponse("response.json", true);
		assert.isTrue(
			(console.log as SinonStub).calledWith(`Data written succesfully to assets/response.json`)
		);

		fs.rmSync(path.join(process.cwd(), ASSETS_DIR, "response.json"));
	});

	it("should write --dryrun-dump in `cache/dryrun` and run debugger with provided args", async () => {
		assert.equal(tealDebugger.writtenFiles.length, 0);
		await tealDebugger.run();

		// verify .msdp (dryrun dump) is present in cache/dryrun
		assert.equal(tealDebugger.writtenFiles.length, 1);
		// eg. artifacts/cache/dryrun/dump-1626204870.msgp
		const pathToMsgpDump = tealDebugger.writtenFiles[0];
		assert.equal(path.dirname(pathToMsgpDump), "artifacts/cache/dryrun");

		// verify dump arg (-d)
		assert.include(tealDebugger.debugArgs, "-d");
		assert.include(tealDebugger.debugArgs, pathToMsgpDump);

		// verify path to teal file is present(if passed)
		await tealDebugger.run({ tealFile: "gold-asa.teal" });
		assert.include(tealDebugger.debugArgs, "assets/gold-asa.teal");

		// verify mode and groupIndex arg (--mode, --group-index)
		await tealDebugger.run({ mode: ExecutionMode.APPLICATION, groupIndex: 0 });
		assert.include(tealDebugger.debugArgs, "--mode");
		assert.include(tealDebugger.debugArgs, "application");
		assert.include(tealDebugger.debugArgs, "--group-index");
		assert.include(tealDebugger.debugArgs, "0");
	});

	it("should throw error if groupIndex is greator than txGroup length", async () => {
		tealDebugger.execParams = [txParam, { ...txParam, payFlags: { note: "Algrand" } }];

		try {
			await tealDebugger.run({ mode: ExecutionMode.APPLICATION, groupIndex: 5 });
		} catch (error) {
			if (error instanceof Error) {
				assert.equal(error.message, "groupIndex(= 5) exceeds transaction group length(= 2)");
			}
			console.error("An unexpected error occurred:", error);
		}
	});

	it("should run debugger using pyteal files as well", async () => {
		const writtenFilesBeforeLen = tealDebugger.writtenFiles.length;
		await tealDebugger.run({ tealFile: "gold-asa.py" });

		// 2 files should be written: (1. --dryrun-dump and 2. compiled teal code from pyTEAL)
		assert.equal(tealDebugger.writtenFiles.length, writtenFilesBeforeLen + 2);
	});

	it("should run debugger from cached TEAL code", async () => {
		const stub = console.info as SinonStub;
		stub.reset();
		const writtenFilesBeforeLen = tealDebugger.writtenFiles.length;

		// write to cache
		const pathToWrite = path.join(CACHE_DIR, "gold-asa.py.yaml");
		fs.writeFileSync(
			pathToWrite,
			YAML.stringify({
				tealCode: getProgram("gold-asa.py"),
			})
		);

		await tealDebugger.run({ tealFile: "gold-asa.py" });

		// verify cached console.info is true
		assert.isTrue(
			(console.info as SinonStub).calledWith(
				"\x1b[33m%s\x1b[0m",
				`Using cached TEAL code for gold-asa.py`
			)
		);

		// 2 files should be written: (1. --dryrun-dump and 2. cached teal code from pyTEAL)
		assert.equal(tealDebugger.writtenFiles.length, writtenFilesBeforeLen + 2);
		fs.rmSync(pathToWrite);
	});
});