path#posix TypeScript Examples

The following examples show how to use path#posix. 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: 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 #2
Source File: QBittorrent.ts    From cross-seed with Apache License 2.0 6 votes vote down vote up
async isSubfolderContentLayout(searchee: Searchee): Promise<boolean> {
		const response = await this.request(
			"/torrents/files",
			`hash=${searchee.infoHash}`,
			X_WWW_FORM_URLENCODED
		);

		const files: TorrentFiles[] = JSON.parse(response);
		const [{ name }] = files;
		return files.length === 1 && name !== posix.basename(name);
	}
Example #3
Source File: distLink.ts    From telefunc with MIT License 6 votes vote down vote up
function distLinkOn(): Plugin {
  let ssr: boolean
  let root: undefined | string
  return {
    name: 'telefunc:distLinkOn',
    apply: 'build',
    configResolved(config) {
      ssr = isSSR_config(config)
      root = config.root ? toPosixPath(config.root) : toPosixPath(process.cwd())
    },
    generateBundle() {
      assert(typeof ssr === 'boolean')
      if (!ssr) {
        return
      }
      assert(root)
      // To `require()` an absolute path doesn't seem to work on Vercel
      const rootRelative = posix.relative(toPosixPath(dir), root)
      writeFileSync(
        telefuncFilesGlobFromDistPath,
        [
          'exports.distLinkActivated = true;',
          `const { telefuncFilesGlob } = require('${rootRelative}/dist/server/telefuncFilesGlob.js');`,
          `exports.telefuncFilesGlob = telefuncFilesGlob;`,
          ''
        ].join('\n')
      )
    }
  } as Plugin
}
Example #4
Source File: filesystemPathHandling.ts    From telefunc with MIT License 6 votes vote down vote up
function toPosixPath(path: string) {
  if (process.platform !== 'win32') {
    assert(sep === posix.sep)
    assertPosixPath(path)
    return path
  } else {
    assert(sep === win32.sep)
    const pathPosix = path.split(win32.sep).join(posix.sep)
    assertPosixPath(pathPosix)
    return pathPosix
  }
}
Example #5
Source File: transformTelefuncFileSync.ts    From telefunc with MIT License 6 votes vote down vote up
function transformTelefuncFileSync(id: string, root: string, exportNames: readonly string[] | string[]) {
  assertPosixPath(id)
  assertPosixPath(root)

  const telefuncFilePath = '/' + posix.relative(root, id)
  assert(!telefuncFilePath.startsWith('/.'))
  assertPosixPath(telefuncFilePath)

  return {
    code: getCode(exportNames, telefuncFilePath),
    map: null
  }
}
Example #6
Source File: loadTelefuncFilesFromConfig.ts    From telefunc with MIT License 6 votes vote down vote up
async function loadTelefuncFilesFromConfig(telefuncFiles: string[], root: string | null): Promise<TelefuncFiles> {
  assertUsage(root, 'You need to set `telefuncConfig.root`.')
  const telefuncFilesLoaded: TelefuncFiles = {}
  await Promise.all(
    telefuncFiles.map(async (telefuncFilePath) => {
      const path = posix.relative(toPosixPath(root), toPosixPath(telefuncFilePath))
      assertPosixPath(path)
      assertUsage(
        !path.startsWith('../'),
        `The telefunc file \`${telefuncFilePath}\` is not inlcuded in your project root \`${root}\`.`
      )
      assert(!path.startsWith('/') && !path.startsWith('.'))
      telefuncFilesLoaded['/' + path] = await dynamicImport(telefuncFilePath)
    })
  )
  return telefuncFilesLoaded
}
Example #7
Source File: addFileScope.ts    From vanilla-extract with MIT License 6 votes vote down vote up
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 #8
Source File: index.ts    From web with MIT License 6 votes vote down vote up
function getMatcher(patterns?: string[]) {
  if (!patterns || patterns.length === 0) {
    return () => true;
  }

  const key = patterns.join('');
  let matcher = cachedMatchers.get(key);
  if (!matcher) {
    const resolvedPatterns = patterns.map(pattern =>
      !isAbsolute(pattern) && !pattern.startsWith('*')
        ? posix.join(coverageBaseDir, pattern)
        : pattern,
    );
    matcher = picoMatch(resolvedPatterns);
    cachedMatchers.set(key, matcher);
  }
  return matcher;
}
Example #9
Source File: TestProject.ts    From yarn-plugins with MIT License 6 votes vote down vote up
public static async setup(): Promise<TestProject> {
    const dir = await tmp.dir();
    const pluginBundles = await globby('packages/*/bundles/**/*.js', {
      cwd: PROJECT_DIR,
    });
    const plugins = pluginBundles.map((src) => ({
      src,
      name: '@yarnpkg/' + basename(src, extname(src)),
      dest: posix.join('.yarn', 'plugins', ...src.split(sep).slice(3)),
    }));

    for (const path of plugins) {
      await copy(join(PROJECT_DIR, path.src), join(dir.path, path.dest));
    }

    const yarnConfig = safeLoad(
      await readFile(join(PROJECT_DIR, '.yarnrc.yml'), 'utf8'),
    ) as Record<string, unknown>;

    // Create .yarnrc.yml
    await outputFile(
      join(dir.path, '.yarnrc.yml'),
      safeDump({
        yarnPath: join(PROJECT_DIR, yarnConfig.yarnPath as string),
        plugins: plugins.map((plugin) => ({
          path: plugin.dest,
          spec: plugin.name,
        })),
      }),
    );

    // Create package.json
    await outputJSON(join(dir.path, 'package.json'), {
      private: true,
      workspaces: ['packages/*'],
    });

    return new TestProject(dir);
  }
