path#parse TypeScript Examples

The following examples show how to use path#parse. 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: Reload.ts    From yumeko with GNU Affero General Public License v3.0 6 votes vote down vote up
@constantly
    public async exec(msg: Message, { command, dontBuild }: { command?: Command; dontBuild: boolean }): Promise<Message> {
        const { execute } = this.collector.commands.get("exec") as ExecCommand;
        const { ext, dir } = parse(this.dir);
        // check if code runned by tsc or ts-node
        if (dir.includes("/dist/") && ext === ".js" && !dontBuild) await execute("yarn build");
        if (command) {
            this.reload([command]);
            return msg.ctx.send(`✅ **| Succes reloading command \`${command.identifier}\`**`);
        }
        this.reload(this.collector.commands.array());
        return msg.ctx.send("✅ **| Succes reloading all commands**");
    }
Example #3
Source File: utilsFS.ts    From yfm-transform with MIT License 6 votes vote down vote up
export function getFileTokens(path: string, state: StateCore, options: GetFileTokensOpts) {
    const {
        getVarsPerFile,
        vars,
        disableLiquid,
        disableLint,
        lintMarkdown,
        disableTitleRefSubstitution,
        disableCircularError,
        inheritVars = true,
    } = options;
    let content;

    const builtVars = (getVarsPerFile && !inheritVars ? getVarsPerFile(path) : vars) || {};

    if (filesCache[path]) {
        content = filesCache[path];
    } else {
        content = readFileSync(path, 'utf8');
        filesCache[path] = content;
    }

    let sourceMap;

    if (!disableLiquid) {
        const liquidResult = liquid(content, builtVars, path, {withSourceMap: true});

        content = liquidResult.output;
        sourceMap = liquidResult.sourceMap;
    }

    if (!disableLint && lintMarkdown) {
        lintMarkdown({
            input: content,
            path,
            sourceMap,
        });
    }

    const meta = state.md.meta;
    const tokens = state.md.parse(content, {
        ...state.env,
        path,
        disableTitleRefSubstitution,
        disableCircularError,
    });
    state.md.meta = meta;

    return tokens;
}
Example #4
Source File: utilsFS.ts    From yfm-transform with MIT License 6 votes vote down vote up
export function resolveRelativePath(fromPath: string, relativePath: string) {
    const {dir: fromDir} = parse(fromPath);

    return resolve(fromDir, relativePath);
}
Example #5
Source File: Loader.ts    From ZenTS with MIT License 6 votes vote down vote up
constructor(templateFiles: string[]) {
    const files = templateFiles.map((filePath) => parse(filePath))
    let basePath = fs.resolveZenPath('view')

    if (basePath.endsWith(sep)) {
      basePath = basePath.slice(0, -1)
    }

    for (const file of files) {
      const filePath = join(file.dir, file.base)
      let key = file.dir.replace(basePath, '').substr(1).replace(sep, '/')
      key += key.length ? `/${file.name}` : file.name

      this.templates.set(key, {
        path: filePath,
        src: readFileSync(filePath, {
          encoding: config.template.encoding,
        }),
        noCache: config.template.noCache ?? false,
      })
    }
  }
Example #6
Source File: AbstractZenFileLoader.ts    From ZenTS with MIT License 6 votes vote down vote up
/**
   * Load a given module and returns an unitialized version of the module. The exported class is guessed either
   * by using the default export (CommonJS) or by using the modules filename to determine the exported member.
   * This function will throw an error when no exported member could be found.
   *
   * @param filePath Absolute path to the module file
   */
  protected async loadModule<T>(filePath: string): Promise<LoadModuleResult<T>> {
    const module = (await import(filePath)) as CommonJSZenModule<T>
    const moduleKeys = Object.keys(module)
    const { name: filename } = parse(filePath)
    let classModule

    if (moduleKeys.includes('default')) {
      classModule = module.default
    } else if (moduleKeys.includes(filename)) {
      classModule = module[filename]
    } else {
      throw new Error('Unable to find the exported module member. Please use default export.')
    }

    return {
      key: filename.toLowerCase(),
      module: classModule,
    }
  }
Example #7
Source File: EmailTemplateLoader.ts    From ZenTS with MIT License 6 votes vote down vote up
public async load(): Promise<EmailTemplates> {
    const emailTemplates = new Map() as EmailTemplates
    const emailFilesPath = fs.resolveZenPath('email')

    if (!((await fs.exists(emailFilesPath)) || config.email.engine === 'plain')) {
      return emailTemplates
    }

    const filePaths = await this.loadFiles(emailFilesPath)

    for (const filePath of filePaths) {
      const { name } = parse(filePath)
      const content = await promises.readFile(filePath, {
        encoding: 'utf-8',
      })

      emailTemplates.set(name, content)
    }

    return emailTemplates
  }
