fs-extra#pathExists TypeScript Examples

The following examples show how to use fs-extra#pathExists. 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: lint.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
export async function checkTslintJson(dirPath: string, dt: boolean): Promise<void> {
  const configPath = getConfigPath(dirPath);
  const shouldExtend = `@definitelytyped/dtslint/${dt ? "dt" : "dtslint"}.json`;
  const validateExtends = (extend: string | string[]) =>
    extend === shouldExtend || (!dt && Array.isArray(extend) && extend.some((val) => val === shouldExtend));

  if (!(await pathExists(configPath))) {
    if (dt) {
      throw new Error(
        `On DefinitelyTyped, must include \`tslint.json\` containing \`{ "extends": "${shouldExtend}" }\`.\n` +
          "This was inferred as a DefinitelyTyped package because it contains a `// Type definitions for` header."
      );
    }
    return;
  }

  const tslintJson = await readJson(configPath);
  if (!validateExtends(tslintJson.extends)) {
    throw new Error(`If 'tslint.json' is present, it should extend "${shouldExtend}"`);
  }
}
Example #2
Source File: setupTestEnv.ts    From joplin-utils with MIT License 6 votes vote down vote up
export async function setupTestEnv() {
  config.baseUrl = 'http://localhost:27583'
  const envPath = path.resolve(__dirname, '.env.local')
  if (!(await pathExists(envPath))) {
    throw new Error('请更新 .env.local 文件:' + envPath)
  }
  const env = await readFile(envPath, 'utf8')
  config.token = parse(env).TOKEN!
}
Example #3
Source File: WikiCommander.ts    From joplin-blog with MIT License 6 votes vote down vote up
async checkConfig(): Promise<JoplinBlogConfig | false> {
    const configPath = path.resolve('.joplin-blog.json')
    if (!(await pathExists(configPath))) {
      console.error(
        i18n.t("wiki.Can't find configuration file _joplin-blog_json"),
      )
      return false
    }
    return (await readJson(configPath)) as JoplinBlogConfig
  }
Example #4
Source File: BlogCommander.ts    From joplin-blog with MIT License 6 votes vote down vote up
async checkConfig(): Promise<JoplinBlogConfig | false> {
    const configPath = path.resolve('.joplin-blog.json')
    if (!(await pathExists(configPath))) {
      console.error(
        i18n.t("blog.Can't find configuration file _joplin-blog_json"),
      )
      return false
    }
    return (await readJson(configPath)) as JoplinBlogConfig
  }
Example #5
Source File: ResourceWriter.ts    From joplin-blog with MIT License 6 votes vote down vote up
async clean() {
    const postPath = path.resolve(this.config.postPath)
    const resourcePath = path.resolve(this.config.resourcePath)

    async function clean(dirPath: string) {
      if (await pathExists(dirPath)) {
        await remove(dirPath)
      }
      await mkdirp(dirPath)
    }

    await Promise.all([clean(postPath), clean(resourcePath)])
  }