Example #10
Source File: resolvefiledestination.ts    From baidupcs-batch-upload with MIT License 6 votes vote down vote up
export function resolvefiledestination(
    file: string,
    input: string,
    dest: string
) {
    const inputbase = path.basename(input);
    const destination = posix.dirname(
        posix
            .resolve(dest, inputbase, path.relative(input, file))
            .replace(/\\/g, "/")
    );
    return destination;
}
Example #11
Source File: test-util.ts    From karma-test-explorer with MIT License 6 votes vote down vote up
withUnixStyleSeparator = (filePath: string) => filePath.split(pathSeparator).join(posix.sep)
Example #12
Source File: utils.ts    From karma-test-explorer with MIT License 6 votes vote down vote up
normalizePath = (filePath: string): string => {
  return process.platform === 'win32'
    ? filePath
        .replace(/^[\/]?([A-Za-z]:)/, (_, drive) => drive.toUpperCase())
        .split(sep)
        .join(posix.sep)
    : filePath;
}
Example #13
Source File: test-suite-organizer.ts    From karma-test-explorer with MIT License 6 votes vote down vote up
private flattenSingChildPaths(
    suite: TestFolderSuiteInfo,
    flattenOptions: TestSuiteFolderGroupingOptions
  ): TestFolderSuiteInfo {
    if (!flattenOptions.flattenSingleChildFolders && !flattenOptions.flattenSingleSuiteFiles) {
      return suite;
    }

    suite.children = suite.children.map(childSuite => {
      if (childSuite.suiteType === TestSuiteType.Folder) {
        return this.flattenSingChildPaths(childSuite, flattenOptions);
      } else if (childSuite.suiteType === TestSuiteType.File && flattenOptions.flattenSingleSuiteFiles) {
        const singleChild = childSuite.children.length === 1 ? childSuite.children[0] : undefined;

        return singleChild?.type === TestType.Suite
          ? { ...singleChild, suiteType: TestSuiteType.File, file: singleChild.file! }
          : childSuite;
      }
      return childSuite;
    });

    const singleChild = suite.children.length === 1 ? suite.children[0] : undefined;

    let flattenedTestSuite: TestFolderSuiteInfo = suite;

    if (flattenOptions.flattenSingleChildFolders && singleChild?.suiteType === TestSuiteType.Folder) {
      const flattenedSuiteName = posix.join(suite.name, singleChild.name);
      flattenedTestSuite = { ...singleChild, name: flattenedSuiteName, label: flattenedSuiteName };
    }

    return flattenedTestSuite;
  }
