• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript realpath-native.sync函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中realpath-native.sync函数的典型用法代码示例。如果您正苦于以下问题:TypeScript sync函数的具体用法?TypeScript sync怎么用?TypeScript sync使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了sync函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: async

export default async (rootDir: string = realpath(process.cwd())) => {
  // prerequisite checks
  const projectPackageJsonPath: string = path.join(rootDir, PACKAGE_JSON);
  const jestConfigPath: string = path.join(rootDir, JEST_CONFIG);

  if (!fs.existsSync(projectPackageJsonPath)) {
    throw new NotFoundPackageJsonError(rootDir);
  }

  const questions = defaultQuestions.slice(0);
  let hasJestProperty: boolean = false;
  let hasJestConfig: boolean = false;
  let projectPackageJson: ProjectPackageJson;

  try {
    projectPackageJson = JSON.parse(
      fs.readFileSync(projectPackageJsonPath, 'utf-8'),
    );
  } catch (error) {
    throw new MalformedPackageJsonError(projectPackageJsonPath);
  }

  if (projectPackageJson.jest) {
    hasJestProperty = true;
  }

  if (fs.existsSync(jestConfigPath)) {
    hasJestConfig = true;
  }

  if (hasJestProperty || hasJestConfig) {
    const result: {continue: boolean} = await prompts({
      initial: true,
      message:
        'It seems that you already have a jest configuration, do you want to override it?',
      name: 'continue',
      type: 'confirm',
    });

    if (!result.continue) {
      console.log();
      console.log('Aborting...');
      return;
    }
  }

  // Add test script installation only if needed
  if (
    !projectPackageJson.scripts ||
    projectPackageJson.scripts.test !== 'jest'
  ) {
    questions.unshift(testScriptQuestion);
  }

  // Start the init process
  console.log();
  console.log(
    chalk.underline(
      `The following questions will help Jest to create a suitable configuration for your project\n`,
    ),
  );

  let promptAborted: boolean = false;

  // @ts-ignore: Return type cannot be object - faulty typings
  const results: PromptsResults = await prompts(questions, {
    onCancel: () => {
      promptAborted = true;
    },
  });

  if (promptAborted) {
    console.log();
    console.log('Aborting...');
    return;
  }

  const shouldModifyScripts = results.scripts;

  if (shouldModifyScripts || hasJestProperty) {
    const modifiedPackageJson = modifyPackageJson({
      projectPackageJson,
      shouldModifyScripts,
    });

    fs.writeFileSync(projectPackageJsonPath, modifiedPackageJson);

    console.log('');
    console.log(`✏️  Modified ${chalk.cyan(projectPackageJsonPath)}`);
  }

  const generatedConfig = generateConfigFile(results);

  fs.writeFileSync(jestConfigPath, generatedConfig);

  console.log('');
  console.log(
    `📝  Configuration file created at ${chalk.cyan(jestConfigPath)}`,
  );
};
开发者ID:Volune,项目名称:jest,代码行数:100,代码来源:index.ts


示例2: normalize