Example #8
Source File: files.ts    From the-fake-backend with ISC License 6 votes vote down vote up
/**
 * Read the file and parse its content as json.
 *
 * @param path The file path
 * @return The file content
 */
export function readJSONFileSync(path: string): any {
  return JSON.parse(readFileSync(path).toString());
}
Example #9
Source File: files.ts    From the-fake-backend with ISC License 6 votes vote down vote up
/**
 * Return a boolean indicating that the dirent name includes the text.
 *
 * @param text The text to match
 * @param dirent The dirent object
 * @return A boolean indicating that the dirent name includes the text
 */
export function direntFilenameMatchText(text: string, dirent: Dirent): boolean {
  return parse(dirent.name).name === text;
}
Example #10
Source File: MediaController.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
@Post()
  @HttpAuth(UserRole.ADMIN, UserRole.AUTHOR)
  @HttpCode(HttpStatus.OK)
  @UseInterceptors(FileInterceptor('file'))
  @ApiBearerAuth()
  @ApiConsumes('multipart/form-data')
  @ApiBody({type: HttpRestApiModelCreateMediaBody})
  @ApiQuery({name: 'name', type: 'string', required: false})
  @ApiQuery({name: 'type', enum: MediaType})
  @ApiResponse({status: HttpStatus.OK, type: HttpRestApiResponseMedia})
  public async createMedia(
    @Req() request: HttpRequestWithUser,
    @UploadedFile() file: MulterFile,
    @Query() query: HttpRestApiModelCreateMediaQuery
    
  ): Promise<CoreApiResponse<MediaUseCaseDto>> {
  
    const adapter: CreateMediaAdapter = await CreateMediaAdapter.new({
      executorId: request.user.id,
      name      : query.name || parse(file.originalname).name,
      type      : query.type,
      file      : file.buffer,
    });
    
    const createdMedia: MediaUseCaseDto = await this.createMediaUseCase.execute(adapter);
    this.setFileStorageBasePath([createdMedia]);
    
    return CoreApiResponse.success(createdMedia);
  }
Example #11
Source File: add-to-sln.ts    From nx-dotnet with MIT License 6 votes vote down vote up
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 #12
Source File: upload.ts    From swarm-cli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private async uploadSingleFile(tag?: Tag): Promise<string> {
    const contentType = this.contentType || getMime(this.path) || undefined
    setCurlStore({
      path: this.path,
      folder: false,
      type: 'stream',
    })
    const buffer = FS.readFileSync(this.path)
    const parsedPath = parse(this.path)
    const { reference } = await this.bee.uploadFile(this.stamp, buffer, this.determineFileName(parsedPath.base), {
      tag: tag && tag.uid,
      pin: this.pin,
      encrypt: this.encrypt,
      contentType,
    })
    this.hash = reference

    return `${this.bee.url}/bzz/${this.hash}/`
  }
Example #13
Source File: download.ts    From swarm-cli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private async downloadFork(fork: EnrichedFork, address: BzzAddress, isSingleFork: boolean): Promise<void> {
    if ((!isSingleFork || !this.stdout) && !this.quiet) {
      if (this.curl) {
        this.console.log(chalk.dim(fork.path))
      } else {
        process.stdout.write(chalk.dim(fork.path))
      }
    }
    const parsedForkPath = parse(fork.path)
    const data = await this.bee.downloadData(referenceToHex(fork.node.getEntry as Reference))

    if (isSingleFork && this.stdout) {
      process.stdout.write(data)

      return
    }

    const destination = this.destination || address.hash
    const destinationFolder = join(destination, parsedForkPath.dir)

    if (!directoryExists(destinationFolder)) {
      await fs.promises.mkdir(destinationFolder, { recursive: true })
    }

    if (!this.quiet && !this.curl) {
      process.stdout.write(' ' + chalk.green('OK') + '\n')
    }
    await fs.promises.writeFile(join(destination, fork.fsPath), data)
  }
