path#dirname TypeScript Examples

The following examples show how to use path#dirname. 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 vote down vote up
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 graphql-eslint with MIT License 7 votes vote down vote up
getOnDiskFilepath = (filepath: string): string => {
  try {
    if (statSync(filepath).isFile()) {
      return filepath;
    }
  } catch (err) {
    // https://github.com/eslint/eslint/issues/11989
    if (err.code === 'ENOTDIR') {
      return getOnDiskFilepath(dirname(filepath));
    }
  }

  return filepath;
}
Example #3
Source File: utils.ts    From react-loosely-lazy with Apache License 2.0 7 votes vote down vote up
/**
 * 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: index.ts    From fetch-gh-release-asset with MIT License 7 votes vote down vote up
baseFetchAssetFile = async (
  octokit: ReturnType<typeof github.getOctokit>,
  { id, outputPath, owner, repo, token }: FetchAssetFileOptions
) => {
  const {
    body,
    headers: { accept, 'user-agent': userAgent },
    method,
    url,
  } = octokit.request.endpoint(
    'GET /repos/:owner/:repo/releases/assets/:asset_id',
    {
      asset_id: id,
      headers: {
        accept: 'application/octet-stream',
      },
      owner,
      repo,
    }
  );
  let headers: HeadersInit = {
    accept,
    authorization: `token ${token}`,
  };
  if (typeof userAgent !== 'undefined')
    headers = { ...headers, 'user-agent': userAgent };

  const response = await fetch(url, { body, headers, method });
  if (!response.ok) {
    const text = await response.text();
    core.warning(text);
    throw new Error('Invalid response');
  }
  const blob = await response.blob();
  const arrayBuffer = await blob.arrayBuffer();
  await mkdir(dirname(outputPath), { recursive: true });
  void (await writeFile(outputPath, new Uint8Array(arrayBuffer)));
}
Example #5
Source File: utils.ts    From karma-test-explorer with MIT License 7 votes vote down vote up
getNodeExecutablePath = (searchPath?: string): string => {
  const path = searchPath ?? process.env.PATH;
  const npxExecutablePath = which.sync('npx', { all: false, nothrow: true, path });

  const npxNodeExecutablePath = npxExecutablePath
    ? which.sync('node', { all: false, nothrow: true, path: dirname(npxExecutablePath) })
    : undefined;

  const nodeExecutablePath = which.sync('node', { all: false, nothrow: true, path });

  return npxNodeExecutablePath ?? nodeExecutablePath ?? process.execPath;
}
Example #6
Source File: util.ts    From DefinitelyTyped-tools with MIT License 7 votes vote down vote up
export function getCommonDirectoryName(files: readonly string[]): string {
  let minLen = 999;
  let minDir = "";
  for (const file of files) {
    const dir = dirname(file);
    if (dir.length < minLen) {
      minDir = dir;
      minLen = dir.length;
    }
  }
  return basename(minDir);
}
Example #7
Source File: plugin-utils.ts    From automapper-transformer-plugin with MIT License 7 votes vote down vote up
export function replaceImportPath(typeReference: string, fileName: string) {
  if (!typeReference.includes('import')) {
    return typeReference;
  }
  let importPath = /\("([^)]).+(")/.exec(typeReference)?.[0];
  if (!importPath) {
    return undefined;
  }
  importPath = importPath.slice(2, importPath.length - 1);

  let relativePath = posix.relative(dirname(fileName), importPath);
  relativePath = relativePath[0] !== '.' ? './' + relativePath : relativePath;
  typeReference = typeReference.replace(importPath, relativePath);

  return typeReference.replace('import', 'require');
}
Example #8
Source File: fs-utils.ts    From open-design-sdk with Apache License 2.0 7 votes vote down vote up
export async function writeJsonFile(
  filename: string,
  data: unknown,
  options: {
    cancelToken?: CancelToken | null
  } = {}
): Promise<void> {
  await mkdirp(dirname(filename))
  options.cancelToken?.throwIfCancelled()

  const writeFile = promisify(fs.writeFile)
  const json = JSON.stringify(data)
  await writeFile(filename, json)
  options.cancelToken?.throwIfCancelled()
}
Example #9
Source File: utils.ts    From language-tools with MIT License 7 votes vote down vote up
export function findTsConfigPath(fileName: string, rootUris: string[]) {
    const searchDir = dirname(fileName);

    const path =
        ts.findConfigFile(searchDir, ts.sys.fileExists, 'tsconfig.json') ||
        ts.findConfigFile(searchDir, ts.sys.fileExists, 'jsconfig.json') ||
        '';
    // Don't return config files that exceed the current workspace context.
    return !!path && rootUris.some((rootUri) => isSubPath(rootUri, path)) ? path : '';
}
Example #10
Source File: index.ts    From nestjs-proto-gen-ts with MIT License 6 votes vote down vote up
private output(file: string, pkg: string, tmpl: string): void {
        const root = new Root();

        this.resolveRootPath(root);

        root.loadSync(file, {
            keepCase: this.options.keepCase,
            alternateCommentMode: this.options.comments
        }).resolveAll();

        this.walkTree(root);

        const results = compile(tmpl)(root);
        const outputFile = this.options.output ? join(this.options.output, file.replace(/^.+?[/\\]/, '')) : file;
        const outputPath = join(dirname(outputFile), `${basename(file, extname(file))}.ts`);

        outputFileSync(outputPath, results, 'utf8');
    }
Example #11
Source File: bundle.ts    From luabundler with MIT License 6 votes vote down vote up
async run() {
		const {args, flags} = this.parse(BundleCommand)
		const options: BundleOptions = {
			luaVersion: flags.lua,
			isolate: flags.isolate,
			expressionHandler: (module: Module, expression: Expression) => {
				const start = expression.loc!.start
				console.warn(`WARNING: Non-literal require found in '${module.name}' at ${start.line}:${start.column}`)
			},
		}

		if (flags.path.length > 0) {
			options.paths = flags.path
		}

		let content

		if (!args.file || args.file === '-') {
			content = bundleString(await readStdin(), options)
		} else {
			content = bundle(args.file, options)
		}

		if (flags.output) {
			const resolvedPath = resolvePath(flags.output)
			const resolvedDir = dirname(resolvedPath)

			if (!existsSync(resolvedDir)) {
				mkdirSync(resolvedDir, {recursive: true})
			}

			writeFileSync(flags.output, content)
		} else {
			console.log(content)
		}
	}
Example #12
Source File: run-nx-new-command.ts    From nx-plugins with MIT License 6 votes vote down vote up
export function runNxNewCommand(args?: string, silent?: boolean) {
  const localTmpDir = dirname(tmpProjPath());
  return execSync(
    `node ${require.resolve(
      '@nrwl/tao',
    )} new proj --nx-workspace-root=${localTmpDir} --no-interactive --skip-install --collection=@nrwl/workspace --npmScope=proj --preset=empty ${
      args || ''
    }`,
    {
      cwd: localTmpDir,
      // eslint-disable-next-line no-constant-condition
      ...(silent && false ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}),
    },
  );
}
Example #13
Source File: jest-build-test.ts    From askql with MIT License 6 votes vote down vote up
// TODO '.*/__tests__/.*',
// special case