//.........这里部分代码省略.........
      case 'testPathIgnorePatterns':
      case 'transformIgnorePatterns':
      case 'watchPathIgnorePatterns':
      case 'unmockedModulePathPatterns':
        value = normalizeUnmockedModulePathPatterns(oldOptions, key);
        break;
      case 'haste':
        value = {...oldOptions[key]};
        if (value.hasteImplModulePath != null) {
          const resolvedHasteImpl = resolve(newOptions.resolver, {
            filePath: replaceRootDirInPath(
              options.rootDir,
              value.hasteImplModulePath,
            ),
            key: 'haste.hasteImplModulePath',
            rootDir: options.rootDir,
          });

          value.hasteImplModulePath = resolvedHasteImpl || undefined;
        }
        break;
      case 'projects':
        value = (oldOptions[key] || [])
          .map(project =>
            typeof project === 'string'
              ? _replaceRootDirTags(options.rootDir, project)
              : project,
          )
          .reduce((projects, project) => {
            // Project can be specified as globs. If a glob matches any files,
            // We expand it to these paths. If not, we keep the original path
            // for the future resolution.
            const globMatches =
              typeof project === 'string' ? glob.sync(project) : [];
            return projects.concat(globMatches.length ? globMatches : project);
          }, []);
        break;
      case 'moduleDirectories':
      case 'testMatch':
        {
          const replacedRootDirTags = _replaceRootDirTags(
            escapeGlobCharacters(options.rootDir),
            oldOptions[key],
          );

          if (replacedRootDirTags) {
            value = Array.isArray(replacedRootDirTags)
              ? replacedRootDirTags.map(replacePathSepForGlob)
              : replacePathSepForGlob(replacedRootDirTags);
          } else {
            value = replacedRootDirTags;
          }
        }
        break;
      case 'testRegex':
        {
          const option = oldOptions[key];
          value = option
            ? (Array.isArray(option) ? option : [option]).map(
                replacePathSepForRegex,
              )
            : [];
        }
        break;
      case 'moduleFileExtensions': {
        value = oldOptions[key];
开发者ID:Volune,项目名称:jest,代码行数:67,代码来源:normalize.ts


示例3: cleanup

/**
 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import os from 'os';
import path from 'path';
import HasteMap from 'jest-haste-map';
import {sync as realpath} from 'realpath-native';
import {cleanup, writeFiles} from '../Utils';

const DIR = path.resolve(realpath(os.tmpdir()), 'haste_map_size');

beforeEach(() => {
  cleanup(DIR);
  writeFiles(DIR, {
    'file.js': '"abc"',
  });
});
afterEach(() => cleanup(DIR));

const options = {
  extensions: ['js'],
  forceNodeFilesystemAPI: true,
  ignorePattern: / ^/,
  maxWorkers: 2,
  mocksPattern: '',
  name: 'tmp',
  platforms: [],
开发者ID:Volune,项目名称:jest,代码行数:31,代码来源:hasteMapSize.test.ts


示例4: _getRealPath

 private _getRealPath(filepath: Config.Path): Config.Path {
   try {
     return realpath(filepath) || filepath;
   } catch (err) {
     return filepath;
   }
 }
开发者ID:Volune,项目名称:jest,代码行数:7,代码来源:ScriptTransformer.ts


示例5: catch

const getProjectListFromCLIArgs = (
  argv: Config.Argv,
  project?: Config.Path,
) => {
  const projects = argv.projects ? argv.projects : [];

  if (project) {
    projects.push(project);
  }

  if (!projects.length && process.platform === 'win32') {
    try {
      projects.push(realpath(process.cwd()));
    } catch (err) {
      // do nothing, just catch error
      // process.binding('fs').realpath can throw, e.g. on mapped drives
    }
  }

  if (!projects.length) {
    projects.push(process.cwd());
  }

  return projects;
};
开发者ID:facebook,项目名称:jest,代码行数:25,代码来源:index.ts


示例6: nodeModulesPaths

export default function nodeModulesPaths(
  basedir: Config.Path,
  options: NodeModulesPathsOptions,
): Array<Config.Path> {
  const modules =
    options && options.moduleDirectory
      ? Array.from(options.moduleDirectory)
      : ['node_modules'];

  // ensure that `basedir` is an absolute path at this point,
  // resolving against the process' current working directory
  const basedirAbs = path.resolve(basedir);

  let prefix = '/';
  if (/^([A-Za-z]:)/.test(basedirAbs)) {
    prefix = '';
  } else if (/^\\\\/.test(basedirAbs)) {
    prefix = '\\\\';
  }

  // The node resolution algorithm (as implemented by NodeJS and TypeScript)
  // traverses parents of the physical path, not the symlinked path
  let physicalBasedir;
  try {
    physicalBasedir = realpath(basedirAbs);
  } catch (err) {
    // realpath can throw, e.g. on mapped drives
    physicalBasedir = basedirAbs;
  }

  const paths: Array<Config.Path> = [physicalBasedir];
  let parsed = path.parse(physicalBasedir);
  while (parsed.dir !== paths[paths.length - 1]) {
    paths.push(parsed.dir);
    parsed = path.parse(parsed.dir);
  }

  const dirs = paths
    .reduce(
      (dirs, aPath) =>
        dirs.concat(
          modules.map(moduleDir =>
            path.isAbsolute(moduleDir)
              ? aPath === basedirAbs
                ? moduleDir
                : ''
              : path.join(prefix, aPath, moduleDir),
          ),
        ),
      [] as Array<Config.Path>,
    )
    .filter(dir => dir !== '');

  return options.paths ? dirs.concat(options.paths) : dirs;
}
开发者ID:Volune,项目名称:jest,代码行数:55,代码来源:nodeModulesPaths.ts


示例7:

const getCacheDirectory = () => {
  const {getuid} = process;
  const tmpdir = path.join(realpath(os.tmpdir()), 'jest');
  if (getuid == null) {
    return tmpdir;
  } else {
    // On some platforms tmpdir() is `/tmp`, causing conflicts between different
    // users and permission issues. Adding an additional subdivision by UID can
    // help.
    return `${tmpdir}_${getuid.call(process).toString(36)}`;
  }
};
开发者ID:Volune,项目名称:jest,代码行数:12,代码来源:getCacheDirectory.ts


示例8: createConfigError

const normalizeRootDir = (
  options: Config.InitialOptions,
): Config.InitialOptions => {
  // Assert that there *is* a rootDir
  if (!options.hasOwnProperty('rootDir')) {
    throw createConfigError(
      `  Configuration option ${chalk.bold('rootDir')} must be specified.`,
    );
  }
  options.rootDir = path.normalize(options.rootDir);

  try {
    // try to resolve windows short paths, ignoring errors (permission errors, mostly)
    options.rootDir = realpath(options.rootDir);
  } catch (e) {
    // ignored
  }

  return options;
};
开发者ID:Volune,项目名称:jest,代码行数:20,代码来源:normalize.ts


示例9: collectHandles

const processResults = (
  runResults: AggregatedResult,
  options: ProcessResultOptions,
) => {
  const {
    outputFile,
    json: isJSON,
    onComplete,
    outputStream,
    testResultsProcessor,
    collectHandles,
  } = options;

  if (collectHandles) {
    runResults.openHandles = collectHandles();
  } else {
    runResults.openHandles = [];
  }

  if (testResultsProcessor) {
    runResults = require(testResultsProcessor)(runResults);
  }
  if (isJSON) {
    if (outputFile) {
      const cwd = realpath(process.cwd());
      const filePath = path.resolve(cwd, outputFile);

      fs.writeFileSync(filePath, JSON.stringify(formatTestResults(runResults)));
      outputStream.write(
        `Test results written to: ${path.relative(cwd, filePath)}\n`,
      );
    } else {
      process.stdout.write(JSON.stringify(formatTestResults(runResults)));
    }
  }

  return onComplete && onComplete(runResults);
};
开发者ID:Volune,项目名称:jest,代码行数:38,代码来源:runJest.ts


示例10: realpath

};

type BooleanObject = Record<string, boolean>;

namespace Resolver {
  export type ResolveModuleConfig = {
    skipNodeResolution?: boolean;
    paths?: Array<Config.Path>;
  };
}

const NATIVE_PLATFORM = 'native';

// We might be inside a symlink.
const cwd = process.cwd();
const resolvedCwd = realpath(cwd) || cwd;
const {NODE_PATH} = process.env;
const nodePaths = NODE_PATH
  ? NODE_PATH.split(path.delimiter)
      .filter(Boolean)
      // The resolver expects absolute paths.
      .map(p => path.resolve(resolvedCwd, p))
  : undefined;

/* eslint-disable-next-line no-redeclare */
class Resolver {
  private readonly _options: ResolverConfig;
  private readonly _moduleMap: ModuleMap;
  private readonly _moduleIDCache: Map<string, string>;
  private readonly _moduleNameCache: Map<string, Config.Path>;
  private readonly _modulePathCache: Map<string, Array<Config.Path>>;
开发者ID:facebook,项目名称:jest,代码行数:31,代码来源:index.ts



注:本文中的realpath-native.sync函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript rebirth-common.RebirthWindow类代码示例发布时间:2022-05-25
下一篇:
TypeScript readline.Interface类代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap