path#sep TypeScript Examples

The following examples show how to use path#sep. 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: utils.ts    From yfm-transform with MIT License 7 votes vote down vote up
export function errorToString(path: string, error: LintError, sourceMap?: Dictionary<string>) {
    const ruleMoniker = error.ruleNames
        ? error.ruleNames.join(sep)
        : // @ts-expect-error bad markdownlint typings
          error.ruleName + sep + error.ruleAlias;
    const lineNumber = sourceMap ? sourceMap[error.lineNumber] : error.lineNumber;

    return (
        `${path}${lineNumber ? `: ${lineNumber}:` : ':'} ${ruleMoniker} ${error.ruleDescription}` +
        (error.errorDetail ? ` [${error.errorDetail}]` : '') +
        (error.errorContext ? ` [Context: "${error.errorContext}"]` : '')
    );
}
Example #2
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 #3
Source File: module-checker.ts    From malagu with MIT License 6 votes vote down vote up
check(modulePath: string) {
        try {
            this.pkg.resolveModule(modulePath);
            return true;
        } catch (error) {
            console.log(resolve(modulePath));
            const projectPath = this.pkg.projectPath.split(sep).join('/');
            if (modulePath.indexOf(projectPath) === 0 && existsSync(resolve(`${modulePath}.ts`))) {
                return true;
            } else if (modulePath.indexOf(projectPath) === 0 && existsSync(resolve(modulePath))) {
                return true;
            } else if (existsSync(resolve(this.pkg.projectPath, 'node_modules', modulePath))) {
                return true;
            } else {
                return false;
            }
        }
    }
Example #4
Source File: tree-data-provider.ts    From plugin-vscode with Apache License 2.0 6 votes vote down vote up
private createPackageData(packages: Package[]): PackageTreeItem[] {
        let packageItems: PackageTreeItem[] = [];
        packages.sort((package1, package2) => {
            return package1.name.localeCompare(package2.name!);
        });
        packages.forEach(projectPackage => {
            projectPackage.name = projectPackage.name === '.' ? window.activeTextEditor!.document.fileName
                .replace('.bal', '').split(sep).pop()!.toString() : projectPackage.name;
            if (projectPackage.name) {
                packageItems.push(new PackageTreeItem(projectPackage.name, '',
                    TreeItemCollapsibleState.Expanded, PROJECT_KIND.PACKAGE, fileUriToPath(projectPackage.filePath),
                    this.extensionPath, true, null, { modules: projectPackage.modules }));
            }
        });
        return packageItems;
    }