Example #6
Source File: main.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
export async function withFileLock(lockFilePath: string, cb: () => Promise<void>): Promise<LockFileResult> {
  console.log("Checking for lock file...");
  if (await pathExists(lockFilePath)) {
    const lastRunStartTimestamp = (await tryReadJson(lockFilePath, isLockfileFormat))?.timestamp || currentTimeStamp();
    const elapsedSeconds = (Date.now() - Date.parse(lastRunStartTimestamp)) / 1000;
    if (elapsedSeconds < getFunctionTimeoutSeconds()) {
      console.log("Lock file exists; new run not triggered.");
      return { triggered: false, timestamp: lastRunStartTimestamp };
    }
  }

  console.log("Lock file does not exist; writing lock file and running.");
  await writeFile(lockFilePath, JSON.stringify({ timestamp: currentTimeStamp() }));
  cb().then(
    () => remove(lockFilePath),
    async (error) => {
      console.error(error?.stack || error?.message || error);
      applicationinsights.defaultClient.trackException({
        exception: error,
      });

      await remove(lockFilePath);
      process.exit(1);
    }
  );

  return { triggered: true };
}
Example #7
Source File: prepareAffectedPackages.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
export async function installDependencies(packages: Iterable<TypingsData>, typesPath: string): Promise<void> {
  console.log("Installing NPM dependencies...");

  // We need to run `npm install` for all dependencies, too, so that we have dependencies' dependencies installed.
  for (const pkg of packages) {
    const cwd = joinPaths(typesPath, pkg.subDirectoryPath);
    if (!(await pathExists(joinPaths(cwd, "package.json")))) {
      continue;
    }

    // Scripts may try to compile native code.
    // This doesn't work reliably on travis, and we're just installing for the types, so ignore.
    const cmd = `npm install ${npmInstallFlags} --tag ts${pkg.minTypeScriptVersion}`;
    console.log(`  ${cwd}: ${cmd}`);
    const stdout = await execAndThrowErrors(cmd, cwd);
    if (stdout) {
      // Must specify what this is for since these run in parallel.
      console.log(` from ${cwd}: ${stdout}`);
    }
  }
}
Example #8
Source File: util.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
export async function getCompilerOptions(dirPath: string): Promise<ts.CompilerOptions> {
  const tsconfigPath = join(dirPath, "tsconfig.json");
  if (!(await pathExists(tsconfigPath))) {
    throw new Error(`Need a 'tsconfig.json' file in ${dirPath}`);
  }
  return (await readJson(tsconfigPath)).compilerOptions;
}
Example #9
Source File: lint.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
async function getLintConfig(
  expectedConfigPath: string,
  tsconfigPath: string,
  minVersion: TsVersion,
  maxVersion: TsVersion,
  tsLocal: string | undefined
): Promise<IConfigurationFile> {
  const configExists = await pathExists(expectedConfigPath);
  const configPath = configExists ? expectedConfigPath : joinPaths(__dirname, "..", "dtslint.json");
  // Second param to `findConfiguration` doesn't matter, since config path is provided.
  const config = Configuration.findConfiguration(configPath, "").results;
  if (!config) {
    throw new Error(`Could not load config at ${configPath}`);
  }

  const expectRule = config.rules.get("expect");
  if (!expectRule || expectRule.ruleSeverity !== "error") {
    throw new Error("'expect' rule should be enabled, else compile errors are ignored");
  }
  if (expectRule) {
    const versionsToTest = range(minVersion, maxVersion).map((versionName) => ({
      versionName,
      path: typeScriptPath(versionName, tsLocal),
    }));
    const expectOptions: ExpectOptions = { tsconfigPath, versionsToTest };
    expectRule.ruleArguments = [expectOptions];
  }
  return config;
}
Example #10
Source File: JoplinNoteCommandService.ts    From joplin-utils with MIT License 6 votes vote down vote up
/**
   * 创建资源
   */
  async createResource() {
    const globalStoragePath = GlobalContext.context.globalStorageUri.fsPath
    const title = await vscode.window.showInputBox({
      placeHolder: i18n.t('Please enter what you want to create {{type}} name', {
        type: i18n.t('attachment'),
      }),
      value: '',
    })
    if (!title) {
      return
    }
    const filePath = path.resolve(globalStoragePath, `.tempResource/${title}`)
    await createEmptyFile(filePath)
    let { res, markdownLink } = await UploadResourceUtil.uploadFileByPath(filePath)
    // 如果是 svg 图片则作为图片插入
    if (path.extname(filePath) === '.svg') {
      markdownLink = '!' + markdownLink
    }
    await Promise.all([
      uploadResourceService.insertUrlByActiveEditor(markdownLink),
      uploadResourceService.refreshResourceList(res.id),
    ])
    if (await pathExists(filePath)) {
      await remove(filePath)
    }
    vscode.window.showInformationMessage(i18n.t('Attachment resource created successfully'))
    await this.handlerService.openResource(res.id)
  }