Example #14
Source File: virustotal.ts    From ghaction-virustotal with MIT License 6 votes vote down vote up
monitorItems(filename: string, path?: string): Promise<UploadData> {
    const {name, mime, size, file} = asset(filename);
    const fd = new FormData();
    fd.append('file', file, {
      filename: name,
      contentType: mime,
      knownLength: size
    });

    const itemPath: string = posix.join(path ? path : '/', name);
    core.debug(`monitorItems path: ${itemPath}`);
    fd.append('path', itemPath);

    return this.instance
      .post('/monitor/items', fd.getBuffer(), {
        headers: fd.getHeaders()
      })
      .then(upload => {
        const data = upload.data.data as UploadData;
        data.url = `https://www.virustotal.com/monitor/analyses/item:${data.id}`;
        return data;
      })
      .catch(error => {
        throw new Error(`Cannot send ${name} to VirusTotal Monitor at ${itemPath}: ${error}`);
      });
  }
Example #15
Source File: handlers.ts    From backstage with Apache License 2.0 6 votes vote down vote up
export async function handleAllFiles(
  fileHandlers: FileHandler[],
  files: FileDiff[],
  promptFunc: PromptFunc,
) {
  for (const file of files) {
    const path = file.path.split(sep).join(posix.sep);
    const fileHandler = fileHandlers.find(handler =>
      handler.patterns.some(pattern =>
        typeof pattern === 'string' ? pattern === path : pattern.test(path),
      ),
    );
    if (fileHandler) {
      await fileHandler.handler(file, promptFunc);
    } else {
      throw new Error(`No template file handler found for ${path}`);
    }
  }
}
Example #16
Source File: uploadandcheck.ts    From baidupcs-batch-upload with MIT License 5 votes vote down vote up
export async function uploadandcheck(
    file: string,
    destination: string
): Promise<void> {
    const inputbase = path.basename(file);
    const remotefile = posix.join(destination, inputbase);

    if (Math.random() > 0.5) {
        const starttime = Date.now();
        const fileexist = await checkexist(remotefile);

        if (fileexist) {
            console.log(
                ["检查网盘中存在此文件,跳过上传成功:", file, remotefile].join(
                    "\n"
                )
            );
            const endtime = Date.now();
            const durtime = (endtime - starttime) / 1000;
            console.log("用时" + durtime + "秒");
            return;
        } else {
            console.warn(
                [
                    "检查网盘中不存在此文件,开始上传文件:",
                    file,
                    remotefile,
                ].join("\n")
            );
        }
    }
    await upload(file, destination);

    const starttime = Date.now();
    const fileexist = await checkexist(remotefile);
    if (fileexist) {
        console.log(
            ["检查网盘中存在此文件,上传文件成功:", file, remotefile].join(
                "\n"
            )
        );
        const endtime = Date.now();
        const durtime = (endtime - starttime) / 1000;
        console.log("用时" + durtime + "秒");
        return;
    } else {
        console.warn(
            ["检查网盘中不存在此文件,重新上传文件:", file, remotefile].join(
                "\n"
            )
        );
        return await retryupload(file, destination);
    }
}
Example #17
Source File: mimeTypesPlugin.ts    From web with MIT License 5 votes vote down vote up
function createMatcher(rootDir: string, pattern: string) {
  const resolvedPattern =
    !isAbsolute(pattern) && !pattern.startsWith('*') ? posix.join(rootDir, pattern) : pattern;
  return picoMatch(resolvedPattern, { dot: true });
}
Example #18
Source File: project-factory.ts    From karma-test-explorer with MIT License 5 votes vote down vote up
private shouldActivateAdapterForWorkspaceFolder(
    workspaceFolderPath: string,
    config: WorkspaceConfiguration
  ): boolean {
    const enableExtension = config.get<boolean | null>(WorkspaceConfigSetting.EnableExtension);

    if (typeof enableExtension === 'boolean') {
      this.logger.debug(
        () =>
          `${enableExtension ? 'Including' : 'Excluding'} projects in workspace ` +
          `folder '${workspaceFolderPath}' because the extension has been ` +
          `explicitly ${enableExtension ? 'enabled' : 'disabled'} by setting the ` +
          `'${EXTENSION_CONFIG_PREFIX}.${WorkspaceConfigSetting.EnableExtension}' ` +
          `setting to ${enableExtension ? 'true' : 'false'}`
      );
      return enableExtension;
    }

    const configuredExtensionSetting = Object.values(WorkspaceConfigSetting).find(
      configSetting => config.inspect(configSetting)?.workspaceFolderValue ?? false
    );

    if (configuredExtensionSetting !== undefined) {
      this.logger.debug(
        () =>
          `Including projects in workspace folder '${workspaceFolderPath}' ` +
          `because it has one or more extension settings configured: ` +
          `${configuredExtensionSetting}`
      );
      return true;
    }

    const projectRootPath = config.get<string>(WorkspaceConfigSetting.ProjectRootPath) ?? '';
    const projectPackageJsonFilePath = posix.join(workspaceFolderPath, projectRootPath, 'package.json');
    const workspacePackageJsonFilePath = posix.join(workspaceFolderPath, 'package.json');

    let packageJsonFilePath: string | undefined;

    try {
      if (existsSync(projectPackageJsonFilePath)) {
        packageJsonFilePath = projectPackageJsonFilePath;
      }
    } catch (error) {
      this.logger.debug(() => `Could not find a project package.json file at ${projectPackageJsonFilePath}`);
    }

    try {
      if (!packageJsonFilePath && existsSync(workspacePackageJsonFilePath)) {
        packageJsonFilePath = workspacePackageJsonFilePath;
      }
    } catch (error) {
      this.logger.debug(() => `Could not find a workspace package.json file at ${workspacePackageJsonFilePath}`);
    }

    const packageJson: { devDependencies: Record<string, string> } | undefined = packageJsonFilePath
      ? require(projectPackageJsonFilePath)
      : undefined;

    if (packageJson && Object.keys(packageJson.devDependencies).includes('karma')) {
      this.logger.debug(
        () =>
          `Including projects in workspace folder '${workspaceFolderPath}' ` +
          `because related package.json file '${packageJsonFilePath}' has a karma dev dependency`
      );
      return true;
    }
    return false;
  }