Example #5
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)}`)
    }
  })
}
Example #6
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 #7
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 #8
Source File: io.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
function createTar(dir: string, onError: (error: Error) => void): NodeJS.ReadableStream {
  const dirSegments = resolve(dir).split(sep);
  const parentDir = dirSegments.slice(0, dirSegments.length - 1).join(sep);
  const entryToAdd = dirSegments[dirSegments.length - 1];
  const packer = new Pack({ cwd: parentDir, filter: addDirectoryExecutablePermission });
  packer.on("error", onError);
  const stream = packer.add(entryToAdd);
  packer.end();

  return stream;
}
Example #9
Source File: mimeTypesPlugin.ts    From web with MIT License 6 votes vote down vote up
export function mimeTypesPlugin(mappings: MimeTypeMappings): Plugin {
  const matchers: Matcher[] = [];
  let rootDir: string;

  return {
    name: 'mime-types',

    serverStart({ config }) {
      ({ rootDir } = config);
      const matcherBaseDir = config.rootDir.split(sep).join('/');

      for (const [pattern, mimeType] of Object.entries(mappings)) {
        matchers.push({ fn: createMatcher(matcherBaseDir, pattern), mimeType });
      }
    },

    resolveMimeType(context) {
      const filePath = getRequestFilePath(context.url, rootDir);
      for (const matcher of matchers) {
        if (matcher.fn(filePath)) {
          return matcher.mimeType;
        }
      }
    },
  };
}
Example #10
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 #11
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 #12
Source File: writers.ts    From language-tools with MIT License 6 votes vote down vote up
file(diagnostics: Diagnostic[], workspaceDir: string, filename: string, text: string): void {
        diagnostics.filter(this.diagnosticFilter).forEach((diagnostic) => {
            const source = diagnostic.source ? `(${diagnostic.source})` : '';

            // Display location in a format that IDEs will turn into file links
            const { line, character } = diagnostic.range.start;
            // eslint-disable-next-line max-len
            this.stream.write(
                `${workspaceDir}${sep}${pc.green(filename)}:${line + 1}:${character + 1}\n`
            );

            // Show some context around diagnostic range
            const codePrevLine = this.getLine(diagnostic.range.start.line - 1, text);
            const codeLine = this.getCodeLine(diagnostic, text);
            const codeNextLine = this.getLine(diagnostic.range.end.line + 1, text);
            const code = codePrevLine + codeLine + codeNextLine;

            let msg;
            if (this.isVerbose) {
                msg = `${diagnostic.message} ${source}\n${pc.cyan(code)}`;
            } else {
                msg = `${diagnostic.message} ${source}`;
            }

            if (diagnostic.severity === DiagnosticSeverity.Error) {
                this.stream.write(`${pc.red('Error')}: ${msg}\n`);
            } else if (diagnostic.severity === DiagnosticSeverity.Warning) {
                this.stream.write(`${pc.yellow('Warn')}: ${msg}\n`);
            } else {
                this.stream.write(`${pc.gray('Hint')}: ${msg}\n`);
            }

            this.stream.write('\n');
        });
    }
Example #13
Source File: LintChartCommand.ts    From Helm-Intellisense with MIT License 6 votes vote down vote up
export async function LintChartCommand(collection: vscode.DiagnosticCollection): Promise<void> {
    const doc = vscode.window.activeTextEditor?.document;
    if (doc === undefined) {
        return;
    }

    const chartBasePath = utils.getChartBasePath(doc.fileName);
    if (chartBasePath === undefined) {
        return;
    }

    const templates = walkDirectory(chartBasePath + sep + 'templates');
    let hasErrors = false;
    for (const template of templates) {
        await vscode.workspace.openTextDocument(template).then(template => {
            if (LintCommand(collection, template)) {
                hasErrors = true;
            }
        });
    }

    if (hasErrors) {
        return;
    }
    vscode.window.showInformationMessage(`No errors found in chart '${utils.getNameOfChart(doc.fileName)}' :)`);
}
Example #14
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 #15
Source File: index.ts    From yfm-transform with MIT License 6 votes vote down vote up
function replaceImageSrc(
    token: Token,
    state: StateCore,
    {assetsPublicPath = sep, root = '', path: optsPath, log}: ImageOpts,
) {
    const src = token.attrGet('src') || '';
    const currentPath = state.env.path || optsPath;

    if (!isLocalUrl(src)) {
        return;
    }

    const path = resolveRelativePath(currentPath, src);

    if (isFileExists(path)) {
        state.md.assets?.push(path);
    } else {
        log.error(`Asset not found: ${bold(src)} in ${bold(currentPath)}`);
    }

    const relativeToRoot = path.replace(root + sep, '');
    const publicSrc = join(assetsPublicPath, relativeToRoot);

    token.attrSet('src', publicSrc);
}
Example #16
Source File: snapshots-utils.ts    From ui5-language-assistant with Apache License 2.0 6 votes vote down vote up
export function toSourcesTestDir(libTestDir: string): string {
  // replace TypeScript output dir (lib) with the corresponding sources (test) dir.
  return libTestDir.replace(sep + "lib", "");
}
Example #17
Source File: TenderlyApiService.ts    From hardhat-tenderly with GNU General Public License v3.0 6 votes vote down vote up
private static getTenderlyConfig(): TenderlyKeyConfig {
    const filepath = homedir() + sep + ".tenderly" + sep + "config.yaml";
    const fileData = fs.readFileSync(filepath);
    const yamlData: TenderlyKeyConfig = yaml.load(fileData.toString());

    if (yamlData.access_key == null) {
      throw new HardhatPluginError(
        PluginName,
        `Access token not provided at filepath ${filepath}.\n` +
          `You can find the token at ${TENDERLY_DASHBOARD_BASE_URL}/account/authorization`
      );
    }

    return yamlData;
  }
Example #18
Source File: LanguageManager.ts    From Asena with MIT License 6 votes vote down vote up
init(){
        const files = readdirSync(LanguageManager.LOCALE_PATH)
        if(!files.length) this.client.logger.error('Language files not found.')

        for(const file of files){
            if(!file.endsWith('.json')){
                this.client.logger.warning(`The language file named ${file} does not end with the '.json' file extension.`)
                continue
            }

            const language = require(`${LanguageManager.LOCALE_PATH}${sep}${file}`)
            this.client.logger.info(`Language loaded: ${Colors.LIGHT_PURPLE + language.full}`)

            const locale = new Language(language)
            LanguageManager.addLanguage(locale)

            if(this.client.version.compare(locale.version) === -1){
                if(locale.code === LanguageManager.DEFAULT_LANGUAGE){
                    this.client.logger.warning(`The default language (${LanguageManager.DEFAULT_LANGUAGE}) version is out of date. Please update the language version.`)
                    process.exit(1)
                }else{
                    this.client.logger.warning(`The ${language.full} language version is out of date. Missing keys will be provided from the default language.`)
                }
            }
        }

        if(!LanguageManager.languages.get(LanguageManager.DEFAULT_LANGUAGE)){
            this.client.logger.error(`Default language (${LanguageManager.DEFAULT_LANGUAGE}) could not be loaded.`)
            process.exit(1)
        }

        this.client.logger.info(`Total ${LanguageManager.languages.size} language successfully loaded!`)
    }
Example #19
Source File: collect.ts    From backstage with Apache License 2.0 5 votes vote down vote up
// This handles the support of TypeScript .d.ts config schema declarations.
// We collect all typescript schema definition and compile them all in one go.
// This is much faster than compiling them separately.
async function compileTsSchemas(paths: string[]) {
  if (paths.length === 0) {
    return [];
  }

  // Lazy loaded, because this brings up all of TypeScript and we don't
  // want that eagerly loaded in tests
  const { getProgramFromFiles, generateSchema } = await import(
    'typescript-json-schema'
  );

  const program = getProgramFromFiles(paths, {
    incremental: false,
    isolatedModules: true,
    lib: ['ES5'], // Skipping most libs speeds processing up a lot, we just need the primitive types anyway
    noEmit: true,
    noResolve: true,
    skipLibCheck: true, // Skipping lib checks speeds things up
    skipDefaultLibCheck: true,
    strict: true,
    typeRoots: [], // Do not include any additional types
    types: [],
  });

  const tsSchemas = paths.map(path => {
    let value;
    try {
      value = generateSchema(
        program,
        // All schemas should export a `Config` symbol
        'Config',
        // This enables the use of these tags in TSDoc comments
        {
          required: true,
          validationKeywords: ['visibility', 'deprecated'],
        },
        [path.split(sep).join('/')], // Unix paths are expected for all OSes here
      ) as JsonObject | null;
    } catch (error) {
      assertError(error);
      if (error.message !== 'type Config not found') {
        throw error;
      }
    }

    if (!value) {
      throw new Error(`Invalid schema in ${path}, missing Config export`);
    }
    return { path, value };
  });

  return tsSchemas;
}
Example #20
Source File: externalHelpers.spec.ts    From elderjs with MIT License 5 votes vote down vote up
settings = {
  debug: {
    automagic: true,
  },
  srcDir: `.${sep}src${sep}`,
}
Example #21
Source File: collect.ts    From yfm-transform with MIT License 5 votes vote down vote up
collect = (input: string, options: Options) => {
    const {root, path: startPath, singlePage} = options;

    if (!singlePage) {
        return;
    }

    let result = input;

    /* Syntax "{% include [Text](_includes/file.md) %}" is parsed as link. Need to ignore errors */
    const needSkipLinkFn = (href: string) => href.includes(`_includes${sep}`);
    const transformLink = (href: string) => href;
    const md = new MarkdownIt().use(index, {...options, transformLink, needSkipLinkFn});
    const tokens = md.parse(result, {});

    let i = 0;
    while (i < tokens.length) {
        if (tokens[i].type === 'inline') {
            const childrenTokens = tokens[i].children || [];
            let j = 0;

            while (j < childrenTokens.length) {
                const isLinkOpenToken = childrenTokens[j].type === 'link_open';

                if (!isLinkOpenToken) {
                    j++;
                    continue;
                }

                const linkToken = childrenTokens[j];
                const href = getHrefTokenAttr(linkToken);

                const isIncludeLink = resolveRelativePath(startPath, href).includes(
                    `_includes${sep}`,
                );

                if (!href || !isLocalUrl(href) || isIncludeLink) {
                    j++;
                    continue;
                }

                const {pathname, hash} = url.parse(href);
                if (pathname) {
                    const isPageFile = PAGE_LINK_REGEXP.test(pathname);
                    if (isPageFile) {
                        const newHref = getSinglePageAnchorId({
                            root,
                            currentPath: startPath,
                            pathname,
                            hash,
                        });
                        result = replaceLinkHref(result, href, newHref);
                    }
                } else if (hash) {
                    const newHref = getSinglePageAnchorId({root, currentPath: startPath, hash});
                    result = replaceLinkHref(result, href, newHref);
                }

                j++;
            }
        }

        i++;
    }

    // eslint-disable-next-line consistent-return
    return result;
}
Example #22
Source File: path.ts    From yfm-docs with MIT License 5 votes vote down vote up
export function addSlashPrefix(path: string): string {
    const slashPrefix = path.startsWith(sep) ? '' : sep;

    return `${slashPrefix}${path}`;
}
Example #23
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 #24
Source File: rollupPlugin.ts    From elderjs with MIT License 5 votes vote down vote up
// allows for injection of the cache and future sharing with esbuild
export function resolveFn(importee, importer) {
  // build list of dependencies so we know what CSS to inject into the export.

  logDependency(importee, importer);
  // below largely adapted from the rollup svelte plugin
  // ----------------------------------------------

  if (!importer || importee[0] === '.' || importee[0] === '\0' || path.isAbsolute(importee)) return null;
  // if this is a bare import, see if there's a valid pkg.svelte
  const parts = importee.split('/');

  let dir;
  let pkg;
  let name = parts.shift();
  if (name[0] === '@') {
    name += `/${parts.shift()}`;
  }

  try {
    const file = `.${path.sep}${['node_modules', name, 'package.json'].join(path.sep)}`;
    const resolved = path.resolve(process.cwd(), file);
    dir = path.dirname(resolved);
    // eslint-disable-next-line import/no-dynamic-require
    pkg = require(resolved);
  } catch (err) {
    if (err.code === 'MODULE_NOT_FOUND') {
      if (err.message && name !== 'svelte') console.log(err);
      return null;
    }
    throw err;
  }

  // use pkg.svelte
  if (parts.length === 0 && pkg.svelte) {
    const svelteResolve = path.resolve(dir, pkg.svelte);
    // console.log('-----------------', svelteResolve, name);
    logDependency(svelteResolve, name);
    return svelteResolve;
  }
  return null;
}
Example #25
Source File: change-project.tsx    From uivonim with GNU Affero General Public License v3.0 5 votes vote down vote up
state.inputCallbacks = {
  select: () => {
    vimFocus()
    if (!state.paths.length) {
      assignStateAndRender(resetState)
      return
    }
    const { name } = state.paths[state.index]
    if (!name) return
    const dirpath = join(state.path, name)
    state.create ? createVim(name, dirpath) : api.nvim.cmd(`cd ${dirpath}`)
    assignStateAndRender(resetState)
  },

  change: (value: string) =>
    assignStateAndRender({
      value,
      index: 0,
      paths: value
        ? filterDirs(filter(state.paths, value, { key: 'name' }))
        : state.cache,
    }),

  tab: () => {
    if (!state.paths.length) {
      assignStateAndRender(resetState)
      return
    }
    const { name } = state.paths[state.index]
    if (!name) return
    const path = join(state.path, name)
    getDirFiles(path).then((paths) => show({ path, paths: filterDirs(paths) }))
  },

  jumpNext: () => {
    const { name, dir } = state.paths[state.index]
    if (!dir) return
    const path = join(state.path, name)
    getDirFiles(path).then((paths) => show({ path, paths: filterDirs(paths) }))
  },

  jumpPrev: () => {
    const next = state.path.split(sep)
    next.pop()
    const path = join(sep, ...next)
    getDirFiles(path).then((paths) => show({ path, paths: filterDirs(paths) }))
  },

  // TODO: be more precise than this? also depends on scaled devices
  down: () => {
    listElRef.scrollTop += 300
    assignStateAndRender({
      index: Math.min(state.index + 17, state.paths.length - 1),
    })
  },

  up: () => {
    listElRef.scrollTop -= 300
    assignStateAndRender({ index: Math.max(state.index - 17, 0) })
  },

  top: () => {
    listElRef.scrollTop = 0
  },
  bottom: () => {
    listElRef.scrollTop = listElRef.scrollHeight
  },
  hide: () => (vimFocus(), assignStateAndRender(resetState)),
  next: () =>
    assignStateAndRender({
      index: state.index + 1 >= state.paths.length ? 0 : state.index + 1,
    }),
  prev: () =>
    assignStateAndRender({
      index: state.index - 1 < 0 ? state.paths.length - 1 : state.index - 1,
    }),
}
Example #26
Source File: Tenderly.ts    From hardhat-tenderly with GNU General Public License v3.0 5 votes vote down vote up
public async persistArtifacts(...contracts) {
    if (contracts.length === 0) {
      return;
    }

    const sourcePaths = await this.env.run("compile:solidity:get-source-paths");
    const sourceNames = await this.env.run(
      "compile:solidity:get-source-names",
      { sourcePaths }
    );
    const data = await this.env.run("compile:solidity:get-dependency-graph", {
      sourceNames
    });

    let contract: ContractByName;

    data._resolvedFiles.forEach((resolvedFile, _) => {
      const sourcePath: string = resolvedFile.sourceName;
      const name = sourcePath
        .split("/")
        .slice(-1)[0]
        .split(".")[0];

      for (contract of contracts) {
        if (contract.name === name) {
          const network =
            this.env.hardhatArguments.network !== "hardhat"
              ? this.env.hardhatArguments.network || contract.network
              : contract.network;
          if (network === undefined) {
            console.log(
              `Error in ${PluginName}: Please provide a network via the hardhat --network argument or directly in the contract`
            );
            continue;
          }
          let chainID: string = NetworkMap[network!.toLowerCase()];
          if (this.env.config.networks[network!].chainId !== undefined) {
            chainID = this.env.config.networks[network!].chainId!.toString();
          }

          if (chainID == undefined) {
            chainID = DefaultChainId;
          }
          const destPath = `deployments${sep}${network!.toLowerCase()}_${chainID}${sep}`;
          const contractDataPath = `${this.env.config.paths.artifacts}${sep}${sourcePath}${sep}${name}.json`;
          const contractData = JSON.parse(
            fs.readFileSync(contractDataPath).toString()
          );

          const metadata: Metadata = {
            compiler: {
              version: this.env.config.solidity.compilers[0].version
            },
            sources: {
              [sourcePath]: {
                content: resolvedFile.content.rawContent
              }
            }
          };

          const visited: Record<string, boolean> = {};

          resolveDependencies(data, sourcePath, metadata, visited);

          const artifact: TenderlyArtifact = {
            metadata: JSON.stringify(metadata),
            address: contract.address,
            bytecode: contractData.bytecode,
            deployedBytecode: contractData.deployedBytecode,
            abi: contractData.abi
          };

          fs.outputFileSync(
            `${destPath}${name}.json`,
            JSON.stringify(artifact)
          );
        }
      }
    });
  }
Example #27
Source File: index.ts    From web with MIT License 5 votes vote down vote up
coverageBaseDir = process.cwd().split(sep).join('/')
Example #28
Source File: action.ts    From jest-github-action with MIT License 5 votes vote down vote up
export async function run() {
  let workingDirectory = core.getInput("working-directory", { required: false })
  let cwd = workingDirectory ? resolve(workingDirectory) : process.cwd()
  const CWD = cwd + sep
  const RESULTS_FILE = join(CWD, "jest.results.json")

  try {
    const token = process.env.GITHUB_TOKEN
    if (token === undefined) {
      core.error("GITHUB_TOKEN not set.")
      core.setFailed("GITHUB_TOKEN not set.")
      return
    }

    const cmd = getJestCommand(RESULTS_FILE)

    await execJest(cmd, CWD)

    // octokit
    const octokit = new GitHub(token)

    // Parse results
    const results = parseResults(RESULTS_FILE)

    // Checks
    const checkPayload = getCheckPayload(results, CWD)
    await octokit.checks.create(checkPayload)

    // Coverage comments
    if (getPullId() && shouldCommentCoverage()) {
      const comment = getCoverageTable(results, CWD)
      if (comment) {
        await deletePreviousComments(octokit)
        const commentPayload = getCommentPayload(comment)
        await octokit.issues.createComment(commentPayload)
      }
    }

    if (!results.success) {
      core.setFailed("Some jest tests failed.")
    }
  } catch (error) {
    console.error(error)
    core.setFailed(error.message)
  }
}
Example #29
Source File: client.ts    From devoirs with MIT License 5 votes vote down vote up
async start(): Promise<void> {
    const assetsDirectory = await this.resourceResolver.resolve('assets');
    const page = await this.chromiumLauncher.launch(
      format(
        'file:///%s',
        [...assetsDirectory.split(sep).map(encode), 'index.html'].join('/')
      )
    );

    for (const c of await this.apiClient.getClasses()) {
      const assignments = (await this.apiClient.getAssignments(c.id))
        .sort(compare)
        .map(transform);

      await page.evaluate(
        (c: Class, assignments: (Assignment & { isOverdue: boolean })[]) => {
          const $classes = document.getElementById('classes');
          const $class = document.createElement('li');
          const $name = document.createElement('span');
          const $assignments = document.createElement('ul');

          for (const a of assignments) {
            const $assignment = document.createElement('li');

            $assignment.textContent = a.displayName;
            $assignment.setAttribute('data-due-datetime', a.dueDateTime);
            $assignment.setAttribute('data-overdue', a.isOverdue ? '1' : '0');
            $assignment.setAttribute(
              'data-completed',
              a.isCompleted ? '1' : '0'
            );

            $assignments.appendChild($assignment);
          }

          $name.textContent = c.name;
          $name.addEventListener('click', () => {
            $class.classList.toggle('is-hidden');
          });

          $class.appendChild($name);
          $class.appendChild($assignments);
          $classes.appendChild($class);
        },
        (c as unknown) as JSONObject,
        (assignments as unknown) as JSONObject
      );
    }
  }