fs-extra#existsSync TypeScript Examples

The following examples show how to use fs-extra#existsSync. 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: utils.ts    From cli with MIT License 7 votes vote down vote up
removeUselessFiles = async (target: string) => {
  const nm = join(target, 'node_modules');
  const list = await globby(uselessFilesMatch, {
    cwd: nm,
    deep: 10,
  });
  console.log('  - Useless files Count', list.length);
  let size = 0;
  for (const file of list) {
    const path = join(nm, file);
    if (existsSync(path)) {
      const stats = await stat(path);
      size += stats.size;
      await unlink(path);
    }
  }
  console.log(
    `  - Remove Useless file ${Number(size / (2 << 19)).toFixed(2)} MB`
  );
}
Example #2
Source File: index.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
function assertPathIsInDefinitelyTyped(dirPath: string, dtRoot: string): void {
  // TODO: It's not clear whether this assertion makes sense, and it's broken on Azure Pipelines (perhaps because DT isn't cloned into DefinitelyTyped)
  // Re-enable it later if it makes sense.
  // if (basename(dtRoot) !== "DefinitelyTyped")) {
  if (!existsSync(joinPaths(dtRoot, "types"))) {
    throw new Error(
      "Since this type definition includes a header (a comment starting with `// Type definitions for`), " +
        "assumed this was a DefinitelyTyped package.\n" +
        "But it is not in a `DefinitelyTyped/types/xxx` directory: " +
        dirPath
    );
  }
}
Example #3
Source File: utils.test.ts    From cli with MIT License 6 votes vote down vote up
describe('/test/utils.test.ts', () => {
  beforeAll(async done => {
    if (existsSync(nm)) {
      await remove(nm);
    }
    execSync(`cd ${demoDir};npm install`);
    done();
  });
  it('findModuleFromNodeModules', async () => {
    const deps = JSON.parse(
      readFileSync(join(demoDir, 'package.json')).toString()
    ).dependencies;
    const moduleInfoList = Object.keys(deps).map(name => {
      return {
        name,
        version: deps[name],
      };
    });
    const copyResult = await findModuleFromNodeModules(moduleInfoList, nm, nm);
    assert(Object.keys(copyResult).length > 1);
  });
  it('copyFromNodeModules', async () => {
    const deps = JSON.parse(
      readFileSync(join(demoDir, 'package.json')).toString()
    ).dependencies;
    const moduleInfoList = Object.keys(deps).map(name => {
      return {
        name,
        version: deps[name],
      };
    });
    const target = join(demoDir, 'node_modules2');
    if (existsSync(target)) {
      await remove(target);
    }
    const start = Date.now();
    const copyResult = await copyFromNodeModules(moduleInfoList, nm, target);
    const useTime = Date.now() - start;
    console.log('useTime', useTime);
    assert(copyResult.length);
  });
  it('not exists', async () => {
    const copyResult = await findModuleFromNodeModules(
      [{ name: 'xxx', version: '*' }],
      nm,
      nm
    );
    assert(!copyResult);
  });
  it('not match version', async () => {
    const deps = JSON.parse(
      readFileSync(join(demoDir, 'package.json')).toString()
    ).dependencies;
    const moduleInfoList = Object.keys(deps).map(name => {
      return {
        name: name + 'x',
        version: '^100',
      };
    });
    const copyResult = await findModuleFromNodeModules(moduleInfoList, nm, nm);
    assert(!copyResult);
  });
});
Example #4
Source File: index.ts    From nestjs-proto-gen-ts with MIT License 6 votes vote down vote up
private resolveRootPath(root: Root): void {
        const paths = this.options.path;
        const length = paths.length;

        // Search include paths when resolving imports
        root.resolvePath = (origin, target) => {
            let resolved = util.path.resolve(util.path.normalize(origin), util.path.normalize(target), false);

            const idx = resolved.lastIndexOf('google/protobuf/');

            if (idx > -1) {
                const altname = resolved.substring(idx);

                if (resolved.match(/google\/protobuf\//g).length > 1) {
                    resolved = resolved.split('google/protobuf')[0] + util.path.normalize(target);
                }

                if (altname in common) {
                    resolved = altname;
                }
            }

            if (existsSync(resolved)) {
                return resolved;
            }

            for (let i = 0; i < length; ++i) {
                const iresolved = util.path.resolve(paths[i] + '/', target);

                if (existsSync(iresolved)) {
                    return iresolved;
                }
            }

            return resolved;
        };
    }
Example #5
Source File: Sticker.ts    From wa-sticker-formatter with MIT License 6 votes vote down vote up
private _parse = async (): Promise<Buffer> =>
        Buffer.isBuffer(this.data)
            ? this.data
            : this.data.trim().startsWith('<svg')
            ? Buffer.from(this.data)
            : (async () =>
                  existsSync(this.data)
                      ? readFile(this.data)
                      : axios.get(this.data as string, { responseType: 'arraybuffer' }).then(({ data }) => data))()
Example #6
Source File: not-commonjs.test.ts    From cli with MIT License 6 votes vote down vote up
describe('test/not-commonjs.test.ts', () => {
  it('dev', async () => {
    const tsConfigFile = join(cwd, 'tsconfig.json');
    if (existsSync(tsConfigFile)) {
      await remove(tsConfigFile);
    }
    await copy(join(cwd, 'tsconfig.json.origin'), tsConfigFile);
    const { close, port, getData } = await run(cwd, {
      silent: true,
      fast: false,
    });
    const response = await fetch(`http://127.0.0.1:${port}/hello?name=midway`);
    const body = await response.text();
    const functions = await getData('functions');
    await close();
    const tsconfig = JSON.parse(readFileSync(tsConfigFile).toString());
    await remove(tsConfigFile);
    assert(functions.http);
    assert(body === 'hello world,midway');
    assert(tsconfig['ts-node'].compilerOptions.module === 'commonjs');
  });
});
Example #7
Source File: plugin-config-factory.ts    From malagu with MIT License 6 votes vote down vote up
create(config: WebpackChain, context: CliContext, target: string) {
        const { cfg } = context;
        const faviconPath = path.join(process.cwd(), 'favicon.ico');
        const faviconExists = existsSync(faviconPath);
        const templatePath = path.join(process.cwd(), 'index.html');
        const templateExists = existsSync(templatePath);
        const HtmlWebpackPlugin = require('html-webpack-plugin');
        const templatePathBase = path.join(__dirname, '..', '..', '..', 'templates');

        const c = ConfigUtil.getFrontendMalaguConfig(cfg);
        const baseHref = c.server?.path;

        config
            .plugin('html')
                .use(HtmlWebpackPlugin, [{
                    title: 'Malagu App',
                    template: templateExists ? undefined : path.join(templatePathBase, 'index.html'),
                    favicon: faviconExists ? undefined : path.join(templatePathBase, 'favicon.ico'),
                    templateParameters: ConfigUtil.getConfig(cfg, FRONTEND_TARGET),
                    base: { href: baseHref },
                    ...ConfigUtil.getWebpackConfig(cfg, FRONTEND_TARGET).htmlWebpackPlugin || {},
                    ...(templateExists ? { template: templatePath } : {}),
                    ...(faviconExists ? { favicon: faviconPath } : {})
                }])
            .end();
    }
Example #8
Source File: semantic-model-provider.ts    From ui5-language-assistant with Apache License 2.0 6 votes vote down vote up
export async function readTestLibraryFile(
  version: string,
  fileName: string
): Promise<FetchResponse> {
  try {
    // version might not actually be a TestModelVersion but we'll return ok === false in that case
    // since the file won't exist
    const inputFolder = getModelFolder(version as TestModelVersion);
    const filePath = resolve(inputFolder, fileName);
    const ok = existsSync(filePath);
    return {
      ok: ok,
      json: (): Promise<unknown> => readJson(filePath),
    };
  } catch (error) {
    return {
      ok: false,
      json: (): never => {
        throw error;
      },
    };
  }
}
Example #9
Source File: init-manager.ts    From malagu with MIT License 6 votes vote down vote up
protected async checkOutputDir(): Promise<void> {
        if (existsSync(this.outputDir)) {
            const answers = await inquirer.prompt([{
                name: 'remove',
                type: 'confirm',
                message: `App already exists, remove the app (dir: ${join(relative(process.cwd(), this.outputDir))})`
            }]);
            if (answers.remove) {
                rimraf.sync(this.outputDir);
            } else {
                process.exit(0);
            }
        }
    }
Example #10
Source File: AttachmentsFilesService.ts    From node-experience with MIT License 6 votes vote down vote up
static async  getTempFilesAttachments(emailNotification: EmailNotification): Promise<IFilesAttachments[]>
    {
        const filesystem = FilesystemFactory.create();

        emailNotification.tempFilesAttachments =  await Promise.all(emailNotification.attachedFiles.map(async(_file) =>
        {
            const stream = await filesystem.downloadStreamFile(_file);
            const fileName = `${_file.originalName}.${_file.extension}`;
            const uqFileName = `${_file.name}.${_file.extension}`;
            const tempDir = PATH.join(`${__dirname}/../../../temp`);
            const dirName = PATH.join(`${tempDir}/${uqFileName}`);
            // eslint-disable-next-line no-unused-expressions
            !existsSync(tempDir) && mkdirSync(tempDir);
            void await writeFile(dirName, '01011');
            const ws = createWriteStream(dirName);
            stream.pipe(ws);

            return {
                filename: fileName,
                path:dirName
            };
        }));

        return emailNotification.tempFilesAttachments;
    }
Example #11
Source File: env.ts    From malagu with MIT License 6 votes vote down vote up
hasProjectYarn = (cwd: string) => {
    if (_yarnProjects.has(cwd)) {
        return checkYarn(_yarnProjects.get(cwd));
    }

    const lockFile = path.join(cwd, 'yarn.lock');
    const result = existsSync(lockFile);
    _yarnProjects.set(cwd, result);
    return checkYarn(result);
}
Example #12
Source File: utils.test.ts    From cli with MIT License 6 votes vote down vote up
describe('faas-code-analysis:/test/utils.test.ts', () => {
  it('formatUpperCamel', async () => {
    const camel = formatUpperCamel('ABC');
    assert(camel === 'a-b-c');
  });

  it('compareFileChange', async () => {
    writeFileSync(join(base, 'a.txt'), Date.now() + '');
    const fileChange = await compareFileChange(['*.txt'], ['*.data'], {
      cwd: base,
    });
    assert(fileChange[0] === 'a.txt');

    const noFrom = await compareFileChange(['*.zip'], ['*.data'], {
      cwd: base,
    });
    assert(noFrom.length === 0);

    const noTo = await compareFileChange(['*.txt'], ['*.zip'], {
      cwd: base,
    });
    assert(noTo.length === 1);
    assert(noTo[0] === 'a.txt');

    writeFileSync(join(base, 'b.data'), Date.now() + '');
    const fileChange2 = await compareFileChange(['*.txt'], ['*.data'], {
      cwd: base,
    });
    assert(fileChange2.length === 0);
  });

  it('copyStaticFiles', async () => {
    await copyStaticFiles({ sourceDir: null, targetDir: null, log: null });
    const target = join(__dirname, 'tmpCopyFileDir');
    if (existsSync(target)) {
      await remove(target);
    }
    mkdirSync(target);
    await copyStaticFiles({
      sourceDir: base,
      targetDir: target,
      log: () => {},
    });
    assert(existsSync(join(target, 'a.txt')));
    assert(existsSync(join(target, 'b.data')));
    assert(!existsSync(join(target, 'c.ts')));

    await copyStaticFiles({
      sourceDir: base,
      targetDir: target,
      log: () => {},
    });
    await remove(target);
  });
});
Example #13
Source File: install-manager.ts    From malagu with MIT License 6 votes vote down vote up
protected async checkOutputDir(): Promise<void> {
        if (existsSync(this.outputDir)) {
            if (!this.opts.overwrite) {
                const answers = await inquirer.prompt([{
                    name: 'overwrite',
                    type: 'confirm',
                    message: 'Runtime already exists, overwrite the runtime'
                }]);
                if (!answers.overwrite) {
                    process.exit(0);
                }
            }
            await uninstall({ runtime: this.opts.alias || this.runtimeName });
        }
    }
Example #14
Source File: postInstall.ts    From cli with MIT License 6 votes vote down vote up
postInstall = async () => {
  // init cwd
  if (!process.env.INIT_CWD) {
    return;
  }
  const cwd = process.env.INIT_CWD;
  const pkgJsonFile = join(cwd, 'package.json');
  if (!existsSync(pkgJsonFile)) {
    return;
  }
  const pkg = JSON.parse(readFileSync(pkgJsonFile, 'utf-8'));
  const deps = Object.assign({}, pkg.dependencies, pkg.devDependencies);
  return {
    cwd,
    pkg,
    deps,
    pkgJsonFile,
  };
}
Example #15
Source File: index.ts    From nestjs-proto-gen-ts with MIT License 6 votes vote down vote up
private getProtoFiles(pkg: string): void {
        if (!existsSync(pkg)) {
            throw new Error(`Directory ${pkg} is not exist`);
        }

        const files = readdirSync(pkg);

        for (let i = 0; i < files.length; i++) {
            const filename = join(pkg, files[i]);
            const stat = lstatSync(filename);

            if (filename.indexOf(this.options.ignore.join()) > -1) {
                continue;
            }

            if (stat.isDirectory()) {
                this.getProtoFiles(filename);
            } else if (filename.indexOf(this.options.target.join()) > -1) {
                this.generate(filename, pkg);
            }
        }
    }
Example #16
Source File: index.ts    From cli with MIT License 6 votes vote down vote up
// remove useless file
  async safeRemoveUselessFile() {
    const files = [
      'src',
      'f.origin.yml',
      'f.yml',
      'jest.config.js',
      'tsconfig.json',
      'dist/.mwcc-cache',
      'dist/midway-build.json',
    ];

    await Promise.all(
      files.map(async file => {
        const filePosi = join(this.midwayBuildPath, file);
        if (existsSync(filePosi)) {
          await remove(filePosi);
        }
      })
    );

    const list = await globby(['**/*.d.ts', '**/*.ts.map', '**/*.js.map'], {
      cwd: join(this.midwayBuildPath, 'dist'),
      deep: 10,
    });

    for (const file of list) {
      const path = join(this.midwayBuildPath, 'dist', file);
      if (existsSync(path)) {
        await remove(path);
      }
    }
  }
Example #17
Source File: index.ts    From nestjs-proto-gen-ts with MIT License 6 votes vote down vote up
private generate(path: string, pkg: string): void {
        let hbTemplate = resolve(__dirname, '../..', this.options.template);

        //If absolute path we will know have custom template option
        if (isAbsolute(path)) {
            hbTemplate = path;
        }

        if (!existsSync(hbTemplate)) {
            throw new Error(`Template ${hbTemplate} is not found`);
        }

        const tmpl = readFileSync(hbTemplate, 'utf8');

        if (this.options.verbose) {
            console.log(chalk.blueBright(`-- found: `) + chalk.gray(path));
        }

        this.output(path, pkg, tmpl);
    }
Example #18
Source File: login.ts    From cli with Apache License 2.0 6 votes vote down vote up
export async function loginWithApiKey(
  apiKey: string,
  orgId: string,
  env: string
) {
  if (!existsSync(getConfigFilePath())) {
    throw 'Missing config file';
  }
  const cfg = await readJSON(getConfigFilePath());
  cfg.accessToken = apiKey;
  cfg.organization = orgId;
  cfg.environment = env;
  cfg.analyticsEnabled = false;
  cfg.anonymous = true;
  await writeJSON(getConfigFilePath(), cfg);
}
Example #19
Source File: build.ts    From malagu with MIT License 5 votes vote down vote up
export async function after(ctx: CliContext) {

    const genEntry = join(PathUtil.getBackendProjectDistPath(), 'gen-entry.js');
    if (existsSync(genEntry)) {
        remove(genEntry);
    }
}
Example #20
Source File: file.ts    From cli with Apache License 2.0 5 votes vote down vote up
function isEnvFileActive(projectPath: string) {
  return existsSync(join(projectPath, '.env'));
}
Example #21
Source File: detector-filesystem.ts    From malagu with MIT License 5 votes vote down vote up
protected async doHasPath(name: string): Promise<boolean> {
        return existsSync(resolve(this.projectPath, name));
    }
Example #22
Source File: index.ts    From cli with MIT License 5 votes vote down vote up
async newFormatCommand() {
    this.template = this.options.template;
    if (this.options.type) {
      this.template = templateList[this.options.type]?.package;
    }
    if (!this.template) {
      this.template = await this.userSelectTemplate();
    }

    if (!this.options.npm) {
      const { cmd, npm, registry } = findNpm();
      if (['yarn', 'pnpm'].includes(npm)) {
        this.options.npm = 'npm' + (registry ? ` --registry=${registry}` : '');
      } else {
        this.options.npm = cmd;
      }
    }

    const { commands } = this.core.coreOptions;
    let projectPath = this.options.target || commands[1];
    if (!projectPath) {
      projectPath = await new (enquirer as any).Input({
        message: 'What name would you like to use for the new project?',
        initial: 'midway-project',
      }).run();
    }
    this.projectName = projectPath;
    const { cwd } = this.core;
    this.core.debug('cwd', cwd);
    const projectDirPath = join(cwd, projectPath);
    if (existsSync(projectDirPath)) {
      const isOverwritten = await new (enquirer as any).Confirm({
        name: 'question',
        message: `The name '${projectPath}' already exists, is it overwritten?`,
        initial: true,
      }).run();
      if (!isOverwritten) {
        process.exit();
      }
      await remove(projectDirPath);
    }
    this.projectDirPath = projectDirPath;
  }
Example #23
Source File: module-builder.ts    From malagu with MIT License 5 votes vote down vote up
protected buildPath(componentPackage: ComponentPackage, modulePath: string) {
        let realPath = modulePath;
        if (modulePath.startsWith('@')) {
            realPath = modulePath.split(sep).join('/');
        } else if (this.pkg.isRoot(componentPackage)) {
            realPath = join(this.pkg.projectPath, modulePath).split(sep).join('/');
        } else {
            realPath = join(componentPackage.name, modulePath).split(sep).join('/');
        }
        try {
           return this.pkg.resolveModule(realPath);
        } catch (error) {
            const projectPath = this.pkg.projectPath.split(sep).join('/');
            if (realPath.indexOf(projectPath) === 0) {
                if (existsSync(resolve(`${realPath}.ts`))) {
                    return resolve(`${realPath}.ts`);
                } else if (existsSync(resolve(realPath))) {
                    return resolve(realPath);
                } else if (this.pkg.projectPath !== process.cwd()) {
                    realPath = join(process.cwd(), modulePath).split(sep).join('/');
                    if (existsSync(realPath)) {
                        return realPath;
                    } else if (existsSync(`${realPath}.js`)) {
                        return `${realPath}.js`;
                    } else if (existsSync(`${realPath}.ts`)) {
                        return `${realPath}.ts`;
                    }
                }
            } else if (realPath.indexOf(process.cwd()) === 0) {
                if (existsSync(resolve(`${realPath}.ts`))) {
                    return resolve(`${realPath}.ts`);
                } else if (existsSync(resolve(realPath))) {
                    return resolve(realPath);
                }
            } else if (existsSync(resolve(this.pkg.resolveModulePath(componentPackage.name), modulePath))) {
                return resolve(this.pkg.resolveModulePath(componentPackage.name), modulePath);
            }
            throw Error(`Module not found: ${realPath}`);
        }
    }
Example #24
Source File: index.ts    From cli with MIT License 5 votes vote down vote up
private safeRemove(path) {
    if (!existsSync(path)) {
      return;
    }
    return remove(path);
  }
Example #25
Source File: init-manager.ts    From malagu with MIT License 5 votes vote down vote up
async render(): Promise<void> {
        const packageJsonPath = resolve(this.outputDir, 'package.json');
        if (existsSync(packageJsonPath)) {
            const packageJson = await readJSON(packageJsonPath, { encoding: 'utf8' });
            packageJson.name = basename(this.outputDir);
            await writeJSON(packageJsonPath, packageJson, { encoding: 'utf8', spaces: 2 });
        }
    }
Example #26
Source File: create-fixture.ts    From dt-mergebot with MIT License 5 votes vote down vote up
export default async function main(directory: string, overwriteInfo: boolean) {
    const writeJsonSync = (file: string, json: unknown) =>
        writeFileSync(file, scrubDiagnosticDetails(JSON.stringify(json, undefined, 2) + "\n"));

    const fixturePath = join("src", "_tests", "fixtures", directory);
    const prNumber = parseInt(directory, 10);
    if (isNaN(prNumber)) throw new Error(`Expected ${directory} to be parseable as a PR number`);

    if (!existsSync(fixturePath)) mkdirSync(fixturePath);

    const jsonFixturePath = join(fixturePath, "_response.json");
    if (overwriteInfo || !existsSync(jsonFixturePath)) {
        writeJsonSync(jsonFixturePath, await getPRInfo(prNumber));
    }
    const response: ApolloQueryResult<PR> = readJsonSync(jsonFixturePath);

    const filesJSONPath = join(fixturePath, "_files.json");
    const filesFetched: {[expr: string]: string | undefined} = {};
    const downloadsJSONPath = join(fixturePath, "_downloads.json");
    const downloadsFetched: {[packageName: string]: number} = {};
    const derivedFixturePath = join(fixturePath, "derived.json");

    const shouldOverwrite = (file: string) => overwriteInfo || !existsSync(file);

    const prInfo = response.data.repository?.pullRequest;
    if (!prInfo) {
        console.error(`Could not get PR info for ${directory}, is the number correct?`);
        return;
    }

    const derivedInfo = await deriveStateForPR(
        prInfo,
        shouldOverwrite(filesJSONPath) ? initFetchFilesAndWriteToFile() : getFilesFromFile,
        shouldOverwrite(downloadsJSONPath) ? initGetDownloadsAndWriteToFile() : getDownloadsFromFile,
        shouldOverwrite(derivedFixturePath) ? undefined : getTimeFromFile(),
    );

    writeJsonSync(derivedFixturePath, derivedInfo);

    const resultFixturePath = join(fixturePath, "result.json");
    const actions = computeActions.process(derivedInfo);
    writeJsonSync(resultFixturePath, actions);

    const mutationsFixturePath = join(fixturePath, "mutations.json");
    const mutations = await executePrActions(actions, prInfo, /*dry*/ true);
    writeJsonSync(mutationsFixturePath, mutations);

    console.log("Recorded");

    function initFetchFilesAndWriteToFile() {
        writeJsonSync(filesJSONPath, {}); // one-time initialization of an empty storage
        return fetchFilesAndWriteToFile;
    }
    async function fetchFilesAndWriteToFile(expr: string, limit?: number) {
        filesFetched[expr] = await fetchFile(expr, limit);
        writeJsonSync(filesJSONPath, filesFetched);
        return filesFetched[expr];
    }
    function getFilesFromFile(expr: string) {
        return readJsonSync(filesJSONPath)[expr];
    }

    function initGetDownloadsAndWriteToFile() {
        writeJsonSync(downloadsJSONPath, {}); // one-time initialization of an empty storage
        return getDownloadsAndWriteToFile;
    }
    async function getDownloadsAndWriteToFile(packageName: string, until?: Date) {
        const downloads = await getMonthlyDownloadCount(packageName, until);
        downloadsFetched[packageName] = downloads;
        writeJsonSync(downloadsJSONPath, downloadsFetched);
        return downloads;
    }
    function getDownloadsFromFile(packageName: string) {
        return readJsonSync(downloadsJSONPath)[packageName];
    }

    function getTimeFromFile() {
        return new Date(readJsonSync(derivedFixturePath).now);
    }
}
Example #27
Source File: index.ts    From cli with MIT License 5 votes vote down vote up
async emit() {
    // 跳过编译
    if (this.options.skipBuild) {
      return;
    }
    const isTsDir = existsSync(join(this.servicePath, 'tsconfig.json'));
    this.core.cli.log('Building project directory files...');
    if (!isTsDir) {
      this.core.cli.log(' - Not found tsconfig.json and skip build');
      return;
    }
    this.core.cli.log(' - Using tradition build mode');

    const { diagnostics } = await this.program.emit();
    if (!diagnostics || !diagnostics.length) {
      return;
    }
    const errorNecessary = [];
    const errorUnnecessary = [];
    diagnostics.forEach(diagnostic => {
      if (diagnostic.category !== ts.DiagnosticCategory.Error) {
        return;
      }
      if (diagnostic.reportsUnnecessary) {
        errorUnnecessary.push(diagnostic);
      } else {
        errorNecessary.push(diagnostic);
      }
    });
    const cwd = this.getCwd();
    if (errorNecessary.length) {
      console.log('');
      errorNecessary.forEach(error => {
        let errorPath = '';
        // tsconfig error, file is undefined
        if (error?.file?.text) {
          const code = error.file.text.slice(0, error.start).split('\n');
          errorPath = `(${relative(cwd, error.file.fileName)}:${code.length}:${
            code[code.length - 1].length
          })`;
        }
        this.outputTsErrorMessage(error, errorPath);
      });
      if (!this.core.service?.experimentalFeatures?.ignoreTsError) {
        throw new Error(
          `Error: ${errorNecessary.length} ts error that must be fixed!`
        );
      }
    }

    if (errorUnnecessary.length) {
      errorUnnecessary.forEach(error => {
        const errorPath = `(${relative(cwd, error.file.fileName)})`;
        this.outputTsErrorMessage(error, errorPath);
      });
    }

    this.core.cli.log(' - Build project complete');
  }
Example #28
Source File: remixd.ts    From remix-project with MIT License 4 votes vote down vote up
(async () => {
  const { version } = require('../../package.json') // eslint-disable-line
  program.version(version, '-v, --version')

  program
    .description('Establish a two-way websocket connection between the local computer and Remix IDE for a folder')
    .option('-u, --remix-ide  <url>', 'URL of remix instance allowed to connect')
    .option('-s, --shared-folder <path>', 'Folder to share with Remix IDE (Default: CWD)')
    .option('-r, --read-only', 'Treat shared folder as read-only (experimental)')
    .on('--help', function () {
      console.log('\nExample:\n\n    remixd -s ./shared_project -u http://localhost:8080')
    }).parse(process.argv)
  // eslint-disable-next-line

  await warnLatestVersion()

  if (!program.remixIde) {
    console.log('\x1b[33m%s\x1b[0m', '[WARN] You can only connect to remixd from one of the supported origins.')
  } else {
    const isValid = await isValidOrigin(program.remixIde)
    /* Allow unsupported origins and display warning. */
    if (!isValid) {
      console.log('\x1b[33m%s\x1b[0m', '[WARN] You are using IDE from an unsupported origin.')
      console.log('\x1b[33m%s\x1b[0m', 'Check https://gist.github.com/EthereumRemix/091ccc57986452bbb33f57abfb13d173 for list of all supported origins.\n')
      // return
    }
    console.log('\x1b[33m%s\x1b[0m', '[WARN] You may now only use IDE at ' + program.remixIde + ' to connect to that instance')
  }

  if (!program.sharedFolder) program.sharedFolder = process.cwd() // if no specified, use the current folder

  if (program.sharedFolder && existsSync(absolutePath('./', program.sharedFolder))) {
    console.log('\x1b[33m%s\x1b[0m', '[WARN] Any application that runs on your computer can potentially read from and write to all files in the directory.')
    console.log('\x1b[33m%s\x1b[0m', '[WARN] Symbolic links are not forwarded to Remix IDE\n')
    try {
      startService('folder', (ws: WS, sharedFolderClient: servicesList.Sharedfolder, error: any) => {
        if (error) {
          errorHandler(error, 'hardhat')
          return false
        }
        sharedFolderClient.setWebSocket(ws)
        sharedFolderClient.setupNotifications(program.sharedFolder)
        sharedFolderClient.sharedFolder(program.sharedFolder)
      })
      startService('slither', (ws: WS, sharedFolderClient: servicesList.Sharedfolder) => {
        sharedFolderClient.setWebSocket(ws)
        sharedFolderClient.sharedFolder(program.sharedFolder)
      })
      // Run truffle service if a truffle project is shared as folder
      const truffleConfigFilePath = absolutePath('./', program.sharedFolder) + '/truffle-config.js'
      if (existsSync(truffleConfigFilePath)) {
        startService('truffle', (ws: WS, sharedFolderClient: servicesList.Sharedfolder, error: any) => {
          if (error) {
            errorHandler(error, 'truffle')
            return false
          }
          sharedFolderClient.setWebSocket(ws)
          sharedFolderClient.sharedFolder(program.sharedFolder)
        })
      }
      // Run hardhat service if a hardhat project is shared as folder
      const hardhatConfigFilePath = absolutePath('./', program.sharedFolder)
      const isHardhatProject = existsSync(hardhatConfigFilePath  + '/hardhat.config.js') || existsSync(hardhatConfigFilePath  + '/hardhat.config.ts')
      if (isHardhatProject) {
        startService('hardhat', (ws: WS, sharedFolderClient: servicesList.Sharedfolder, error: Error) => {
          if (error) {
            errorHandler(error, 'hardhat')
            return false
          }
          sharedFolderClient.setWebSocket(ws)
          sharedFolderClient.sharedFolder(program.sharedFolder)
        })
      }
      /*
      startService('git', (ws: WS, sharedFolderClient: servicesList.Sharedfolder) => {
        sharedFolderClient.setWebSocket(ws)
        sharedFolderClient.sharedFolder(program.sharedFolder)
      })
      */
    } catch (error) {
      throw new Error(error)
    }
  } else {
    console.log('\x1b[31m%s\x1b[0m', '[ERR] No valid shared folder provided.')
  }

  // kill
  function kill () {
    for (const k in killCallBack) {
      try {
        killCallBack[k]()
      } catch (e) {
        console.log(e)
      }
    }
    process.exit(0)
  }

  process.on('SIGINT', kill) // catch ctrl-c
  process.on('SIGTERM', kill) // catch kill
  process.on('exit', kill)

  async function isValidOrigin (origin: string): Promise<any> {
    if (!origin) return false
    const domain = getDomain(origin)
    const gistUrl = 'https://gist.githubusercontent.com/EthereumRemix/091ccc57986452bbb33f57abfb13d173/raw/3367e019335746b73288e3710af2922d4c8ef5a3/origins.json'

    try {
      const { data } = (await Axios.get(gistUrl)) as { data: any }

      try {
        await writeJSON(path.resolve(path.join(__dirname, '../..', 'origins.json')), { data })
      } catch (e) {
        console.error(e)
      }

      const dataArray:string[] = data
      return dataArray.includes(origin) ? dataArray.includes(origin) : dataArray.includes(domain)
    } catch (e) {
      try {
        // eslint-disable-next-line
        const origins = require('../../origins.json')
        const { data } = origins

        return data.includes(origin) ? data.includes(origin) : data.includes(domain)
      } catch (e) {
        return false
      }
    }
  }
})()
Example #29
Source File: build.test.ts    From cli with MIT License 4 votes vote down vote up
describe('test/build.test.ts', () => {
  it('build', async () => {
    const dist = join(cwd, 'dist');
    if (existsSync(dist)) {
      await remove(dist);
    }
    await run(cwd, 'build');
    assert(existsSync(join(dist, 'index.js')));
    assert(existsSync(join(dist, 'app/public/public.js')));
    assert(!existsSync(join(dist, 'a.js')));
  });
  it('build clean', async () => {
    const dist = join(cwd, 'dist');
    if (existsSync(dist)) {
      await remove(dist);
    }
    await run(cwd, 'build', { clean: true });
    assert(existsSync(join(dist, 'index.js')));
  });
  it('copyfile', async () => {
    const dist = join(cwd, 'dist');
    if (existsSync(dist)) {
      await remove(dist);
    }
    await run(cwd, 'build', { clean: true, include: 'a.js' });
    assert(existsSync(join(dist, 'a.js')));
    assert(existsSync(join(dist, 'index.js')));
    assert(existsSync(join(dist, 'a.json')));
    assert(existsSync(join(dist, 'b/b.txt')));
    assert(existsSync(join(dist, 'c')));
  });

  it('error ts', async () => {
    const errorcwd = join(__dirname, 'fixtures/error-ts');
    const dist = join(errorcwd, 'dist');
    if (existsSync(dist)) {
      await remove(dist);
    }
    try {
      await run(errorcwd, 'build');
    } catch (e) {
      assert(/stringx/.test(e.message));
    }
  });
  it('ignore error ts', async () => {
    const errorcwd = join(__dirname, 'fixtures/error-ts-ignore');
    const dist = join(errorcwd, 'dist');
    if (existsSync(dist)) {
      await remove(dist);
    }
    await run(errorcwd, 'build', { buildCache: false });
  });
  it('error no ts config', async () => {
    const errorcwd = join(__dirname, 'fixtures/error-no-tsconfig');
    const dist = join(errorcwd, 'dist');
    if (existsSync(dist)) {
      await remove(dist);
    }
    try {
      await run(errorcwd, 'build');
    } catch (e) {
      assert(/tsconfig\.json not found/.test(e.message));
    }
  });
  it('error ts config options', async () => {
    const errorcwd = join(__dirname, 'fixtures/error-no-tsconfig');
    const dist = join(errorcwd, 'dist');
    if (existsSync(dist)) {
      await remove(dist);
    }
    try {
      await run(errorcwd, 'build', {
        tsConfig: 'xxx',
      });
    } catch (e) {
      assert(/Unexpected token x/.test(e.message));
    }
  });
  it('ts config options', async () => {
    const errorcwd = join(__dirname, 'fixtures/error-no-tsconfig');
    const dist = join(errorcwd, 'dist');
    if (existsSync(dist)) {
      await remove(dist);
    }
    await run(errorcwd, 'build', {
      tsConfig: JSON.stringify({
        compileOnSave: true,
        compilerOptions: {
          rootDir: 'src',
          outDir: 'dist',
        },
        include: ['./src/**/*.ts'],
      }),
    });
    assert(existsSync(join(dist, 'index.js')));
  });
  it('error ts config file', async () => {
    const errorcwd = join(__dirname, 'fixtures/error-tsconfig');
    const dist = join(errorcwd, 'dist');
    if (existsSync(dist)) {
      await remove(dist);
    }
    try {
      await run(errorcwd, 'build');
    } catch (e) {
      assert(/Unexpected token \//.test(e.message));
    }
  });
  it('test hooks', async () => {
    const hooks = join(__dirname, 'fixtures/hooks');
    const dist = join(hooks, 'dist');
    if (existsSync(dist)) {
      await remove(dist);
    }
    execSync(`cd ${hooks};npm i`);
    await run(hooks, 'build');
  });
  it('bundle', async () => {
    const bundle = join(__dirname, 'fixtures/bundle');
    const dist = join(bundle, 'dist');
    if (existsSync(dist)) {
      await remove(dist);
    }
    execSync(`cd ${bundle};npm i`);
    await run(bundle, 'build', { bundle: true });
    assert(existsSync(join(bundle, 'dist/bundle.js')));
  });
});