本文整理匯總了TypeScript中path.dirname函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript dirname函數的具體用法?TypeScript dirname怎麽用?TypeScript dirname使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了dirname函數的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1: main
async function main(): Promise<void> {
let packagingLocation: pkgLocationUtils.PackagingLocation;
try {
packagingLocation = await pkgLocationUtils.getPackagingUris(pkgLocationUtils.ProtocolType.NuGet);
} catch (error) {
tl.debug("Unable to get packaging URIs, using default collection URI");
tl.debug(JSON.stringify(error));
const collectionUrl = tl.getVariable("System.TeamFoundationCollectionUri");
packagingLocation = {
PackagingUris: [collectionUrl],
DefaultPackagingUri: collectionUrl};
}
let buildIdentityDisplayName: string = null;
let buildIdentityAccount: string = null;
try {
tl.setResourcePath(path.join(__dirname, "task.json"));
nutil.setConsoleCodePage();
// read inputs
let searchPattern = tl.getPathInput("searchPattern", true, false);
let allowEmptyNupkgMatch = tl.getBoolInput("continueOnEmptyNupkgMatch");
let filesList = nutil.resolveFilterSpec(
searchPattern,
tl.getVariable("System.DefaultWorkingDirectory") || process.cwd(),
allowEmptyNupkgMatch);
filesList.forEach(packageFile => {
if (!tl.stats(packageFile).isFile()) {
throw new Error(tl.loc("NotARegularFile", packageFile));
}
});
let connectedServiceName = tl.getInput("connectedServiceName");
let internalFeedUri = tl.getInput("feedName");
let nuGetAdditionalArgs = tl.getInput("nuGetAdditionalArgs");
let verbosity = tl.getInput("verbosity");
let nuGetFeedType = tl.getInput("nuGetFeedType") || "external";
// make sure the feed type is an expected one
let normalizedNuGetFeedType
= ["internal", "external"].find(x => nuGetFeedType.toUpperCase() === x.toUpperCase());
if (!normalizedNuGetFeedType) {
throw new Error(tl.loc("UnknownFeedType", nuGetFeedType));
}
nuGetFeedType = normalizedNuGetFeedType;
// due to a bug where we accidentally allowed nuGetPath to be surrounded by quotes before,
// locateNuGetExe() will strip them and check for existence there.
let nuGetPath = tl.getPathInput("nuGetPath", false, false);
let nugetUxOption = tl.getInput("nuGetversion");
let userNuGetProvided = false;
if (nuGetPath !== null && tl.filePathSupplied("nuGetPath")) {
nuGetPath = nutil.stripLeadingAndTrailingQuotes(nuGetPath);
userNuGetProvided = true;
if (nugetUxOption !== "custom")
{
// For back compat, if a path has already been specified then use it.
// However, warn the user in the build of this behavior.
tl.warning(tl.loc("Warning_ConflictingNuGetPreference"));
}
}
else {
if (nugetUxOption === "custom")
{
throw new Error(tl.loc("NoNuGetSpecified"))
}
// Pull the pre-installed path for NuGet.
let nuGetPathSuffix: string;
let versionToUse: string;
if (nugetUxOption === "4.0.0.2283") {
nuGetPathSuffix = "NuGet/4.0.0/";
versionToUse = "4.0.0";
}
else if (nugetUxOption === "3.5.0.1829") {
nuGetPathSuffix = "NuGet/3.5.0/";
versionToUse = "3.5.0";
}
else if (nugetUxOption === "3.3.0") {
nuGetPathSuffix = "NuGet/3.3.0/";
versionToUse = "3.3.0";
}
else {
throw new Error(tl.loc("NGCommon_UnabletoDetectNuGetVersion"));
}
// save and reset the tool path env var, so this task doesn't act as a tool installer
const tempNuGetPath = tl.getVariable(ngToolGetter.NUGET_EXE_TOOL_PATH_ENV_VAR);
const cachedVersion = await ngToolGetter.cacheBundledNuGet(versionToUse, nuGetPathSuffix);
nuGetPath = await ngToolGetter.getNuGet(cachedVersion);
tl.setVariable(ngToolGetter.NUGET_EXE_TOOL_PATH_ENV_VAR, tempNuGetPath);
}
//find nuget location to use
let credProviderPath = nutil.locateCredentialProvider();
const quirks = await ngToolRunner.getNuGetQuirksAsync(nuGetPath);
// clauses ordered in this way to avoid short-circuit evaluation, so the debug info printed by the functions
//.........這裏部分代碼省略.........
示例2: srcDirRelative
/**
* Convert a binDir-relative path to srcDir-relative
* @param from path to a file under the srcDir, like packages/core/testing/package.json
* @param file path to a file under the binDir, like bazel-bin/core/testing/generated.js
*/
function srcDirRelative(from: string, file: string) {
const result =
path.relative(path.dirname(from), path.join(srcDir, path.relative(binDir, file)));
if (result.startsWith('..')) return result;
return `./${result}`;
}
示例3: spawnSync
#!/usr/bin/env ts-node
import * as Path from 'path'
import chalk from 'chalk'
import { spawnSync } from 'child_process'
const shouldFix = process.argv.indexOf('--fix') > -1
const root = Path.dirname(__dirname)
const prettier = process.platform === 'win32' ? 'prettier.cmd' : 'prettier'
const prettierPath = Path.join(root, 'node_modules', '.bin', prettier)
const args = [
'**/*.{scss,y{,a}ml}',
'app/**/*.{ts,tsx}',
'script/**/*.ts',
'--list-different',
]
if (shouldFix) {
args.push('--write')
}
const result = spawnSync(prettierPath, args, {
cwd: root,
})
if (!shouldFix && result.status > 0) {
process.exitCode = result.status
示例4: getPTVSToolsFilePath
private getPTVSToolsFilePath(): string {
let currentFileName = module.filename;
let ptVSToolsPath = path.join(path.dirname(currentFileName), '..', '..', '..', '..', 'pythonFiles', 'PythonTools');
return path.join(ptVSToolsPath, 'visualstudio_py_launcher.py');
}
示例5: findLoadChildren
findLoadChildren(tsPath).forEach(moduleName => {
const fileName = path.resolve(path.dirname(tsPath), moduleName) + '.ts';
if (fs.existsSync(fileName)) {
result[moduleName] = fileName;
}
});
示例6: checkWindowsResult
async function checkWindowsResult(packager: Packager, packagerOptions: PackagerOptions, checkOptions: AssertPackOptions, artifacts: Array<ArtifactCreated>) {
const productName = getProductName(packager.metadata, packager.devMetadata)
function getWinExpected(archSuffix: string) {
return [
`RELEASES`,
`${productName} Setup 1.1.0${archSuffix}.exe`,
`TestApp-1.1.0${archSuffix}-full.nupkg`,
]
}
const archSuffix = (packagerOptions.arch || process.arch) === "x64" ? "" : "-ia32"
const expected = checkOptions == null || checkOptions.expectedArtifacts == null ? (archSuffix == "" ? getWinExpected(archSuffix) : getWinExpected(archSuffix).concat(getWinExpected(""))) : checkOptions.expectedArtifacts
const filenames = artifacts.map(it => path.basename(it.file))
assertThat(filenames.slice().sort()).deepEqual(expected.slice().sort())
if (checkOptions != null && checkOptions.expectedArtifacts != null) {
return
}
const expectedArtifactNames = expected.slice()
expectedArtifactNames[1] = `TestAppSetup-1.1.0${archSuffix}.exe`
assertThat(artifacts.map(it => it.artifactName).filter(it => it != null)).deepEqual([`TestApp-Setup-1.1.0${archSuffix}.exe`])
const packageFile = path.join(path.dirname(artifacts[0].file), `TestApp-1.1.0${archSuffix}-full.nupkg`)
const unZipper = new DecompressZip(packageFile)
const fileDescriptors = await unZipper.getFiles()
const files = pathSorter(fileDescriptors.map(it => it.path.replace(/\\/g, "/")).filter(it => (!it.startsWith("lib/net45/locales/") || it === "lib/net45/locales/en-US.pak") && !it.endsWith(".psmdcp")))
// console.log(JSON.stringify(files, null, 2))
const expectedContents = checkOptions == null || checkOptions.expectedContents == null ? expectedWinContents : checkOptions.expectedContents
assertThat(files).deepEqual(expectedContents.map(it => {
if (it === "lib/net45/TestApp.exe") {
return `lib/net45/${productName}.exe`
}
else {
return it
}
}))
if (checkOptions == null || checkOptions.expectedContents == null) {
await unZipper.extractFile(fileDescriptors.filter(it => it.path === "TestApp.nuspec")[0], {
path: path.dirname(packageFile),
})
const expectedSpec = (await readFile(path.join(path.dirname(packageFile), "TestApp.nuspec"), "utf8")).replace(/\r\n/g, "\n")
// console.log(expectedSpec)
assertThat(expectedSpec).equal(`<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
<metadata>
<id>TestApp</id>
<version>1.1.0</version>
<title>${productName}</title>
<authors>Foo Bar</authors>
<owners>Foo Bar</owners>
<iconUrl>https://raw.githubusercontent.com/szwacz/electron-boilerplate/master/resources/windows/icon.ico</iconUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>Test Application (test quite \" #378)</description>
<copyright>Copyright Š ${new Date().getFullYear()} Foo Bar</copyright>
<projectUrl>http://foo.example.com</projectUrl>
</metadata>
</package>`)
}
}
示例7: extractEditor
export function extractEditor(options: tss.ITreeShakingOptions & { destRoot: string }): void {
let result = tss.shake(options);
for (let fileName in result) {
if (result.hasOwnProperty(fileName)) {
writeFile(path.join(options.destRoot, fileName), result[fileName]);
}
}
let copied: { [fileName: string]: boolean; } = {};
const copyFile = (fileName: string) => {
if (copied[fileName]) {
return;
}
copied[fileName] = true;
const srcPath = path.join(options.sourcesRoot, fileName);
const dstPath = path.join(options.destRoot, fileName);
writeFile(dstPath, fs.readFileSync(srcPath));
};
const writeOutputFile = (fileName: string, contents: string) => {
writeFile(path.join(options.destRoot, fileName), contents);
};
for (let fileName in result) {
if (result.hasOwnProperty(fileName)) {
const fileContents = result[fileName];
const info = ts.preProcessFile(fileContents);
for (let i = info.importedFiles.length - 1; i >= 0; i--) {
const importedFileName = info.importedFiles[i].fileName;
let importedFilePath: string;
if (/^vs\/css!/.test(importedFileName)) {
importedFilePath = importedFileName.substr('vs/css!'.length) + '.css';
} else {
importedFilePath = importedFileName;
}
if (/(^\.\/)|(^\.\.\/)/.test(importedFilePath)) {
importedFilePath = path.join(path.dirname(fileName), importedFilePath);
}
if (/\.css$/.test(importedFilePath)) {
transportCSS(importedFilePath, copyFile, writeOutputFile);
} else {
if (fs.existsSync(path.join(options.sourcesRoot, importedFilePath + '.js'))) {
copyFile(importedFilePath + '.js');
}
}
}
}
}
const tsConfig = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.json')).toString());
tsConfig.compilerOptions.noUnusedLocals = false;
tsConfig.compilerOptions.preserveConstEnums = false;
tsConfig.compilerOptions.declaration = false;
writeOutputFile('tsconfig.json', JSON.stringify(tsConfig, null, '\t'));
[
'vs/css.build.js',
'vs/css.d.ts',
'vs/css.js',
'vs/loader.js',
'vs/monaco.d.ts',
'vs/nls.build.js',
'vs/nls.d.ts',
'vs/nls.js',
'vs/nls.mock.ts',
'typings/lib.ie11_safe_es6.d.ts',
'typings/thenable.d.ts',
'typings/es6-promise.d.ts',
'typings/require.d.ts',
].forEach(copyFile);
}
示例8: loadRules
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as fs from "fs";
import * as path from "path";
import { getRelativePath } from "./configuration";
import { showWarningOnce } from "./error";
import { AbstractRule } from "./language/rule/abstractRule";
import { IDisabledInterval, IOptions, IRule } from "./language/rule/rule";
import { arrayify, camelize, dedent } from "./utils";
const moduleDirectory = path.dirname(module.filename);
const CORE_RULES_DIRECTORY = path.resolve(moduleDirectory, ".", "rules");
const cachedRules = new Map<string, typeof AbstractRule | null>(); // null indicates that the rule was not found
export interface IEnableDisablePosition {
isEnabled: boolean;
position: number;
}
export function loadRules(ruleOptionsList: IOptions[],
enableDisableRuleMap: Map<string, IEnableDisablePosition[]>,
rulesDirectories?: string | string[],
isJs?: boolean): IRule[] {
const rules: IRule[] = [];
const notFoundRules: string[] = [];
const notAllowedInJsRules: string[] = [];
示例9: dirname
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { dirname } from 'path';
export const pkg = {
__filename: require.resolve('../../../package.json'),
__dirname: dirname(require.resolve('../../../package.json')),
// tslint:disable no-var-requires
...require('../../../package.json'),
};
示例10: getAppFromConfig
const init: any = (config: any, emitter: any, customFileHandlers: any) => {
const appConfig = getAppFromConfig(config.angularCli.app);
const appRoot = path.join(config.basePath, appConfig.root);
const testConfig: WebpackTestOptions = Object.assign({
environment: 'dev',
codeCoverage: false,
sourcemaps: true,
progress: process.stdout.isTTY === true,
preserveSymlinks: false,
}, config.angularCli);
if (testConfig.sourcemaps) {
// Add a reporter that fixes sourcemap urls.
config.reporters.unshift('@angular/cli');
// Code taken from https://github.com/tschaub/karma-source-map-support.
// We can't use it directly because we need to add it conditionally in this file, and karma
// frameworks cannot be added dynamically.
const smsPath = path.dirname(require.resolve('source-map-support'));
const ksmsPath = path.dirname(require.resolve('karma-source-map-support'));
addKarmaFiles(config.files, [
{ pattern: path.join(smsPath, 'browser-source-map-support.js'), watched: false },
{ pattern: path.join(ksmsPath, 'client.js'), watched: false }
], true);
}
// Add assets. This logic is mimics the one present in GlobCopyWebpackPlugin.
if (appConfig.assets) {
config.proxies = config.proxies || {};
appConfig.assets.forEach((pattern: AssetPattern) => {
// Convert all string patterns to Pattern type.
pattern = typeof pattern === 'string' ? { glob: pattern } : pattern;
// Add defaults.
// Input is always resolved relative to the appRoot.
pattern.input = path.resolve(appRoot, pattern.input || '');
pattern.output = pattern.output || '';
pattern.glob = pattern.glob || '';
// Build karma file pattern.
const assetPath = path.join(pattern.input, pattern.glob);
const filePattern = isDirectory(assetPath) ? assetPath + '/**' : assetPath;
addKarmaFiles(config.files, [{ pattern: filePattern, included: false }]);
// The `files` entry serves the file from `/base/{asset.input}/{asset.glob}`.
// We need to add a URL rewrite that exposes the asset as `/{asset.output}/{asset.glob}`.
let relativePath: string, proxyPath: string;
if (fs.existsSync(assetPath)) {
relativePath = path.relative(config.basePath, assetPath);
proxyPath = path.join(pattern.output, pattern.glob);
} else {
// For globs (paths that don't exist), proxy pattern.output to pattern.input.
relativePath = path.relative(config.basePath, pattern.input);
proxyPath = path.join(pattern.output);
}
// Proxy paths must have only forward slashes.
proxyPath = proxyPath.replace(/\\/g, '/');
config.proxies['/' + proxyPath] = '/base/' + relativePath;
});
}
// Add webpack config.
const webpackConfig = new WebpackTestConfig(testConfig, appConfig).buildConfig();
const webpackMiddlewareConfig = {
noInfo: true, // Hide webpack output because its noisy.
watchOptions: { poll: testConfig.poll },
publicPath: '/_karma_webpack_/',
stats: { // Also prevent chunk and module display output, cleaner look. Only emit errors.
assets: false,
colors: true,
version: false,
hash: false,
timings: false,
chunks: false,
chunkModules: false
}
};
// If Karma is being ran in single run mode, throw errors.
if (config.singleRun) {
webpackConfig.plugins.push(new KarmaWebpackThrowError());
}
// Use existing config if any.
config.webpack = Object.assign(webpackConfig, config.webpack);
config.webpackMiddleware = Object.assign(webpackMiddlewareConfig, config.webpackMiddleware);
// Remove the @angular/cli test file if present, for backwards compatibility.
const testFilePath = path.join(appRoot, appConfig.test);
config.files.forEach((file: any, index: number) => {
if (path.normalize(file.pattern) === testFilePath) {
config.files.splice(index, 1);
}
});
// When using code-coverage, auto-add coverage-istanbul.
config.reporters = config.reporters || [];
if (testConfig.codeCoverage && config.reporters.indexOf('coverage-istanbul') === -1) {
config.reporters.push('coverage-istanbul');
//.........這裏部分代碼省略.........