Example #11
Source File: setupTestEnv.ts    From joplin-utils with MIT License 6 votes vote down vote up
export async function setupTestEnv() {
  config.baseUrl = 'http://localhost:27583'
  const envPath = path.resolve(__dirname, '.env.local')
  if (!(await pathExists(envPath))) {
    throw new Error('请更新 .env.local 文件:' + envPath)
  }
  const env = await readFile(envPath, 'utf8')
  config.token = parse(env).TOKEN!
}
Example #12
Source File: DownloadedUpdateHelper.ts    From electron-differential-updater with MIT License 6 votes vote down vote up
async validateDownloadedPath(updateFile: string, updateInfo: UpdateInfo, fileInfo: ResolvedUpdateFileInfo, logger: Logger): Promise<string | null> {
    if (this.versionInfo != null && this.file === updateFile && this.fileInfo != null) {
      // update has already been downloaded from this running instance
      // check here only existence, not checksum
      if (isEqual(this.versionInfo, updateInfo) && isEqual(this.fileInfo.info, fileInfo.info) && (await pathExists(updateFile))) {
        return updateFile
      }
      else {
        return null
      }
    }

    // update has already been downloaded from some previous app launch
    const cachedUpdateFile = await this.getValidCachedUpdateFile(fileInfo, logger)
    if (cachedUpdateFile === null) {
      return null
    }
    logger.info(`Update has already been downloaded to ${updateFile}).`)
    this._file = cachedUpdateFile
    return cachedUpdateFile
  }
Example #13
Source File: darwin.ts    From TidGi-Desktop with Mozilla Public License 2.0 6 votes vote down vote up
async function findApplication(editor: IDarwinExternalEditor): Promise<string | null> {
  for (const identifier of editor.bundleIdentifiers) {
    try {
      logger.info(`Try getting path of ${identifier} in darwin.findApplication`);
      // app-path not finding the app isn't an error, it just means the
      // bundle isn't registered on the machine.
      // https://github.com/sindresorhus/app-path/blob/0e776d4e132676976b4a64e09b5e5a4c6e99fcba/index.js#L7-L13
      const installPath = await appPath(identifier).catch(async (error: Error) => {
        logger.info(`findApplication() gets appPath Error: ${error?.message ?? String(error)}`);
        if (error?.message === "Couldn't find the app") {
          return await Promise.resolve(null);
        }
        return await Promise.reject(error);
      });
      logger.info(`Path of ${identifier} is ${String(installPath)} in darwin.findApplication`);

      if (installPath === null) {
        return null;
      }

      if (await pathExists(installPath)) {
        return installPath;
      }

      logger.info(`App installation for ${editor.name} not found at '${installPath}'`);
    } catch (error) {
      logger.info(`findApplication() Unable to locate ${editor.name} installation. Error: ${(error as Error).message}`);
    }
  }

  return null;
}
Example #14
Source File: launch.ts    From TidGi-Desktop with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Open a given file or folder in the desired external editor.
 *
 * @param fullPath A folder or file path to pass as an argument when launching the editor.
 * @param editor The external editor to launch.
 */