Example #14
Source File: ChartDownload.ts    From Bridge with GNU General Public License v3.0 6 votes vote down vote up
constructor(public versionID: number, private data: NewDownload) {
    this.updateGUI('', 'Waiting for other downloads to finish...', 'good')
    this.files = this.filterDownloadFiles(data.driveData.files)
    this.individualFileProgressPortion = 80 / this.files.length
    if (data.driveData.inChartPack) {
      this.destinationFolderName = sanitizeFilename(parse(data.driveData.files[0].name).name)
    } else {
      this.destinationFolderName = sanitizeFilename(`${this.data.artist} - ${this.data.chartName} (${this.data.charter})`)
    }
  }
Example #15
Source File: resolveSymbolset.ts    From geostyler-mapfile-parser with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Parses the Mapfile data if it contains single SYMBOL tags and replaces the name with the filename within the
 * symbol tag
 *
 * @param {Mapfile} mapfile Parsed Mapfile Object
 */
export function resolveSymbolsFromMapfile(mapfile: Mapfile): Mapfile {
  const symbols = mapfile.map.symbols;

  if (mapfile.map.layers) {
    mapfile.map.layers.forEach((layer: MapfileLayer) => {
      if (layer.classes) {
        layer.classes.forEach((mclass: MapfileClass) => {
          if (mclass.styles) {
            const styles: MapfileStyle[] = mclass.styles;
            styles.forEach((style: MapfileStyle) => {
              if (style.symbol) {
                symbols.forEach((symbol: any) => {
                  if (
                    symbol.name && symbol.image && symbol.name === style.symbol
                  ) {
                    style.symbol = (parse(symbol.image)
                      .base as unknown) as MapfileSymbol;
                  }
                });
              }
            });
          }  else if (mclass.labels) {
            // parse symbol data within a style tag of a label
            mclass.labels.forEach((label) => {
              const styles: MapfileStyle[] = label.styles as MapfileStyle[];
              styles?.forEach((style: MapfileStyle) => {
                symbols?.forEach((symbol: any) => {
                  if (
                    symbol.name &&
                    symbol.image &&
                    symbol.name === style.symbol
                  ) {
                    style.symbol = (parse(symbol.image)
                      .base as unknown) as MapfileSymbol;
                  }
                });
              });
            });
          }
        });
      }
    });
  }
  return mapfile;
}
Example #16
Source File: mime.ts    From swarm-cli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
export function getMime(path: string): string | null {
  const { ext } = parse(path)

  return mimes[ext.toLowerCase()] || null
}
Example #17
Source File: nexpect.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
export function nspawn(command: string | string[], params: string[] = [], options: SpawnOptions = {}) {
  if (Array.isArray(command)) {
    params = command;
    command = params.shift();
  } else if (typeof command === 'string') {
    const parsedPath = parse(command);
    const parsedArgs = parsedPath.base.split(' ');
    command = join(parsedPath.dir, parsedArgs[0]);
    params = params || parsedArgs.slice(1);
  }

  let childEnv = undefined;
  let pushEnv = undefined;

  // For push operations in E2E we have to explicitly disable the Amplify Console App creation
  // as for the tests that need it, it is already enabled for init, setting the env var here
  // disables the post push check we have in the CLI.
  if (params.length > 0 && params[0].toLowerCase() === 'push') {
    pushEnv = {
      CLI_DEV_INTERNAL_DISABLE_AMPLIFY_APP_CREATION: '1',
    };
  }

  // If we have an environment passed in we've to add the current process' environment, otherwised the forked
  // process would not have $PATH and others that is required to run amplify-cli successfully.
  // to be able to disable CI detection we do need to pass in a childEnv
  if (options.env || pushEnv || options.disableCIDetection === true) {
    childEnv = {
      ...process.env,
      ...pushEnv,
      ...options.env,
    };

    // Undo ci-info detection, required for some tests
    if (options.disableCIDetection === true) {
      delete childEnv.CI;
      delete childEnv.CONTINUOUS_INTEGRATION;
      delete childEnv.BUILD_NUMBER;
      delete childEnv.TRAVIS;
      delete childEnv.GITHUB_ACTIONS;
      delete childEnv.CIRCLECI;
      delete childEnv.CIRCLE_PULL_REQUEST;
    }
  }

  let context: Context = {
    command: command,
    cwd: options.cwd || undefined,
    env: childEnv || undefined,
    ignoreCase: options.ignoreCase || true,
    noOutputTimeout: options.noOutputTimeout || DEFAULT_NO_OUTPUT_TIMEOUT,
    params: params,
    queue: [],
    stripColors: options.stripColors,
    process: undefined,
    getRecording: () => {
      if (context.process) {
        return context.process.getRecording();
      }
    },
  };

  return chain(context);
}
Example #18
Source File: tocs.ts    From yfm-docs with MIT License 5 votes vote down vote up
/**
 * Copies all files of include toc to original dir.
 * @param tocPath
 * @param destDir
 * @return
 * @private
 */
