本文整理汇总了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)}`,
);
};
示例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];
示例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: [],
示例4: _getRealPath
private _getRealPath(filepath: Config.Path): Config.Path {
try {
return realpath(filepath) || filepath;
} catch (err) {
return filepath;
}
}
示例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;
};
示例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;
}
示例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)}`;
}
};
示例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;
};
示例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);
};
示例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>>;