export async function launchExternalEditor(fullPath: string, editor: FoundEditor): Promise<void> {
  const editorPath = editor.path;
  const exists = await pathExists(editorPath);
  if (!exists) {
    const label = process.platform === 'darwin' ? 'Preferences' : 'Options';
    throw new ExternalEditorError(
      `Could not find executable for '${editor.editor}' at path '${editor.path}'.  Please open ${label} and select an available editor.`,
      { openPreferences: true },
    );
  }

  const options: SpawnOptions = {
    // Make sure the editor processes are detached from the Desktop app.
    // Otherwise, some editors (like Notepad++) will be killed when the
    // Desktop app is closed.
    detached: true,
  };

  if (editor.usesShell) {
    spawn(`"${editorPath}"`, [`"${fullPath}"`], { ...options, shell: true });
  } else if (process.platform === 'darwin') {
    // In macOS we can use `open`, which will open the right executable file
    // for us, we only need the path to the editor .app folder.
    spawn('open', ['-a', editorPath, fullPath], options);
  } else {
    spawn(editorPath, [fullPath], options);
  }
}
Example #15
Source File: linux.ts    From TidGi-Desktop with Mozilla Public License 2.0 6 votes vote down vote up
async function getAvailablePath(paths: string[]): Promise<string | null> {
  for (const path of paths) {
    if (await pathExists(path)) {
      return path;
    }
  }

  return null;
}
Example #16
Source File: compareImages.ts    From cucumber-playwright with MIT License 6 votes vote down vote up
export async function compareToBaseImage(
  customWorld: ICustomWorld,
  name: string,
  screenshot: Buffer,
  threshold?: { threshold: number },
) {
  let baseImage;
  const baseImagePath = getImagePath(customWorld, name);
  const baseImgExist = await pathExists(baseImagePath);
  if (baseImgExist) {
    baseImage = PNG.sync.read(fs.readFileSync(baseImagePath));
  } else {
    await ensureFile(baseImagePath);
    writeFileSync(baseImagePath, screenshot);
    customWorld.log(
      `The base Image doesn't exist, a screenshot was taken to ${baseImagePath} so it can be used for next run`,
    );
    return;
  }
  const img1 = PNG.sync.read(screenshot);
  const difference = getDifference(img1, baseImage, threshold);
  if (difference) {
    await customWorld.attach(difference, 'image/png;base64');
    throw new Error(`Screenshot does not match : ${baseImagePath}`);
  }
}
Example #17
Source File: download-ui5-resources.ts    From ui5-language-assistant with Apache License 2.0 6 votes vote down vote up
async function writeUrlToFile(url: string, file: string): Promise<void> {
  // Don't download the file if it already exists
  if (await pathExists(file)) {
    return;
  }

  log(`fetching from ${url}`);
  const response = await fetch(url);
  if (!response.ok) {
    error(`error fetching from ${url}`);
    return;
  }
  const text = await response.text();
  if (text === "{}") {
    // These files don't add anything to the model but they return an error in strict mode
    log(`empty object returned from ${url}`);
    return;
  }
  await writeFile(file, text);
}
Example #18
Source File: ui5-model.ts    From ui5-language-assistant with Apache License 2.0 6 votes vote down vote up
async function readFromCache(filePath: string | undefined): Promise<unknown> {
  if (filePath !== undefined) {
    try {
      if ((await pathExists(filePath)) && (await lstat(filePath)).isFile()) {
        return await readJson(filePath);
      }
    } catch (err) {
      getLogger().warn("Could not read cache file For UI5 lib", {
        filePath,
        error: err,
      });
    }
  }
  return undefined;
}
Example #19
Source File: win32.ts    From TidGi-Desktop with Mozilla Public License 2.0 6 votes vote down vote up
async function findApplication(editor: WindowsExternalEditor) {
  for (const { key, subKey } of editor.registryKeys) {
    const keys = enumerateValues(key, subKey);
    if (keys.length === 0) {
      continue;
    }

    const { displayName, publisher, installLocation } = getAppInfo(editor, keys);

    if (!displayName.startsWith(editor.displayNamePrefix) || publisher !== editor.publisher) {
      logger.info(`Unexpected registry entries for ${editor.name}`);
      continue;
    }

    const executableShimPaths =
      editor.installLocationRegistryKey === 'DisplayIcon' ? [installLocation] : editor.executableShimPaths.map((p) => Path.join(installLocation, ...p));

    for (const path of executableShimPaths) {
      const exists = await pathExists(path);
      if (exists) {
        return path;
      }

      logger.info(`Executable for ${editor.name} not found at '${path}'`);
    }
  }

  return null;
}
Example #20
Source File: TagUseService.ts    From joplin-utils with MIT License 5 votes vote down vote up
private async init() {
    if (!(await pathExists(this.configPath))) {
      await mkdirp(path.dirname(this.configPath))
      await writeJson(this.configPath, {
        tagUse: [],
      })
    }
  }