test(`saves ${targetPath}`, async () => {
  const src: string = await readFile(jestTestPath, { encoding: 'utf-8' });
  expect(src).toBeDefined();

  const javaScriptSource = toJavaScriptSource(src, testPath);
  expect(javaScriptSource).toBeDefined();

  await mkdir(dirname(targetPath), { recursive: true });
  await writeFile(targetPath, javaScriptSource);
});
Example #14
Source File: imports.ts    From solc-typed-ast with Apache License 2.0 6 votes vote down vote up
/**
 * Normalize a relative import path as described in
 * https://docs.soliditylang.org/en/v0.8.8/path-resolution.html#relative-imports
 *
 * @param importer - source unit name of importing unit
 * @param imported - path of import directive
 */
function normalizeRelativeImportPath(importer: string, imported: string): string {
    imported = normalize(imported);

    const importedSegments = imported.split("/").filter((s) => s !== "");

    let prefix = dirname(importer);
    let strippedSegments = 0;

    while (
        strippedSegments < importedSegments.length &&
        importedSegments[strippedSegments] === ".."
    ) {
        prefix = dirname(prefix);

        strippedSegments++;
    }

    // According to https://docs.soliditylang.org/en/v0.8.8/path-resolution.html#relative-imports when prefix
    // is empty there is no leading "./". However `dirname` always returns non-empty prefixes.
    // Handle this edge case.
    if (prefix === "." && !importer.startsWith(".")) {
        prefix = "";
    }

    assert(prefix === "" || !prefix.endsWith("/"), `Invalid prefix ${prefix}`);

    const suffix = importedSegments.slice(strippedSegments).join("/");

    return prefix === "" ? suffix : prefix + "/" + suffix;
}
Example #15
Source File: paths.ts    From Cromwell with MIT License 6 votes vote down vote up
getNodeModuleDir = async (moduleName: string) => {
    try {
        const modulePath = resolvePackageJsonPath(moduleName);
        if (modulePath) return dirname(await fs.realpath(modulePath));
    } catch (e) { }

    try {
        // if module is a root package
        const rootPackage = await getModulePackage();
        if (rootPackage?.name === moduleName) return await fs.realpath(process.cwd());
    } catch (e) { }
}
Example #16
Source File: index.ts    From write-file-action with Apache License 2.0 6 votes vote down vote up
async function main() {
  try {
    const path = getInput("path", { required: true });
    const contents = getInput("contents", { required: true });
    const mode = (getInput("write-mode") || "append").toLocaleLowerCase();

    // Ensure the correct mode is specified
    if (mode !== "append" && mode !== "overwrite" && mode !== "preserve") {
      setFailed("Mode must be one of: overwrite, append, or preserve");
      return;
    }

    // Preserve the file
    if (mode === "preserve" && (await existsAsync(path))) {
      const statResult = await statAsync(path);
      setOutput("size", `${statResult.size}`);
      return;
    }

    const targetDir = dirname(path);

    await mkdirP(targetDir);

    if (mode === "overwrite") {
      await writeFileAsync(path, contents);
    } else {
      await appendFileAsync(path, contents);
    }

    const statResult = await statAsync(path);
    setOutput("size", `${statResult.size}`);
  } catch (error) {
    setFailed(error.message);
  }
}
Example #17
Source File: builder.ts    From nx-plugins with MIT License 6 votes vote down vote up
export function runBuilder(
  options: NxDeployItDeployBuilderSchema,
  context: BuilderContext
): Observable<BuilderOutput> {
  if (!context?.target?.project) {
    return of({ success: false });
  }
  const configuration = context.target.configuration || 'dev';

  const project = getProjectConfig(context);
  const applicationType = getApplicationType(project.architect);

  return from(context.getTargetOptions(context.target)).pipe(
    switchMap((targetOptions: DeployTargetOptions) => {
      const cwd = dirname(
        resolve(context.workspaceRoot, targetOptions.main as string)
      );

      createStackIfNotExist(cwd, configuration, context.target.project);

      const adapter = getAdapterByApplicationType(
        applicationType,
        project,
        options
      );

      return adapter.deploy(
        context,
        cwd,
        options,
        configuration,
        targetOptions
      );
    })
  );
}
Example #18
Source File: upload.ts    From ng-spotify-importer with GNU General Public License v3.0 6 votes vote down vote up
(async () => {
    await sftp.connect({
        host: process.env.NG_SPOTIFY_IMPORTER__DEPLOYMENT_HOST,
        username: process.env.NG_SPOTIFY_IMPORTER__DEPLOYMENT_USERNAME,
        password: process.env.NG_SPOTIFY_IMPORTER__DEPLOYMENT_PASSWORD,
        port: parseInt(process.env.NG_SPOTIFY_IMPORTER__DEPLOYMENT_PORT, 10)
    });

    const remoteHomePath = process.env.NG_SPOTIFY_IMPORTER__DEPLOYMENT_HOME_PATH;
    const remoteProjectPath = remoteHomePath + '/' + process.env.NG_SPOTIFY_IMPORTER__DEPLOYMENT_PROJECT_PATH;

    try {
        await sftp.rmdir(remoteProjectPath, true);
    } catch {
        // Nothing to cleanup, so do nothing.
    }

    await sftp.mkdir(remoteProjectPath, true);

    const htaccessFilePath = dirname(__filename) + '/../dist/.htaccess';
    await sftp.fastPut(htaccessFilePath, remoteProjectPath + '/.htaccess');

    const localProjectPath = dirname(__filename) + '/../dist/ng-slacker-to-spotify/';
    await sftp.uploadDir(localProjectPath, remoteProjectPath);

    await sftp.end();
})();
Example #19
Source File: manifest-handling.ts    From ui5-language-assistant with Apache License 2.0 6 votes vote down vote up
export function getFlexEnabledFlagForXMLFile(xmlPath: string): boolean {
  const manifestFilesForCurrentFolder = filter(
    Object.keys(manifestData),
    (manifestPath) => xmlPath.startsWith(dirname(manifestPath))
  );

  const closestManifestPath = maxBy(
    manifestFilesForCurrentFolder,
    (manifestPath) => manifestPath.length
  );

  if (closestManifestPath === undefined) {
    return false;
  }

  return manifestData[closestManifestPath].flexEnabled;
}
Example #20
Source File: spParser.ts    From sourcepawn-vscode with MIT License 6 votes vote down vote up
export function parseFile(
  file: string,
  items: FileItems,
  itemsRepository: ItemsRepository,
  searchTokens: boolean,
  IsBuiltIn: boolean
) {
  if (!existsSync(file)) {
    return;
  }
  let data = readFileSync(file, "utf-8");

  // Test for symbolic links
  let match = data.match(/^(?:\.\.\/)+(?:[\/\w\-])+\.\w+/);
  if (match !== null) {
    let folderpath = dirname(file);
    file = resolve(folderpath, match[0]);
    data = readFileSync(file, "utf-8");
  }
  parseText(data, file, items, itemsRepository, searchTokens, IsBuiltIn);
}
Example #21
Source File: build.impl.ts    From nx-extend with MIT License 6 votes vote down vote up
export function copyFolderSync(from, to) {
  fs.readdirSync(from).forEach((element) => {
    const stat = fs.lstatSync(join(from, element))
    const toPath = join(to, element)

    if (stat.isFile()) {
      // Make sure the directory exists
      fs.mkdirSync(dirname(toPath), { recursive: true })

      fs.copyFileSync(join(from, element), toPath)

    } else if (stat.isSymbolicLink()) {
      fs.symlinkSync(fs.readlinkSync(join(from, element)), toPath)

    } else if (stat.isDirectory() && element !== 'node_modules') {
      copyFolderSync(join(from, element), toPath)
    }
  })
}
Example #22
Source File: runBatch.ts    From elephize with MIT License 6 votes vote down vote up
function onData(basePath: string[], promises: Array<Promise<any>>, filename: string, content: string) {
  process.stdout.write('[data received] ' + filename + '\n');
  promises.push(new Promise((resolve) => {
    const resultFileName = join(baseDir, normalizeFileExt(filename));
    const cont = prettier.format(content, phpPrettierOptions);

    mkdirpSync(dirname(resultFileName));

    writeFileSync(resultFileName + '.result', cont, 'utf-8');
    expect(cont).toBeTruthy();
    expect(cont, 'Failed in file: ' + filename)
      .toEqual(prettier.format(readFileSync(resultFileName, 'utf-8'), phpPrettierOptions));
    process.stdout.write('[test ok] ' + filename.replace(pResolve(...basePath), '') + '\n');
    unlinkSync(resultFileName + '.result');
    resolve(null);
  }));
}
Example #23
Source File: folder-mark.ts    From alx-folder-note with MIT License 6 votes vote down vote up
//#endregion
  //#region set hide collapse indicator
  private initHideCollapseIndicator() {
    if (!this.plugin.settings.hideCollapseIndicator) return;
    const { vault } = this.app;
    [
      vault.on("create", (file) => this.setChangedFolder(file.parent.path)),
      vault.on("delete", (file) => {
        let parent = dirname(file.path);
        this.setChangedFolder(parent === "." ? "/" : parent);
      }),
      vault.on("rename", (file, oldPath) => {
        this.setChangedFolder(file.parent.path);
        let parent = dirname(oldPath);
        this.setChangedFolder(parent === "." ? "/" : parent);
      }),
    ].forEach(this.plugin.registerEvent.bind(this.plugin));
  }
