本文整理汇总了TypeScript中path.basename函数的典型用法代码示例。如果您正苦于以下问题:TypeScript basename函数的具体用法?TypeScript basename怎么用?TypeScript basename使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了basename函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1:
return files.map((filename) => path.basename(filename, '.json'));
示例2: extractVersion
function extractVersion(file): string {
var result;
result = path.basename(file);
result = result.slice(0, result.indexOf('.transformation.js'))
return result;
}
示例3: handler
//.........这里部分代码省略.........
console.log(`Directory ${chalk.cyan(projectPath)} must be empty.`)
return
}
} else {
fs.mkdirSync(projectPath)
}
// allow short handle boilerplate (e.g. `node-basic`)
if (boilerplate && !boilerplate.startsWith('http')) {
const matchedBoilerplate = defaultBoilerplates.find(
b => b.name === boilerplate,
)
if (matchedBoilerplate) {
boilerplate = matchedBoilerplate.repo
} else {
// allow shorthand GitHub URLs (e.g. `graphcool/graphcool-server-example`)
boilerplate = getGitHubUrl(boilerplate)
}
}
// interactive selection
if (!boilerplate) {
const maxNameLength = defaultBoilerplates
.map(bp => bp.name.length)
.reduce((max, x) => Math.max(max, x), 0)
const choices = defaultBoilerplates.map(
bp => `${padEnd(bp.name, maxNameLength + 2)} ${bp.description}`,
)
const { choice } = await context.prompt({
type: 'list',
name: 'choice',
message: `Choose GraphQL boilerplate project:`,
choices,
})
boilerplate = defaultBoilerplates[choices.indexOf(choice)].repo
}
// download repo contents
const zipInfo = getZipInfo(boilerplate!)
const downloadUrl = zipInfo.url
const tmpFile = tmp.fileSync()
console.log(`[graphql create] Downloading boilerplate from ${downloadUrl}...`)
await new Promise(resolve => {
request(downloadUrl)
.pipe(fs.createWriteStream(tmpFile.name))
.on('close', resolve)
})
const zip = new Zip(tmpFile.name)
zip.extractEntryTo(zipInfo.path, projectPath, false)
tmpFile.removeCallback()
// run npm/yarn install
if (!noInstall) {
const subDirs = fs
.readdirSync(projectPath)
.map(f => path.join(projectPath, f))
.filter(f => fs.statSync(f).isDirectory())
const installPaths = [projectPath, ...subDirs]
.map(dir => path.join(dir, 'package.json'))
.filter(p => fs.existsSync(p))
for (const packageJsonPath of installPaths) {
process.chdir(path.dirname(packageJsonPath))
console.log(
`[graphql create] Installing node dependencies for ${packageJsonPath}...`,
)
if (commandExists.sync('yarn')) {
await shell('yarn install')
} else {
await shell('npm install')
}
}
}
// change dir to projectPath for install steps
process.chdir(projectPath)
// run & delete setup script
let installPath = path.join(projectPath, 'install.js')
if (!fs.existsSync(installPath)) {
installPath = path.join(projectPath, '.install')
}
if (fs.existsSync(installPath)) {
console.log(`[graphql create] Running boilerplate install script... `)
const installFunction = require(installPath)
await installFunction({
context,
project: path.basename(projectPath),
projectDir: directory,
})
rimraf.sync(installPath)
}
}
示例4: done
this.checkFilePatternAbsoluteMatch((exists, size) => {
if (this.isCanceled) {
return done(null, this.isLimitHit);
}
// Report result from file pattern if matching
if (exists) {
this.resultCount++;
onResult({
relativePath: this.filePattern,
basename: path.basename(this.filePattern),
size
});
// Optimization: a match on an absolute path is a good result and we do not
// continue walking the entire root paths array for other matches because
// it is very unlikely that another file would match on the full absolute path
return done(null, this.isLimitHit);
}
// For each extra file
if (extraFiles) {
extraFiles.forEach(extraFilePath => {
const basename = path.basename(extraFilePath);
if (this.globalExcludePattern && this.globalExcludePattern(extraFilePath, basename)) {
return; // excluded
}
// File: Check for match on file pattern and include pattern
this.matchFile(onResult, { relativePath: extraFilePath /* no workspace relative path */, basename });
});
}
let traverse = this.nodeJSTraversal;
if (!this.maxFilesize) {
if (this.useRipgrep) {
this.traversal = Traversal.Ripgrep;
traverse = this.cmdTraversal;
} else if (platform.isMacintosh) {
this.traversal = Traversal.MacFind;
traverse = this.cmdTraversal;
// Disable 'dir' for now (#11181, #11179, #11183, #11182).
} /* else if (platform.isWindows) {
this.traversal = Traversal.WindowsDir;
traverse = this.windowsDirTraversal;
} */ else if (platform.isLinux) {
this.traversal = Traversal.LinuxFind;
traverse = this.cmdTraversal;
}
}
const isNodeTraversal = traverse === this.nodeJSTraversal;
if (!isNodeTraversal) {
this.cmdForkStartTime = Date.now();
}
// For each root folder
flow.parallel<IFolderSearch, void>(folderQueries, (folderQuery: IFolderSearch, rootFolderDone: (err: Error, result: void) => void) => {
this.call(traverse, this, folderQuery, onResult, onMessage, (err?: Error) => {
if (err) {
const errorMessage = toErrorMessage(err);
console.error(errorMessage);
this.errors.push(errorMessage);
rootFolderDone(err, undefined);
} else {
rootFolderDone(undefined, undefined);
}
});
}, (errors, result) => {
const err = errors ? errors.filter(e => !!e)[0] : null;
done(err, this.isLimitHit);
});
});
示例5: getJsPath
function getJsPath(tsPath: string): string {
return path.join(path.dirname(tsPath), path.basename(tsPath, ".ts")) + ".js";
}
示例6:
path.isAbsolute('bar\\baz') // false
path.isAbsolute('.') // false
path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb')
// returns
// '..\\..\\impl\\bbb'
path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')
// returns
// '../../impl/bbb'
path.dirname('/foo/bar/baz/asdf/quux')
// returns
// '/foo/bar/baz/asdf'
path.basename('/foo/bar/baz/asdf/quux.html')
// returns
// 'quux.html'
path.basename('/foo/bar/baz/asdf/quux.html', '.html')
// returns
// 'quux'
path.extname('index.html')
// returns
// '.html'
path.extname('index.coffee.md')
// returns
// '.md'
示例7: execute
async execute(editor?: TextEditor, uri?: Uri, args: ShowQuickFileHistoryCommandArgs = {}) {
uri = getCommandUri(uri, editor);
if (uri == null) return commands.executeCommand(Commands.ShowQuickCurrentBranchHistory);
const gitUri = await GitUri.fromUri(uri);
if (args.showInView) {
await Container.fileHistoryView.showHistoryForUri(gitUri);
return undefined;
}
args = { ...args };
const placeHolder = `${gitUri.getFormattedPath({
suffix: args.reference ? ` (${args.reference.name})` : undefined
})}${gitUri.sha ? ` ${Strings.pad(GlyphChars.Dot, 1, 1)} ${gitUri.shortSha}` : ''}`;
const progressCancellation = FileHistoryQuickPick.showProgress(placeHolder);
try {
if (args.log === undefined) {
args.log = await Container.git.getLogForFile(gitUri.repoPath, gitUri.fsPath, {
maxCount: args.maxCount,
range: args.range,
ref: (args.reference && args.reference.ref) || gitUri.sha
});
if (args.log === undefined) {
if (args.reference) {
return window.showWarningMessage(`The file could not be found in ${args.reference.name}`);
}
return Messages.showFileNotUnderSourceControlWarningMessage('Unable to show file history');
}
}
if (progressCancellation !== undefined && progressCancellation.token.isCancellationRequested) {
return undefined;
}
let previousPageCommand: CommandQuickPickItem | undefined = undefined;
if (args.log.truncated) {
let commandArgs: ShowQuickFileHistoryCommandArgs;
commandArgs = { ...args, log: undefined };
const npc = new CommandQuickPickItem(
{
label: '$(arrow-right) Show Next Commits',
description: `${Strings.pad(GlyphChars.Dash, 2, 3)} shows ${args.log.maxCount} newer commits`
},
Commands.ShowQuickFileHistory,
[gitUri, commandArgs]
);
const last = Iterables.last(args.log.commits.values());
if (last != null) {
commandArgs = { ...args, log: undefined, nextPageCommand: npc };
previousPageCommand = new CommandQuickPickItem(
{
label: '$(arrow-left) Show Previous Commits',
description: `${Strings.pad(GlyphChars.Dash, 2, 3)} shows ${
args.log.maxCount
} older commits`
},
Commands.ShowQuickFileHistory,
[new GitUri(uri, last), commandArgs]
);
}
}
const icon =
args.reference instanceof GitTag
? '$(tag) '
: args.reference instanceof GitBranch
? '$(git-branch) '
: '';
// Create a command to get back to where we are right now
const currentCommand = new CommandQuickPickItem(
{
label: `go back ${GlyphChars.ArrowBack}`,
description: `${Strings.pad(GlyphChars.Dash, 2, 3)} to history of ${
GlyphChars.Space
}$(file-text) ${paths.basename(gitUri.fsPath)}${
args.reference
? ` from ${GlyphChars.Space}${icon}${args.reference.name}`
: gitUri.sha
? ` from ${GlyphChars.Space}$(git-commit) ${gitUri.shortSha}`
: ''
}`
},
Commands.ShowQuickFileHistory,
[uri, args]
);
const pick = await FileHistoryQuickPick.show(args.log, gitUri, placeHolder, {
progressCancellation: progressCancellation,
currentCommand: currentCommand,
goBackCommand: args.goBackCommand,
nextPageCommand: args.nextPageCommand,
previousPageCommand: previousPageCommand,
showAllCommand:
//.........这里部分代码省略.........
示例8: if
export let run = () => {
let files = [];
if(program.file) {
if(
!fs.existsSync(program.file) ||
!fs.existsSync(path.join(process.cwd(), program.file))
) {
logger.fatal(`"${ program.file }" file wa not found`);
process.exit(1);
}
else {
files = [program.file];
}
}
else if(program.tsconfig) {
if(!fs.existsSync(program.tsconfig)) {
logger.fatal('"tsconfig.json" file wa not found in the current directory');
process.exit(1);
}
else {
program.tsconfig = path.join(
path.join(process.cwd(), path.dirname(program.tsconfig)),
path.basename(program.tsconfig)
);
logger.info('using tsconfig', program.tsconfig);
files = require(program.tsconfig).files;
if(!files) {
let exclude = [];
exclude = require(program.tsconfig).exclude || [];
var walk = (dir) => {
let results = [];
let list = fs.readdirSync(dir);
list.forEach( (file) => {
if (exclude.indexOf(file) < 0) {
file = path.join(dir, file);
let stat = fs.statSync(file);
if (stat && stat.isDirectory()) {
results = results.concat(walk(file));
}
else if (path.extname(file) === '.ts') {
results.push(file);
}
}
});
return results;
};
files = walk('.');
}
}
}
else if (program.files) {
logger.info('using files', program.files.length, 'file(s) found');
files = program.files;
}
else {
outputHelp()
}
let crawler = new Crawler.Dependencies(
files
);
let deps = crawler.getDependencies();
if(deps.length <= 0) {
logger.info('No dependencies found');
process.exit(0);
}
let engine = new Engine.Dot({
output: program.output
});
engine
.generateGraph(deps)
.then( file => {
if (program.open === true) {
logger.info('openning file ', file);
let open = require("opener");
open(file);
}
})
.catch( e => logger.error(e) )
.finally( _ => logger.info('done'))
}
示例9: getName
export function getName(path: string, includeExt = true) {
return basename(path, includeExt ? undefined : extname(path))
}
示例10: historyFileName
return [
"-",
"noglob",
"nocorrect",
"exec",
"command",
];
}
get historyFileName(): string {
return ".zsh_history";
}
}
const supportedShells: Dictionary<Shell> = {
bash: new Bash(),
zsh: new ZSH() ,
};
const shell = () => {
const shellName = basename(process.env.SHELL);
if (shellName in supportedShells) {
return process.env.SHELL;
} else {
console.error(`${shellName} is not supported; defaulting to /bin/bash`);
return "/bin/bash";
}
};
export const loginShell: Shell = supportedShells[basename(shell())];