Example #21
Source File: withFileLock.test.ts    From DefinitelyTyped-tools with MIT License 5 votes vote down vote up
describe("withFileLock", () => {
  // The file lock should be cleaned up as part of a successful test run,
  // but we clean up before and after just to make sure we don't create
  // any weird state with a failed or canceled test.
  beforeAll(() => {
    try {
      return remove(lockFilePath);
    } catch {
      return;
    }
  });
  afterAll(() => {
    try {
      return remove(lockFilePath);
    } catch {
      return;
    }
  });

  function getDeferred() {
    const eventEmitter = new EventEmitter();
    const resolve = () => eventEmitter.emit("resolve");
    const promise = new Promise<void>((resolve) => {
      eventEmitter.once("resolve", resolve);
    });
    return { resolve, promise };
  }

  it("works", async () => {
    const { resolve, promise } = getDeferred();

    // Awaiting `withFileLock` does not await its callback!
    // `promise` will be pending until we call `resolve()`,
    // but `withFileLock` writes a file and resolves as soon
    // as it can.
    const result1 = await withFileLock(lockFilePath, () => promise);
    expect(result1).toMatchObject({ triggered: true });

    // At this point the file still exists and `promise` is still
    // pending. Calling again should tell us that the callback
    // was not triggered due to an ongoing run.
    const result2 = await withFileLock(lockFilePath, () => Promise.resolve());
    expect(result2).toMatchObject({ triggered: false });
    expect(result2).toHaveProperty("timestamp");

    // Resolving our promise should clean up.
    resolve();
    await promise;
    expect(!(await pathExists(lockFilePath)));
  });
});
Example #22
Source File: index.ts    From joplin-utils with MIT License 5 votes vote down vote up
joplin.plugins.register({
  onStart: async function () {
    await joplin.settings.registerSettings({
      token: {
        label: 'token',
        description: 'token',
        type: SettingItemType.String,
        public: true,
        value: '',
      },
      port: {
        label: 'port',
        description: 'port',
        type: SettingItemType.Int,
        public: true,
        value: 41184,
      },
    })

    async function setupJoplinConfig() {
      const token = await joplin.settings.value('token')
      const port = await joplin.settings.value('port')
      if (!token || !port) {
        return false
      }
      config.token = token
      config.port = port
      return true
    }

    await joplin.interop.registerExportModule({
      description: 'Export Directory',
      format: 'folder',
      target: FileSystemItem.Directory,
      isNoteArchive: true,

      async onInit(context: ExportContext) {
        if (!(await setupJoplinConfig())) {
          return
        }
        const exporter = new Exporter({
          rootPath: context.destPath,
        })
        await exporter.export()
      },
      async onProcessItem() {},
      async onProcessResource() {},
      async onClose(_context: any) {},
    })
    await joplin.interop.registerImportModule({
      description: 'Import Directory',
      format: 'folder',
      sources: [FileSystemItem.Directory],
      isNoteArchive: false,

      async onExec(context: ImportContext) {
        if (!(await pathExists(path.resolve(context.sourcePath, 'config')))) {
          console.warn('导入目录不正确')
          return
        }
        const importer = new Importer({ rootPath: context.sourcePath })
        await importer.importArchive()
      },
    })
  },
})
Example #23
Source File: WikiCommander.ts    From joplin-utils with MIT License 5 votes vote down vote up
async checkConfig(): Promise<JoplinBlogConfig | false> {
    const configPath = path.resolve('.joplin-blog.json')
    if (!(await pathExists(configPath))) {
      console.error(i18n.t('common.notFoundConfig'))
      return false
    }
    return (await readJson(configPath)) as JoplinBlogConfig
  }
Example #24
Source File: CacheCommander.ts    From joplin-utils with MIT License 5 votes vote down vote up
async read() {
    if (!(await pathExists(this.cachePath))) {
      await this.init()
    }
    return (await readJson(this.cachePath)) as CacheConfig
  }
Example #25
Source File: BlogCommander.ts    From joplin-utils with MIT License 5 votes vote down vote up
async checkConfig(): Promise<JoplinBlogConfig | false> {
    const configPath = path.resolve('.joplin-blog.json')
    if (!(await pathExists(configPath))) {
      console.error(i18n.t('common.notFoundConfig'))
      return false
    }
    return (await readJson(configPath)) as JoplinBlogConfig
  }