Example #24
Source File: vault-handler.ts    From folder-note-core with MIT License 6 votes vote down vote up
private shouldRename(af: TAbstractFile, oldPath?: string): oldPath is string {
    if (!this.settings.autoRename || !oldPath) return false;
    const renameOnly =
      this.settings.folderNotePref !== NoteLoc.Index &&
      dirname(af.path) === dirname(oldPath) // rename only, same loc
        ? true
        : false;
    // sync loc is enabled in folder renames only
    const syncLoc =
      af instanceof TFolder &&
      this.settings.folderNotePref === NoteLoc.Outside &&
      dirname(af.path) !== dirname(oldPath)
        ? true
        : false;
    return renameOnly || syncLoc;
  }
Example #25
Source File: brew.ts    From setup-cpp with Apache License 2.0 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function setupBrew(_version: string, _setupDir: string, _arch: string) {
  if (!["darwin", "linux"].includes(process.platform)) {
    return undefined
  }
  if (typeof binDir === "string") {
    return { binDir }
  }

  const maybeBinDir = which.sync("brew", { nothrow: true })
  if (maybeBinDir !== null) {
    binDir = dirname(maybeBinDir)
    return { binDir }
  }

  // brew is not thread-safe
  execFileSync(`/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"`, {
    stdio: "inherit",
  })
  binDir = "/usr/local/bin/"

  return { binDir }
}
Example #26
Source File: appdata.ts    From devoirs with MIT License 6 votes vote down vote up
async get(): Promise<string> {
    await mkdir(dirname(this.path)).catch((e: NodeJS.ErrnoException) => {
      if (e.code === 'EEXIST') {
        return;
      }

      throw e;
    });

    return this.path;
  }
