js-yaml#dump TypeScript Examples

The following examples show how to use js-yaml#dump. 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: SchemaExplorer.tsx    From json-schema-viewer with Apache License 2.0 6 votes vote down vote up
SchemaExplorerExample: React.FC<SchemaExplorerExampleProps> = props => {
  const potentialExample = generateJsonExampleFor(props.schema, props.lookup, props.stage);

  if (isExample(potentialExample)) {
    const renderedOutput = props.format === 'json' ? JSON.stringify(potentialExample.value, null, 2) : dump(potentialExample.value);
    return (
      <FullWidth>
        <CodeBlockWithCopy text={renderedOutput} language={props.format} />
      </FullWidth>
    );
  }

  const messages = new Set(potentialExample.errors.map(e => e.message));

  return (
    <div>
      <ErrorHeading>An example could not be generated.</ErrorHeading>
      <Expand onOpen="(Collapse advanced view)" onClosed="(Expand advanced view)">
        <div>
          This example could not be automatically generated because:
          <ul>
            {Array.from(messages.values()).map(m => <li key={m}>{m}</li>)}
          </ul>
          For more information please download the JSON Schema.
        </div>
      </Expand>
    </div>
  );
}
Example #2
Source File: plugin.ts    From lift with MIT License 6 votes vote down vote up
private async eject() {
        getUtils().log("Ejecting from Lift to CloudFormation");
        getUtils().log();
        await this.serverless.pluginManager.spawn("package");
        const legacyProvider = this.serverless.getProvider("aws");
        const compiledTemplateFileName = legacyProvider.naming.getCompiledTemplateFileName();
        const compiledTemplateFilePath = path.join(this.serverless.serviceDir, ".serverless", compiledTemplateFileName);
        const cfTemplate = readFileSync(compiledTemplateFilePath);
        const formattedYaml = dump(JSON.parse(cfTemplate.toString()));
        getUtils().writeText(formattedYaml);
        getUtils().log("You can also find that CloudFormation template in the following file:");
        getUtils().log(compiledTemplateFilePath);
    }