Example #26
Source File: npm.ts    From DefinitelyTyped-tools with MIT License 5 votes vote down vote up
export async function withNpmCache<T>(
  uncachedClient: UncachedNpmInfoClient,
  cb: (client: CachedNpmInfoClient) => Promise<T>,
  cacheDir = defaultCacheDir
): Promise<T> {
  const log = loggerWithErrors()[0];
  const cacheFile = joinPaths(cacheDir, cacheFileBasename);
  let unroll: Map<string, NpmInfo>;
  log.info(`Checking for cache file at ${cacheFile}...`);
  const cacheFileExists = await pathExists(cacheFile);
  if (cacheFileExists) {
    log.info("Reading cache file...");
    const cachedJson = (await readJson(cacheFile)) as Record<string, NpmInfoRaw>;
    log.info(`Cache file ${cacheFile} exists, copying to map...`);
    unroll = recordToMap(cachedJson, npmInfoFromJson);
  } else {
    log.info("Cache file doesn't exist, using empty map.");
    unroll = new Map();
  }

  const res = await cb({ getNpmInfoFromCache, fetchAndCacheNpmInfo });
  log.info("Writing npm cache.");
  await ensureFile(cacheFile);
  await writeJson(cacheFile, mapToRecord(unroll, jsonFromNpmInfo));
  return res;

  /** May return old info -- caller should check that this looks up-to-date. */
  function getNpmInfoFromCache(escapedPackageName: string): NpmInfo | undefined {
    return unroll.get(escapedPackageName);
  }

  /** Call this when the result of getNpmInfoFromCache looks potentially out-of-date. */
  async function fetchAndCacheNpmInfo(escapedPackageName: string): Promise<NpmInfo | undefined> {
    const info = await uncachedClient.fetchNpmInfo(escapedPackageName);
    if (info) {
      unroll.set(escapedPackageName, info);
    }
    return info;
  }
}
Example #27
Source File: index.ts    From yarn-plugins with MIT License 5 votes vote down vote up
describe('add workspace', () => {
  beforeEach(async () => {
    await workspaces[0].yarn(['add', workspaces[1].name]);
  });

  afterEach(async () => {
    await workspaces[0].yarn(['remove', workspaces[1].name]);
  });

  describe('when tsconfig.json does not exist', () => {
    it('should not create tsconfig.json', async () => {
      expect(await pathExists(getTsConfigPath(workspaces[0]))).toBeFalse();
    });
  });

  describe('when tsconfig.json exist', () => {
    describe('target workspace does not have tsconfig.json', () => {
      setupTsConfig({});

      testTsConfig({});
    });

    describe('target workspace has tsconfig.json', () => {
      beforeAll(async () => {
        await writeTsConfig(workspaces[1], {});
      });

      afterAll(async () => {
        await deleteTsConfig(workspaces[1]);
      });

      describe('references does not exist', () => {
        setupTsConfig({
          compilerOptions: {},
        });

        testTsConfig({
          compilerOptions: {},
          references: [{ path: '../test-b' }],
        });
      });

      describe('references exist', () => {
        describe('references contain the workspace', () => {
          setupTsConfig({
            references: [{ path: '../test-b' }, { path: '../test-c' }],
          });

          testTsConfig({
            references: [{ path: '../test-b' }, { path: '../test-c' }],
          });
        });

        describe('references does not contain the workspace', () => {
          setupTsConfig({
            references: [{ path: '../test-c' }],
          });

          testTsConfig({
            references: [{ path: '../test-b' }, { path: '../test-c' }],
          });
        });
      });
    });
  });
});
Example #28
Source File: checks.ts    From DefinitelyTyped-tools with MIT License 5 votes vote down vote up
export async function checkPackageJson(dirPath: string, typesVersions: readonly TypeScriptVersion[]): Promise<void> {
  const pkgJsonPath = joinPaths(dirPath, "package.json");
  const needsTypesVersions = typesVersions.length !== 0;
  if (!(await pathExists(pkgJsonPath))) {
    if (needsTypesVersions) {
      throw new Error(`${dirPath}: Must have 'package.json' for "typesVersions"`);
    }
    return;
  }

  const pkgJson = (await readJson(pkgJsonPath)) as Record<string, unknown>;

  if ((pkgJson as any).private !== true) {
    throw new Error(`${pkgJsonPath} should set \`"private": true\``);
  }

  if (needsTypesVersions) {
    assert.strictEqual((pkgJson as any).types, "index", `"types" in '${pkgJsonPath}' should be "index".`);
    const expected = makeTypesVersionsForPackageJson(typesVersions);
    assert.deepEqual(
      (pkgJson as any).typesVersions,
      expected,
      `"typesVersions" in '${pkgJsonPath}' is not set right. Should be: ${JSON.stringify(expected, undefined, 4)}`
    );
  }

  for (const key in pkgJson) {
    // tslint:disable-line forin
    switch (key) {
      case "private":
      case "dependencies":
      case "license":
      case "imports":
      case "exports":
      case "type":
        // "private"/"typesVersions"/"types" checked above, "dependencies" / "license" checked by types-publisher,
        break;
      case "typesVersions":
      case "types":
        if (!needsTypesVersions) {
          throw new Error(`${pkgJsonPath} doesn't need to set "${key}" when no 'ts3.x' directories exist.`);
        }
        break;
      default:
        throw new Error(`${pkgJsonPath} should not include field ${key}`);
    }
  }
}
Example #29
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
  }