function _copyTocDir(tocPath: string, destDir: string) {
    const {input: inputFolderPath} = ArgvService.getConfig();

    const {dir: tocDir} = parse(tocPath);
    const files: string[] = walkSync(tocDir, {
        globs: ['**/*.*'],
        ignore: ['**/toc.yaml'],
        directories: false,
    });

    files.forEach((relPath) => {
        const from = resolve(tocDir, relPath);
        const to = resolve(destDir, relPath);
        const fileExtension = extname(relPath);
        const isMdFile = fileExtension === '.md';

        shell.mkdir('-p', parse(to).dir);

        if (isMdFile) {
            const fileContent = readFileSync(from, 'utf8');
            const sourcePath = relative(inputFolderPath, from);
            const fileData = {sourcePath};
            const updatedFileContent = getContentWithUpdatedStaticMetadata(fileContent, {
                fileData,
                addSourcePath: true,
            });

            writeFileSync(to, updatedFileContent);
        } else {
            copyFileSync(from, to);
        }
    });
}
Example #19
Source File: index.ts    From yfm-transform with MIT License 5 votes vote down vote up
function defaultTransformLink(href: string) {
    const parsed = url.parse(href);

    return url.format({
        ...parsed,
        pathname: parsed.pathname?.replace(PAGE_LINK_REGEXP, '.html'),
    });
}
Example #20
Source File: ElectronUtilFunctions.ts    From Bridge with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @returns `true` if `name` has a valid video file extension.
 */
export function hasVideoExtension(name: string) {
  return (['.mp4', '.avi', '.webm', '.ogv', '.mpeg'].includes(parse(lower(name)).ext))
}
Example #21
Source File: jest-test-test.ts    From askql with MIT License 5 votes vote down vote up
{ name } = parse(jestTestPath)
Example #22
Source File: index.ts    From yfm-transform with MIT License 4 votes vote down vote up
// eslint-disable-next-line complexity
function processLink(state: StateCore, tokens: Token[], idx: number, opts: ProcOpts) {
    const {path: startPath, root, transformLink, notFoundCb, needSkipLinkFn, log} = opts;
    const currentPath = state.env.path || startPath;
    const linkToken = tokens[idx];
    const nextToken = tokens[idx + 1];

    let href = getHrefTokenAttr(linkToken);

    if (!href) {
        log.error(`Empty link in ${bold(startPath)}`);
        return;
    }

    const {pathname, hash} = url.parse(href);
    let file;
    let fileExists;
    let isPageFile;

    if (!isLocalUrl(href)) {
        linkToken.attrSet('target', '_blank');
        linkToken.attrSet('rel', 'noreferrer noopener');
        return;
    }

    if (pathname) {
        file = resolve(path.parse(currentPath).dir, pathname);
        fileExists = isFileExists(file);
        isPageFile = PAGE_LINK_REGEXP.test(pathname);

        if (isPageFile && !fileExists) {
            let needShowError = true;
            if (needSkipLinkFn) {
                needShowError = !needSkipLinkFn(href);
            }

            if (notFoundCb && needShowError) {
                notFoundCb(file.replace(root, ''));
            }

            if (needShowError) {
                log.error(`Link is unreachable: ${bold(href)} in ${bold(currentPath)}`);
            }
        }
    } else if (hash) {
        file = startPath;
        fileExists = true;
        isPageFile = true;
    } else {
        return;
    }

    const isEmptyLink = nextToken.type === 'link_close';
    const isTitleRefLink = nextToken.type === 'text' && nextToken.content === '{#T}';
    if (
        (isEmptyLink || isTitleRefLink) &&
        fileExists &&
        isPageFile &&
        !state.env.disableTitleRefSubstitution
    ) {
        addTitle({
            hash,
            file,
            state,
            opts,
            isEmptyLink,
            tokens,
            idx,
            nextToken,
            href,
            currentPath,
            log,
        });
    }

    let newPathname = '';
    if (currentPath !== startPath) {
        newPathname = relative(parse(startPath).dir, file);

        href = url.format({
            ...url.parse(href),
            pathname: newPathname,
        });
    }

    if (pathname || newPathname) {
        const transformer = transformLink || defaultTransformLink;
        linkToken.attrSet('href', transformer(href));
    }
}