path#relative TypeScript Examples
The following examples show how to use
path#relative.
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: node-utils.ts From askql with MIT License | 8 votes |
export function getTargetPath(
path: string,
targetExt: string | undefined,
outDir: string = '../dist'
) {
const rootDir = join(__dirname, '../src');
const testDir = relative(rootDir, dirname(path));
const targetDir = join(rootDir, outDir, testDir);
const { name: testName, ext } = parse(path);
return join(targetDir, `${testName}.${targetExt ?? ext}`);
}
Example #2
Source File: utils.ts From karma-test-explorer with MIT License | 7 votes |
isChildPath = (parentPath: string, childPath: string): boolean => {
const childFromParentRelativePath = relative(parentPath, childPath);
return (
childPath !== parentPath &&
!isAbsolute(childFromParentRelativePath) &&
!childFromParentRelativePath.startsWith('..')
);
}
Example #3
Source File: utils.ts From react-loosely-lazy with Apache License 2.0 | 7 votes |
/**
* Generates a relative path to the module that should be 1:1 with what the
* webpack plugin generates for the key for the chunk in the manifest.
*
* @param filename - The absolute path to the file being transpiled
* @param importPath - The import string as it is written in application source code
* @param modulePathReplacer - Contains from and to string keys to override a specific part of the resulting
* module paths generated
* @param resolver - Instance of 'enhanced-resolve' with the custom configuration
*/
export function getModulePath({
filename,
importPath,
modulePathReplacer,
resolver,
}: GetModulePathOptions): string {
// Resolve the import path starting from the filename path itself rather than from within this file
const modulePath = resolver.resolveSync({}, dirname(filename), importPath);
const path = relative(process.cwd(), String(modulePath));
if (modulePathReplacer) {
const { from, to } = modulePathReplacer;
// Normalize the "from" option so that it matches the normalized relative path format and replace it with whatever
// is in the "to" option
const normalizedFrom = normalize(from);
return path.replace(normalizedFrom, to);
}
return addDotSlashPrefix(path);
}
Example #4
Source File: file-watcher.ts From karma-test-explorer with MIT License | 6 votes |
private registerFileHandler(
filePatterns: readonly string[],
handler: (filePath: string, changeType: FileChangeType) => void
): FileSystemWatcher[] {
const fileWatchers: FileSystemWatcher[] = [];
const workspaceRootPath = normalizePath(this.workspaceFolder.uri.fsPath);
const relativeProjectRootPath = relative(workspaceRootPath, this.projectRootPath);
const isProjectRootSameAsWorkspace = this.projectRootPath === workspaceRootPath;
this.logger.debug(() => `Registering file handler for files: ${JSON.stringify(filePatterns, null, 2)}`);
for (const fileOrPattern of filePatterns) {
const relativeFileOrPattern = isProjectRootSameAsWorkspace
? fileOrPattern
: normalizePath(join(relativeProjectRootPath, fileOrPattern));
const absoluteFileOrPattern = new RelativePattern(this.workspaceFolder, relativeFileOrPattern);
this.logger.debug(
() =>
`Creating file watcher for file or pattern '${fileOrPattern}' ` +
`using base path: ${absoluteFileOrPattern.base}`
);
const fileWatcher = workspace.createFileSystemWatcher(absoluteFileOrPattern);
fileWatchers.push(fileWatcher);
this.disposables.push(
fileWatcher.onDidChange(fileUri => handler(normalizePath(fileUri.fsPath), FileChangeType.Changed)),
fileWatcher.onDidCreate(fileUri => handler(normalizePath(fileUri.fsPath), FileChangeType.Created)),
fileWatcher.onDidDelete(fileUri => handler(normalizePath(fileUri.fsPath), FileChangeType.Deleted))
);
}
return fileWatchers;
}
Example #5
Source File: getSelectFilesMenu.ts From web with MIT License | 6 votes |
export function getSelectFilesMenu(succeededFiles: string[], failedFiles: string[]) {
const maxI = succeededFiles.length + failedFiles.length;
const minWidth = maxI.toString().length + 1;
function formatTestFile(file: string, i: number, offset: number, failed: boolean) {
const relativePath = relative(process.cwd(), file);
return `[${i + offset}]${' '.repeat(Math.max(0, minWidth - (i + offset).toString().length))}${
failed ? red(relativePath) : cyan(relativePath)
}`;
}
const entries: string[] = [
'Test files:\n',
...succeededFiles.map((f, i) => formatTestFile(f, i, failedFiles.length + 1, false)),
'',
];
if (failedFiles.length > 0) {
entries.push(
'Failed test files:\n',
...failedFiles.map((f, i) => formatTestFile(f, i, 1, true)),
);
}
return entries;
}
Example #6
Source File: index.ts From cli with MIT License | 6 votes |
printUsage() {
console.log(
'Successfully created project',
chalk.hex('#3eab34')(this.projectName)
);
console.log('Get started with the following commands:');
console.log('');
console.log(
chalk.hex('#777777')(
`$ cd ${relative(this.core.cwd, this.projectDirPath)}`
)
);
console.log(chalk.hex('#777777')('$ npm run dev'));
console.log('');
console.log('');
console.log(chalk.hex('#3eab34')('Thanks for using Midway'));
console.log('');
console.log(
'Document ❤ Star:',
chalk.hex('#1C95E2')('https://github.com/midwayjs/midway')
);
console.log('');
}
Example #7
Source File: NoteWorkspace.ts From vscode-markdown-notes with GNU General Public License v3.0 | 6 votes |
static wikiLinkCompletionForConvention(
uri: vscode.Uri,
fromDocument: vscode.TextDocument
): string {
if (this.useUniqueFilenames()) {
let filename = basename(uri.fsPath);
let c = this.cfg().noteCompletionConvention;
return this._wikiLinkCompletionForConvention(c, filename);
} else {
let toPath = uri.fsPath;
let fromDir = dirname(fromDocument.uri.fsPath.toString());
let rel = normalize(relative(fromDir, toPath));
return rel;
}
}
Example #8
Source File: reportTestFileResults.ts From web with MIT License | 6 votes |
export function reportTestFileResults(
logger: BufferedLogger,
testFile: string,
allBrowserNames: string[],
favoriteBrowser: string,
sessionsForTestFile: TestSession[],
) {
const failedSessions = sessionsForTestFile.filter(s => !s.passed);
reportBrowserLogs(logger, sessionsForTestFile);
reportRequest404s(logger, sessionsForTestFile);
reportTestFileErrors(logger, allBrowserNames, favoriteBrowser, sessionsForTestFile);
if (failedSessions.length > 0) {
reportTestsErrors(logger, allBrowserNames, favoriteBrowser, failedSessions);
}
if (logger.buffer.length > 0) {
logger.buffer.unshift({
method: 'log',
args: [`${bold(cyan(relative(process.cwd(), testFile)))}:\n`],
});
}
}
Example #9
Source File: index.ts From mordred with MIT License | 6 votes |
async writeAll() {
console.log(
`Updating GraphQL client at ${relative(
process.cwd(),
this.graphqlClientPath,
)}..`,
)
await Promise.all([
this.writeNodes(),
this.writeZeus(),
this.writeGraphQL(),
])
}
Example #10
Source File: examples.spec.ts From graphql-eslint with MIT License | 6 votes |
function testSnapshot(results: ESLint.LintResult[]): void {
const normalizedResults = results
.map(result => ({
filePath: relative(ROOT_CWD, result.filePath),
messages: result.messages,
}))
.filter(result => result.messages.length > 0);
expect(normalizedResults).toMatchSnapshot();
}
Example #11
Source File: component.ts From open-source with MIT License | 6 votes |
export function componentUpdate(opts: Required<Schema>): Observable<any> {
if (opts.dryRun) {
logInfo('> Updating component');
return of(true);
}
return readFile(opts.file).pipe(
concatMap((content) => {
const file = relative(opts.path, opts.file);
let source = convertTsInlineTemplate(file, content);
source = convertTsInlineUrlExtension(file, content);
return source !== content
? writeFile(opts.file, source)
: throwError(null);
}),
);
}
Example #12
Source File: add-to-sln.ts From nx-dotnet with MIT License | 6 votes |
export function addToSolutionFile(
host: Tree,
projectRoot: string,
dotnetClient = new DotNetClient(dotnetFactory()),
solutionFile?: string | boolean,
) {
const workspaceConfiguration = readWorkspaceConfiguration(host);
const defaultFilePath = readConfigSection(host, 'solutionFile')?.replace(
'{npmScope}',
workspaceConfiguration.npmScope || '',
);
if (typeof solutionFile === 'boolean' && solutionFile) {
solutionFile = defaultFilePath;
} else if (solutionFile === null || solutionFile === undefined) {
if (defaultFilePath && host.exists(defaultFilePath)) {
solutionFile = defaultFilePath;
}
}
if (solutionFile) {
if (!host.exists(solutionFile)) {
dotnetClient.new('sln', {
name: parse(solutionFile).name,
output: host.root,
});
}
const relativePath = relative(dotnetClient.cwd || host.root, host.root);
dotnetClient.addProjectToSolution(
joinPathFragments(relativePath, solutionFile),
resolve(relativePath, projectRoot),
);
}
}
Example #13
Source File: addFileScope.ts From vanilla-extract with MIT License | 6 votes |
export function addFileScope({
source,
filePath,
rootPath,
packageName,
}: AddFileScopeParams) {
// Encode windows file paths as posix
const normalizedPath = posix.join(...relative(rootPath, filePath).split(sep));
if (source.indexOf('@vanilla-extract/css/fileScope') > -1) {
return source.replace(
/setFileScope\(((\n|.)*?)\)/,
`setFileScope("${normalizedPath}", "${packageName}")`,
);
}
return `
import { setFileScope, endFileScope } from "@vanilla-extract/css/fileScope";
setFileScope("${normalizedPath}", "${packageName}");
${source}
endFileScope();
`;
}
Example #14
Source File: upload-statics.ts From blog with GNU General Public License v3.0 | 6 votes |
(async () => {
console.log('Reading static files in ' + staticFolder);
const allStaticFiles = getAllFiles(staticFolder);
console.log('Loading existing assets from S3...');
const existingAssets = await getS3Assets();
for(let i = 0; i < allStaticFiles.length; i++) {
const file = allStaticFiles[i];
const imageKey = relative(staticFolder, file);
const isAsset = imageKey.substr(0, 6) === 'assets';
if (!existingAssets.includes(imageKey)) {
console.log(`Uploading file ${file} to ${imageKey}...`);
await s3.send(new PutObjectCommand({
Bucket: bucketName,
Key: imageKey,
Body: readFileSync(file),
ContentType: lookup(file) || 'plain/text',
CacheControl: `max-age=${isAsset ? CACHE_ASSETS : CACHE_DEFAULT}`
}));
console.log('Done');
} else {
console.log(`${imageKey} already uploaded`);
}
}
console.log('All done');
})();
Example #15
Source File: assets.ts From fantasticon with MIT License | 6 votes |
loadAssets = async ({
inputDir,
getIconId
}: RunnerOptions): Promise<AssetsMap> => {
const paths = await loadPaths(inputDir);
const out = {};
let index = 0;
for (const path of paths) {
const relativePath = relative(resolve(inputDir), resolve(path));
const parts = splitSegments(relativePath);
const basename = removeExtension(parts.pop());
const absolutePath = resolve(path);
const iconId = getIconId({
basename,
relativeDirPath: join(...parts),
absoluteFilePath: absolutePath,
relativeFilePath: relativePath,
index
});
const result: IconAsset = { id: iconId, relativePath, absolutePath };
if (out[iconId]) {
failForConflictingId(out[iconId], result);
}
out[iconId] = result;
index++;
}
return out;
}
Example #16
Source File: md2html.ts From yfm-docs with MIT License | 6 votes |
export async function resolveMd2HTML(options: ResolverOptions): Promise<void> {
const {inputPath, fileExtension, outputPath, outputBundlePath, metadata} = options;
const pathToDir: string = dirname(inputPath);
const toc: YfmToc|null = TocService.getForPath(inputPath) || null;
const tocBase: string = toc && toc.base ? toc.base : '';
const pathToFileDir: string = pathToDir === tocBase ? '' : pathToDir.replace(`${tocBase}/`, '');
const relativePathToIndex = relative(dirname(inputPath), `${tocBase}/`);
const {input, lang} = ArgvService.getConfig();
const resolvedPath: string = resolve(input, inputPath);
const content: string = readFileSync(resolvedPath, 'utf8');
const transformFn: Function = FileTransformer[fileExtension];
const {result} = transformFn(content, {path: inputPath});
const updatedMetadata = metadata && metadata.isContributorsEnabled
? await getUpdatedMetadata(metadata, content, result?.meta)
: result.meta;
const props = {
data: {
leading: inputPath.endsWith('.yaml'),
toc: transformToc(toc, pathToDir) || {},
...result,
meta: updatedMetadata,
},
router: {
pathname: join(relativePathToIndex, pathToFileDir, basename(outputPath)),
},
lang: lang || Lang.RU,
};
const outputDir = dirname(outputPath);
const relativePathToBundle: string = relative(resolve(outputDir), resolve(outputBundlePath));
const outputFileContent = generateStaticMarkup(props, relativePathToBundle);
writeFileSync(outputPath, outputFileContent);
logger.info(inputPath, PROCESSING_FINISHED);
}
Example #17
Source File: visitor.ts From react-dev-inspector with MIT License | 6 votes |
createVisitor = ({ cwd, excludes }: {
cwd?: string,
excludes?: (string | RegExp)[],
}): Visitor<PluginPass> => {
const isExclude = excludes?.length
? memo((filePath: string): boolean => pathMatch(filePath, excludes))
: () => false
const pathRelative = memo((filePath: string): string => relative(
cwd ?? process.cwd(),
filePath,
))
const visitor: Visitor<PluginPass> = {
JSXOpeningElement: {
enter(path, state: PluginPass) {
const filePath = state?.file?.opts?.filename
if (!filePath) return
if (isExclude(filePath)) return
const relativePath = pathRelative(filePath)
doJSXOpeningElement(
path.node,
{
relativePath,
},
)
},
},
}
return visitor
}
Example #18
Source File: model.ts From TsUML2 with MIT License | 6 votes |
getRelativeFilePath(fromFile: string) {
const rx = /"(.*)"/;
const result = rx.exec(this.id);
if(!result) {
console.log(chalk.redBright("Could not compute path to class / interface definition: " + this.id));
return "";
}
fromFile = resolve(dirname(fromFile));
const toFile = resolve(result[1] + '.ts');
let rel = relative(fromFile,toFile);
return rel;
}
Example #19
Source File: read-file-or-url.spec.ts From graphql-mesh with MIT License | 6 votes |
describe('readFile', () => {
it('should convert relative paths to absolute paths correctly', async () => {
const tmpFileAbsolutePath = join(tmpdir(), './tmpfile.json');
const tmpFileContent = {
test: 'TEST',
};
writeFileSync(tmpFileAbsolutePath, JSON.stringify(tmpFileContent));
const tmpFileRelativePath = relative(cwd(), tmpFileAbsolutePath);
const receivedFileContent = await readFile(tmpFileRelativePath);
expect(receivedFileContent).toStrictEqual(tmpFileContent);
});
it('should respect absolute paths correctly', async () => {
const tmpFileAbsolutePath = join(tmpdir(), './tmpfile.json');
const tmpFileContent = {
test: 'TEST',
};
writeFileSync(tmpFileAbsolutePath, JSON.stringify(tmpFileContent));
const receivedFileContent = await readFile(tmpFileAbsolutePath);
expect(receivedFileContent).toStrictEqual(tmpFileContent);
});
});
Example #20
Source File: gcp-cache.ts From nx-extend with MIT License | 6 votes |
private async uploadDirectory(cacheDirectory: string, dir: string) {
for (const entry of await promises.readdir(dir)) {
const full = join(dir, entry)
const stats = await promises.stat(full)
if (stats.isDirectory()) {
await this.uploadDirectory(cacheDirectory, full)
} else if (stats.isFile()) {
const destination = relative(cacheDirectory, full)
this.uploadQueue.push(this.bucket.upload(full, { destination }))
}
}
}
Example #21
Source File: snapshots-utils.ts From ui5-language-assistant with Apache License 2.0 | 6 votes |
export async function snapshotTestLSPDiagnostic(
testDir: string,
options: LSPDiagnosticOptions
): Promise<void> {
const pkgJsonPath = require.resolve(
"@ui5-language-assistant/language-server/package.json"
);
const languageServerDir = dirname(pkgJsonPath);
// This is the project root directory
const rootDir = resolve(languageServerDir, "..", "..");
// Note: the original `input.xml` snippet acts as **both**:
// - The sample input.
// - A snapshot for marker ranges.
const originalXMLSnippet = readInputXMLSnippet(testDir, false);
const diagnosticsSnapshots = readSnapshotDiagnosticsLSPResponse(testDir);
// Check consistency of the ranges between the input xml and the snapshot response
// (for example, if one of them was changed manually)
const snapshotRanges = map(diagnosticsSnapshots, (_) => _.range);
const snapshotXMLWithMarkedRanges = computeXMLWithMarkedRanges(
testDir,
snapshotRanges
);
expect(
originalXMLSnippet,
`The XML input snippet range markers don't match the snapshot response ranges. Did you forget to run "yarn update-snapshots"?
Input xml is at: ${relative(rootDir, getInputXMLSnippetPath(testDir))}
Snapshot response is at: ${relative(
rootDir,
getSnapshotDiagnosticsLSPResponsePath(testDir)
)}`
).to.equal(snapshotXMLWithMarkedRanges);
const newlyComputedDiagnostics = await computeNewDiagnosticLSPResponse(
testDir,
options
);
expect(
newlyComputedDiagnostics,
`Snapshot Mismatch in LSP Diagnostics response.
Snapshot is at: ${relative(
rootDir,
getSnapshotDiagnosticsLSPResponsePath(testDir)
)}`
).to.deep.equal(diagnosticsSnapshots);
const newlyCommutedRanges = map(newlyComputedDiagnostics, (_) => _.range);
const newlyComputedXMLWithMarkedRanges = computeXMLWithMarkedRanges(
testDir,
newlyCommutedRanges
);
expect(
originalXMLSnippet,
`The XML input snippet range markers are incorrect.
Snapshot is at: ${relative(rootDir, getInputXMLSnippetPath(testDir))}`
).to.equal(newlyComputedXMLWithMarkedRanges);
}
Example #22
Source File: loading.ts From amplify-codegen with Apache License 2.0 | 6 votes |
export function loadAndMergeQueryDocuments(inputPaths: string[], tagName: string = 'gql'): DocumentNode {
const sources = inputPaths
.map(inputPath => {
const body = fs.readFileSync(inputPath, 'utf8');
if (!body) {
return null;
}
if (inputPath.endsWith('.jsx') || inputPath.endsWith('.js') || inputPath.endsWith('.tsx') || inputPath.endsWith('.ts')) {
const doc = extractDocumentFromJavascript(body.toString(), tagName);
return doc ? new Source(doc, inputPath) : null;
}
return new Source(body, inputPath);
})
.filter((source): source is Source => Boolean(source));
const parsedSources = sources.map(source => {
try {
return parse(source);
} catch (err) {
const relativePathToInput = relative(process.cwd(), source.name);
throw new ToolError(`Could not parse graphql operations in ${relativePathToInput}\n Failed on : ${source.body}`);
}
});
return concatAST(parsedSources);
}
Example #23
Source File: isChildPath.ts From backstage with Apache License 2.0 | 6 votes |
/**
* Checks if path is the same as or a child path of base.
*
* @public
*/
export function isChildPath(base: string, path: string): boolean {
const relativePath = relative(base, path);
if (relativePath === '') {
// The same directory
return true;
}
const outsideBase = relativePath.startsWith('..'); // not outside base
const differentDrive = isAbsolute(relativePath); // on Windows, this means dir is on a different drive from base.
return !outsideBase && !differentDrive;
}
Example #24
Source File: shared.ts From ue4-intellisense-fixes with MIT License | 6 votes |
export function isEqualPaths(path1: string, path2: string): boolean {
try {
return !path.relative(path1, path2);
}
catch (error) {
console.error(`Error with path.relative: ${path1} === ${path2}`);
return false;
}
}
Example #25
Source File: init-manager.ts From malagu with MIT License | 6 votes |
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 #26
Source File: get-website-context.ts From xiome with MIT License | 6 votes |
export function getWebsiteContext({
sourcePath,
inputDirectory,
outputDirectory,
}: {
sourcePath: string
inputDirectory: string
outputDirectory: string
}): WebsiteContext {
let base = relative(dirname(sourcePath), inputDirectory)
base = base === ""
? "."
: base
return {
base,
v: hashVersioner({
root: outputDirectory,
origin: relative(
resolve(inputDirectory),
dirname(resolve(sourcePath))
),
})
}
}
Example #27
Source File: unique-fragment-name.ts From graphql-eslint with MIT License | 6 votes |
checkNode = (
context: GraphQLESLintRuleContext,
node: GraphQLESTreeNode<ExecutableDefinitionNode>,
ruleId: string
): void => {
const documentName = node.name.value;
const siblings = requireSiblingsOperations(ruleId, context);
const siblingDocuments: (FragmentSource | OperationSource)[] =
node.kind === Kind.FRAGMENT_DEFINITION ? siblings.getFragment(documentName) : siblings.getOperation(documentName);
const filepath = context.getFilename();
const conflictingDocuments = siblingDocuments.filter(f => {
const isSameName = f.document.name?.value === documentName;
const isSamePath = normalizePath(f.filePath) === normalizePath(filepath);
return isSameName && !isSamePath;
});
if (conflictingDocuments.length > 0) {
context.report({
messageId: ruleId,
data: {
documentName,
summary: conflictingDocuments
.map(f => `\t${relative(process.cwd(), getOnDiskFilepath(f.filePath))}`)
.join('\n'),
},
node: node.name,
});
}
}
Example #28
Source File: expandedPreviewer.ts From cli with Apache License 2.0 | 6 votes |
private async applySnapshotToPreview(dirPath: string) {
recursiveDirectoryDiff(
join(dirPath, 'resources'),
relative(cwd(), this.projectToPreview.resourcePath),
this.shouldDelete
);
await spawnProcess('git', ['add', '.'], {cwd: dirPath, stdio: 'ignore'});
await spawnProcess(
'git',
['commit', `--message=${this.orgId} after snapshot application`],
{
cwd: dirPath,
stdio: 'ignore',
}
);
}
Example #29
Source File: nunit.ts From nunit-reporter with MIT License | 5 votes |
function sanitizePath(filename: string): string {
if (filename.startsWith("/github/workspace"))
return relative("/github/workspace", filename);
else return relative(process.cwd(), filename).replace(/\\/g, "/");
}