Example #27
Source File: local_path.ts    From ardrive-cli with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Resolves the path, verifies its existance and type to conditionally return its dir and file name
 * @param {string} destOutputPath - the path from where to extract the dir path and name
 * @returns {FilePathAndName} - the directory where to put the file and the file name (which is undefined when the provided destOutputPath is a directory)
 */
export function getOutputFilePathAndName(
	destOutputPath: string,
	fsStatSyncAndPathResolveWrapper = fsStatSyncAndPathResolve
): FilePathAndName {
	const resolvedOutputPath = fsStatSyncAndPathResolveWrapper.resolve(destOutputPath);
	const outputDirname = dirname(resolvedOutputPath);
	const outputBasename = basename(resolvedOutputPath);
	try {
		const outputPathStats = fsStatSyncAndPathResolveWrapper.statSync(resolvedOutputPath);
		// the destination does exist
		if (outputPathStats.isDirectory()) {
			// and is a directory
			return [resolvedOutputPath];
		} else if (outputPathStats.isFile()) {
			// as an existing file
			return [outputDirname, outputBasename];
		}
	} catch (e) {
		// the destination doesn't exist
		const outputParentPathStats = fsStatSyncAndPathResolveWrapper.statSync(outputDirname);
		// the parent exists
		if (outputParentPathStats.isDirectory()) {
			return [outputDirname, outputBasename];
		}
		throw new Error(`The path ${outputDirname} is not a directory!`);
	}
	throw new Error(`The destination is neither a folder nor a file!`);
}
Example #28
Source File: hostFactory.ts    From backstage with Apache License 2.0 6 votes vote down vote up
async function getGeneratedCertificate(hostname: string, logger?: Logger) {
  const hasModules = await fs.pathExists('node_modules');
  let certPath;
  if (hasModules) {
    certPath = resolvePath(
      'node_modules/.cache/backstage-backend/dev-cert.pem',
    );
    await fs.ensureDir(dirname(certPath));
  } else {
    certPath = resolvePath('.dev-cert.pem');
  }

  let cert = undefined;
  if (await fs.pathExists(certPath)) {
    const stat = await fs.stat(certPath);
    const ageMs = Date.now() - stat.ctimeMs;
    if (stat.isFile() && ageMs < ALMOST_MONTH_IN_MS) {
      cert = await fs.readFile(certPath);
    }
  }

  if (cert) {
    logger?.info('Using existing self-signed certificate');
    return {
      key: cert,
      cert: cert,
    };
  }

  logger?.info('Generating new self-signed certificate');
  const newCert = await createCertificate(hostname);
  await fs.writeFile(certPath, newCert.cert + newCert.key, 'utf8');
  return newCert;
}
Example #29
Source File: prerender.ts    From vite-plugin-ssr with MIT License 6 votes vote down vote up
function write(
  url: string,
  pageContext: Record<string, unknown>,
  fileExtension: '.html' | '.pageContext.json',
  fileContent: string,
  root: string,
  outDir: string,
  doNotCreateExtraDirectory: boolean,
  concurrencyLimit: pLimit.Limit,
  onPagePrerender: Function | null,
) {
  return concurrencyLimit(async () => {
    const fileUrl = getFileUrl(url, fileExtension, fileExtension === '.pageContext.json' || doNotCreateExtraDirectory)
    assert(fileUrl.startsWith('/'))
    const filePathRelative = fileUrl.slice(1).split('/').join(sep)
    assert(!filePathRelative.startsWith(sep))
    const filePath = join(root, outDir, 'client', filePathRelative)
    if (onPagePrerender) {
      objectAssign(pageContext, {
        _prerenderResult: {
          filePath,
          fileContent,
        },
      })
      await onPagePrerender(pageContext)
    } else {
      const { promises } = require('fs')
      const { writeFile, mkdir } = promises
      await mkdir(dirname(filePath), { recursive: true })
      await writeFile(filePath, fileContent)
      console.log(`${gray(join(outDir, 'client') + sep)}${blue(filePathRelative)}`)
    }
  })
}