Example #3
Source File: utils.ts    From obsidian-linter with MIT License 6 votes vote down vote up
export function escapeYamlString(str: string): string {
  return dump(str, {lineWidth: -1}).slice(0, -1);
}
Example #4
Source File: processServiceFiles.ts    From yfm-docs with MIT License 6 votes vote down vote up
function saveFilteredPresets(path: string, parsedPreset: DocPreset): void {
    const {output: outputFolderPath, varsPreset = ''} = ArgvService.getConfig();

    const outputPath = resolve(outputFolderPath, path);
    const filteredPreset: Record<string, Object> = {
        default: parsedPreset.default,
    };

    if (parsedPreset[varsPreset]) {
        filteredPreset[varsPreset] = parsedPreset[varsPreset];
    }

    const outputPreset = dump(filteredPreset, {
        lineWidth: 120,
    });

    shell.mkdir('-p', dirname(outputPath));
    writeFileSync(outputPath, outputPreset);
}
Example #5
Source File: formDataToInfraEnvField.ts    From assisted-ui-lib with Apache License 2.0 5 votes vote down vote up
toYamlWithComments = (json: object, comments: string[]) => {
  const yamlComments = comments.map((comment) => `${YAML_COMMENT_CHAR}${comment}`);
  return `${yamlComments.join('\n')}\n${dump(json)}`;
}
Example #6
Source File: nmstateYaml.ts    From assisted-ui-lib with Apache License 2.0 5 votes vote down vote up
toYamlWithComments = (json: object, comments: string[]) => {
  const yamlComments = comments.map((comment) => `${YAML_COMMENT_CHAR}${comment}`);
  return `${yamlComments.join('\n')}\n${dump(json)}`;
}
Example #7
Source File: leading.ts    From yfm-docs with MIT License 5 votes vote down vote up
function filterFile(path: string) {
    const {
        input: inputFolderPath,
    } = ArgvService.getConfig();

    const pathToDir = dirname(path);
    const filePath = resolve(inputFolderPath, path);
    const content = readFileSync(filePath, 'utf8');
    const parsedIndex = load(content) as LeadingPage;

    const {vars} = ArgvService.getConfig();
    const combinedVars = {
        ...PresetService.get(pathToDir),
        ...vars,
    };

    /* Should remove all links with false expressions */
    try {
        parsedIndex.title = firstFilterTextItems(
            parsedIndex.title,
            combinedVars,
            {resolveConditions: true},
        );

        parsedIndex.description = filterTextItems(
            parsedIndex.description,
            combinedVars,
            {resolveConditions: true},
        );

        if (parsedIndex.meta?.title) {
            parsedIndex.meta.title = firstFilterTextItems(
                parsedIndex.meta.title,
                combinedVars,
                {resolveConditions: true},
            );
        }

        if (parsedIndex.nav) {
            parsedIndex.nav.title = firstFilterTextItems(
                parsedIndex.nav.title,
                combinedVars,
                {resolveConditions: true},
            );
        }

        parsedIndex.links = filterFiles(parsedIndex.links, 'links', combinedVars, {resolveConditions: true});
        writeFileSync(filePath, dump(parsedIndex));
    } catch (error) {
        log.error(`Error while filtering index file: ${path}. Error message: ${error}`);
    }
}
Example #8
Source File: generate-tasks.ts    From blake3 with MIT License 4 votes vote down vote up
(async () => {
  const res = await fetch('https://nodejs.org/dist/index.json');
  if (!res.ok) {
    throw new Error(`${res.status} error from Node.js releases page`);
  }

  const releases: { version: string; modules: string }[] = await res.json();
  const buildVersion = new Map<number, string>();
  const versionMap: { [key: string]: number } = {};
  for (const release of releases) {
    const moduleVersion = Number(release.modules);
    if (!moduleVersion || moduleVersion < minVersion) {
      break;
    }

    versionMap[release.version] = Number(moduleVersion);
    if (buildVersion.has(moduleVersion)) {
      continue;
    }

    buildVersion.set(moduleVersion, release.version);
  }

  const buildYaml = {
    name: 'Generate Binaries',
    on: {
      push: {
        branches: ['generate-binary'],
      },
    },
    jobs: {
      build: {
        name: 'Build',
        'runs-on': '${{ matrix.os }}',
        strategy: {
          matrix: { os: ['macos-latest', 'ubuntu-latest', 'windows-latest'] },
        },
        steps: [
          { uses: 'actions/checkout@master' },
          { run: 'mkdir dist' },
          {
            uses: 'actions-rs/toolchain@v1',
            with: { target: 'wasm32-unknown-unknown', toolchain: 'nightly' },
          },
          ...[...buildVersion.entries()]
            .map(([moduleVersion, nodeVersion], i) => [
              { uses: 'actions/setup-node@v1', with: { 'node-version': nodeVersion } },
              ...(parseVersion(nodeVersion).major >= 15
                ? [
                    {
                      // See: https://github.com/actions/setup-node/issues/68
                      shell: 'powershell',
                      name: 'use npm 6 on node 15',
                      run: 'npm install -g npm@6',
                      if: "matrix.os == 'windows-latest'",
                    },
                  ]
                : []),
              {
                // See: https://github.com/neon-bindings/neon/issues/589#issuecomment-735395787
                shell: 'powershell',
                name: 'patch node-gyp for VS 2019',
                run:
                  'npm install --global node-gyp@latest\r\nnpm prefix -g | % {npm config set node_gyp "$_\\node_modules\\node-gyp\\bin\\node-gyp.js"}',
                if: "matrix.os == 'windows-latest'",
              },
              i === 0
                ? { run: 'npm install neon-cli rimraf' }
                : { run: './node_modules/.bin/rimraf rs/native/target' },
              { run: '../node_modules/.bin/neon build --release', 'working-directory': 'rs' },
              { run: `mv rs/native/index.node dist/\${{ matrix.os }}-${moduleVersion}.node` },
            ])
            .reduce((acc, v) => [...acc, ...v], []),
          {
            uses: 'actions/upload-artifact@v1',
            with: { name: 'dist', path: 'dist' },
          },
        ],
      },
    },
  };

  writeFileSync(
    join(__dirname, '..', '..', '.github', 'workflows', 'build-neon.yml'),
    dump(buildYaml),
  );
  writeFileSync(join(__dirname, '..', '..', 'targets.json'), JSON.stringify(versionMap));
})();
Example #9
Source File: tocs.ts    From yfm-docs with MIT License 4 votes vote down vote up
function add(path: string) {
    const {
        input: inputFolderPath,
        output: outputFolderPath,
        outputFormat,
        ignoreStage,
        singlePage,
        vars,
        resolveConditions,
        applyPresets,
        removeHiddenTocItems,
    } = ArgvService.getConfig();

    const pathToDir = dirname(path);
    const content = readFileSync(resolve(inputFolderPath, path), 'utf8');
    const parsedToc = load(content) as YfmToc;

    // Should ignore toc with specified stage.
    if (parsedToc.stage === ignoreStage) {
        return;
    }

    const combinedVars = {
        ...PresetService.get(pathToDir),
        ...vars,
    };

    if (parsedToc.title) {
        parsedToc.title = firstFilterTextItems(
            parsedToc.title,
            combinedVars,
            {resolveConditions: true},
        );
    }

    /* Should make substitutions in title */
    if (applyPresets && typeof parsedToc.title === 'string') {
        parsedToc.title = _liquidSubstitutions(parsedToc.title, combinedVars, path);
    }

    /* Should resolve all includes */
    parsedToc.items = _replaceIncludes(
        parsedToc.items,
        join(inputFolderPath, pathToDir),
        resolve(inputFolderPath),
        combinedVars,
    );

    /* Should remove all links with false expressions */
    if (resolveConditions || removeHiddenTocItems) {
        try {
            parsedToc.items = filterFiles(parsedToc.items, 'items', combinedVars, {
                resolveConditions,
                removeHiddenTocItems,
            });
        } catch (error) {
            log.error(`Error while filtering toc file: ${path}. Error message: ${error}`);
        }
    }

    /* Store parsed toc for .md output format */
    storage.set(path, parsedToc);

    /* Store path to toc file to handle relative paths in navigation */
    parsedToc.base = pathToDir;

    if (outputFormat === 'md') {
        /* Should copy resolved and filtered toc to output folder */
        const outputPath = resolve(outputFolderPath, path);
        const outputToc = dump(parsedToc);
        shell.mkdir('-p', dirname(outputPath));
        writeFileSync(outputPath, outputToc);

        if (singlePage) {
            const parsedSinglePageToc = _cloneDeep(parsedToc);
            const currentPath = resolve(outputFolderPath, path);
            parsedSinglePageToc.items = filterFiles(parsedSinglePageToc.items, 'items', {}, {
                removeHiddenTocItems: true,
            });

            prepareTocForSinglePageMode(parsedSinglePageToc, {root: outputFolderPath, currentPath});

            const outputSinglePageDir = resolve(dirname(outputPath), SINGLE_PAGE_FOLDER);
            const outputSinglePageTocPath = resolve(outputSinglePageDir, 'toc.yaml');
            const outputSinglePageToc = dump(parsedSinglePageToc);

            shell.mkdir('-p', outputSinglePageDir);
            writeFileSync(outputSinglePageTocPath, outputSinglePageToc);
        }
    }

    prepareNavigationPaths(parsedToc, pathToDir);
}