Example #19
Source File: index.ts    From vanilla-extract with MIT License 5 votes vote down vote up
{ relative, normalize, dirname } = posix
Example #20
Source File: isChildPath.test.ts    From backstage with Apache License 2.0 5 votes vote down vote up
describe('isChildPath', () => {
  it('should check child posix paths', () => {
    jest.isolateModules(() => {
      jest.setMock('path', posix);
      const { isChildPath } = require('./isChildPath');

      expect(isChildPath('/', '/')).toBe(true);
      expect(isChildPath('/x', '/x')).toBe(true);
      expect(isChildPath('/x', '/x/y')).toBe(true);
      expect(isChildPath('/x', '/x/x')).toBe(true);
      expect(isChildPath('/x', '/x/y/z')).toBe(true);
      expect(isChildPath('/x/y', '/x/y/z')).toBe(true);
      expect(isChildPath('/x/y/z', '/x/y/z')).toBe(true);
      expect(isChildPath('/x/a b c/z', '/x/a b c/z')).toBe(true);
      expect(isChildPath('/', '/ yz')).toBe(true);

      expect(isChildPath('/x', '/y')).toBe(false);
      expect(isChildPath('/x', '/')).toBe(false);
      expect(isChildPath('/x', '/x y')).toBe(false);
      expect(isChildPath('/x y', '/x yz')).toBe(false);
      expect(isChildPath('/ yz', '/')).toBe(false);
      expect(isChildPath('/x', '/')).toBe(false);

      jest.dontMock('path');
    });
  });

  it('should check child win32 paths', () => {
    jest.isolateModules(() => {
      jest.setMock('path', win32);
      const { isChildPath } = require('./isChildPath');

      expect(isChildPath('/x', '/x')).toBe(true);
      expect(isChildPath('/x', '/x/y')).toBe(true);
      expect(isChildPath('/x', '/x/x')).toBe(true);
      expect(isChildPath('/x', '/x/y/z')).toBe(true);
      expect(isChildPath('/x/y', '/x/y/z')).toBe(true);
      expect(isChildPath('/x/y/z', '/x/y/z')).toBe(true);
      expect(isChildPath('Z:', 'Z:')).toBe(true);
      expect(isChildPath('C:/', 'c:/')).toBe(true);
      expect(isChildPath('C:/x', 'C:/x')).toBe(true);
      expect(isChildPath('C:/x', 'c:/x')).toBe(true);
      expect(isChildPath('C:/x', 'C:/x/y')).toBe(true);
      expect(isChildPath('d:/x', 'D:/x/y')).toBe(true);

      expect(isChildPath('/x', '/y')).toBe(false);
      expect(isChildPath('/x', '/')).toBe(false);
      expect(isChildPath('C:/', 'D:/')).toBe(false);
      expect(isChildPath('C:/x', 'D:/x')).toBe(false);
      expect(isChildPath('D:/x', 'CD:/x')).toBe(false);
      expect(isChildPath('D:/x', 'D:/y')).toBe(false);

      jest.dontMock('path');
    });
  });
});
Example #21
Source File: filesystemPathHandling.ts    From telefunc with MIT License 5 votes vote down vote up
function toSystemPath(path: string) {
  path = path.split(posix.sep).join(sep)
  path = path.split(win32.sep).join(sep)
  return path
}
Example #22
Source File: SkinFolderReader.ts    From rewind with MIT License 5 votes vote down vote up
join = posix.join
Example #23
Source File: index.ts    From vanilla-extract with MIT License 4 votes vote down vote up
export default function (): PluginObj<Context> {
  return {
    pre({ opts }) {
      if (!opts.filename) {
        // TODO Make error better
        throw new Error('Filename must be available');
      }

      this.isESM = false;
      this.isCssFile = cssFileFilter.test(opts.filename);
      this.alreadyCompiled = false;

      this.importIdentifiers = new Map();
      this.namespaceImport = '';

      const packageInfo = getPackageInfo(opts.cwd);

      if (!packageInfo.name) {
        throw new Error(
          `Closest package.json (${packageInfo.path}) must specify name`,
        );
      }
      this.packageName = packageInfo.name;
      // Encode windows file paths as posix
      this.filePath = posix.join(
        ...relative(packageInfo.dirname, opts.filename).split(sep),
      );
    },
    visitor: {
      Program: {
        exit(path) {
          if (this.isCssFile && !this.alreadyCompiled) {
            // Wrap module with file scope calls
            const buildSetFileScope = this.isESM
              ? buildSetFileScopeESM
              : buildSetFileScopeCJS;
            path.unshiftContainer(
              'body',
              buildSetFileScope({
                filePath: t.stringLiteral(this.filePath),
                packageName: t.stringLiteral(this.packageName),
              }),
            );

            path.pushContainer('body', buildEndFileScope());
          }
        },
      },
      ImportDeclaration(path) {
        this.isESM = true;
        if (!this.isCssFile || this.alreadyCompiled) {
          // Bail early if file isn't a .css.ts file or the file has already been compiled
          return;
        }

        if (path.node.source.value === filescopePackageIdentifier) {
          // If file scope import is found it means the file has already been compiled
          this.alreadyCompiled = true;
          return;
        } else if (packageIdentifiers.has(path.node.source.value)) {
          path.node.specifiers.forEach((specifier) => {
            if (t.isImportNamespaceSpecifier(specifier)) {
              this.namespaceImport = specifier.local.name;
            } else if (t.isImportSpecifier(specifier)) {
              const { imported, local } = specifier;

              const importName = (
                t.isIdentifier(imported) ? imported.name : imported.value
              ) as StyleFunction;

              if (styleFunctions.includes(importName)) {
                this.importIdentifiers.set(local.name, importName);
              }
            }
          });
        }
      },
      ExportDeclaration() {
        this.isESM = true;
      },
      CallExpression(path) {
        if (!this.isCssFile || this.alreadyCompiled) {
          // Bail early if file isn't a .css.ts file or the file has already been compiled
          return;
        }

        const { node } = path;

        if (
          t.isIdentifier(node.callee, { name: 'require' }) &&
          t.isStringLiteral(node.arguments[0], {
            value: filescopePackageIdentifier,
          })
        ) {
          // If file scope import is found it means the file has already been compiled
          this.alreadyCompiled = true;
          return;
        }

        const usedExport = getRelevantCall(
          node,
          this.namespaceImport,
          this.importIdentifiers,
        );

        if (usedExport && usedExport in debuggableFunctionConfig) {
          if (
            node.arguments.length <
            debuggableFunctionConfig[
              usedExport as keyof typeof debuggableFunctionConfig
            ].maxParams
          ) {
            const debugIdent = getDebugId(path);

            if (debugIdent) {
              node.arguments.push(t.stringLiteral(debugIdent));
            }
          }
        }
      },
    },
  };
}