当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript js-yaml.safeLoad函数代码示例

本文整理汇总了TypeScript中js-yaml.safeLoad函数的典型用法代码示例。如果您正苦于以下问题:TypeScript safeLoad函数的具体用法?TypeScript safeLoad怎么用?TypeScript safeLoad使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了safeLoad函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: async

 packed: async(context) => {
   expect(safeLoad(await readFile(path.join(context.getResources(Platform.WINDOWS, Arch.ia32), "app-update.yml"), "utf-8"))).toMatchSnapshot()
   const updateInfo = safeLoad(await readFile(path.join(context.outDir, "latest.yml"), "utf-8"))
   expect(updateInfo.sha2).not.toEqual("")
   expect(updateInfo.releaseDate).not.toEqual("")
   delete updateInfo.sha2
   delete updateInfo.releaseDate
   expect(updateInfo).toMatchSnapshot()
   await doTest(context.outDir, false)
 },
开发者ID:mbrainiac,项目名称:electron-builder,代码行数:10,代码来源:nsisTest.ts

示例2: async

      onLoading: async (conf:KeypairConfDTO, program:any, logger:any, confDAL:any) => {

        if ((program.keyN || program.keyr || program.keyp) && !(program.salt && program.passwd)) {
          throw Error('Missing --salt and --passwd options along with --keyN|keyr|keyp option');
        }

        // If we have salt and password, convert it to keypair
        if (program.salt || program.passwd) {
          const salt = program.salt || '';
          const key  = program.passwd || '';
          conf.pair = await Scrypt(salt, key);
        }

        // If no keypair has been loaded, try the default .yml file
        if (!conf.pair || !conf.pair.pub || !conf.pair.sec) {
          const ymlContent = await confDAL.coreFS.read('keyring.yml')
          conf.pair = yaml.safeLoad(ymlContent);
        }

        // If no keypair has been loaded or derived from salt/key, generate a random one
        if (!conf.pair || !conf.pair.pub || !conf.pair.sec) {
          conf.pair = randomKey().json()
        }

        // With the --keyprompt option, temporarily use a keypair given from CLI prompt (it won't be stored)
        if (program.keyprompt) {
          // Backup of the current pair
          conf.oldPair = {
            pub: conf.pair.pub,
            sec: conf.pair.sec
          };
          // Ask the for the session key
          await promptKey(conf, program);
        }

        // With the --keyfile option, temporarily use a keypair given from file system (content won't be stored)
        if (program.keyfile) {
          // Backup of the current pair
          conf.oldPair = {
            pub: conf.pair.pub,
            sec: conf.pair.sec
          };
          // Load file content
          const doc = yaml.safeLoad(fs.readFileSync(program.keyfile, 'utf8'));
          if (!doc || !doc.pub || !doc.sec) {
            throw 'Could not load full keyring from file';
          }
          conf.pair = {
            pub: doc.pub,
            sec: doc.sec
          }
        }

      },
开发者ID:duniter,项目名称:duniter,代码行数:54,代码来源:index.ts

示例3: async

 packed: async(context) => {
   assertThat(safeLoad(await readFile(path.join(context.getResources(Platform.WINDOWS, Arch.ia32), "app-update.yml"), "utf-8"))).hasProperties({
         provider: "generic",
         url: "https://develar.s3.amazonaws.com/test",
       })
   const updateInfo = safeLoad(await readFile(path.join(context.outDir, "latest.yml"), "utf-8"))
   assertThat(updateInfo).hasProperties({
         version: "1.1.0",
         path: "TestApp Setup 1.1.0.exe",
       })
   assertThat(updateInfo.sha2).isNotEmpty()
   await doTest(context.outDir, false)
 },
开发者ID:Icenium,项目名称:electron-builder,代码行数:13,代码来源:nsisTest.ts

示例4: play

export function play(monogatari: string, options: PlayOptions) {

  if (!fs.existsSync(options.hostsfile)) {
    log.error('play', `${options.hostsfile} does not exists`);
    process.exit(1);
  }

  const cwd: string = process.cwd();
  monogatari = path.resolve(cwd, 'monogatari', monogatari);
  const hostsfile  = path.resolve(cwd, options.hostsfile);

  const hosts       = yaml.safeLoad(fs.readFileSync(hostsfile, 'utf8'))[0];
  const monogataris = yaml.safeLoad(fs.readFileSync(monogatari, 'utf8'))[0];

  console.log(hosts);
  console.log(monogataris);

  //TODO: update .d.ts of ssh2 and send PR
  const client = new Connection();

  client.on('ready', () => {
    log.info('play', 'connected');

    client.exec(monogataris.tasks[0].shell, (err, stream) => {
      if(err) {
        throw err;
      }

      stream.on('close', (code, signal) => {
        log.info('play', `end code:${code}, signal:${signal}`);
        client.end();
      })
      .on('data', data => {
        log.info('play', data);
      })
      .stderr.on('data', data => {
        log.error('play', data);
      });

    });
  })
  .connect({
    host: hosts[monogataris.hosts].host,
    port: hosts[monogataris.hosts].port,
    username: hosts[monogataris.hosts].user,
    privateKey: fs.readFileSync(options.privateKey)
  });
}
开发者ID:waffle-iron,项目名称:shikibu,代码行数:48,代码来源:play.ts

示例5: sortKey

    objectToCompare[platform.buildConfigurationKey] = await BluebirdPromise.map((artifacts.get(platform) || []).sort((a, b) => sortKey(a).localeCompare(sortKey(b))), async it => {
      const result: any = {...it}
      if (result.file != null) {
        if (result.file.endsWith(".yml")) {
          const fileContent = safeLoad(await readFile(result.file, "utf-8"))
          delete fileContent.sha2
          delete fileContent.sha512
          delete fileContent.releaseDate
          result.fileContent = fileContent
        }
        result.file = path.basename(result.file)
      }

      // reduce snapshot - avoid noise
      if (result.safeArtifactName == null) {
        delete result.safeArtifactName
      }
      if (result.arch == null) {
        delete result.arch
      }
      else {
        result.arch = Arch[result.arch]
      }

      delete result.packager
      delete result.target
      delete result.publishConfig
      return result
    })
开发者ID:yuya-oc,项目名称:electron-builder,代码行数:29,代码来源:packTester.ts

示例6: load

export default function load() {
	const config = yaml.safeLoad(fs.readFileSync(path, 'utf-8')) as Source;

	const mixin = {} as Mixin;

	// Validate URLs
	if (!isUrl(config.url)) throw `url="${config.url}" is not a valid URL`;

	const url = new URL(config.url);
	config.url = normalizeUrl(config.url);

	mixin.host = url.host;
	mixin.hostname = url.hostname;
	mixin.scheme = url.protocol.replace(/:$/, '');
	mixin.ws_scheme = mixin.scheme.replace('http', 'ws');
	mixin.ws_url = `${mixin.ws_scheme}://${mixin.host}`;
	mixin.api_url = `${mixin.scheme}://${mixin.host}/api`;
	mixin.auth_url = `${mixin.scheme}://${mixin.host}/auth`;
	mixin.dev_url = `${mixin.scheme}://${mixin.host}/dev`;
	mixin.docs_url = `${mixin.scheme}://${mixin.host}/docs`;
	mixin.stats_url = `${mixin.scheme}://${mixin.host}/stats`;
	mixin.status_url = `${mixin.scheme}://${mixin.host}/status`;
	mixin.drive_url = `${mixin.scheme}://${mixin.host}/files`;

	if (config.localDriveCapacityMb == null) config.localDriveCapacityMb = 256;
	if (config.remoteDriveCapacityMb == null) config.remoteDriveCapacityMb = 8;

	if (config.name == null) config.name = 'Misskey';

	return Object.assign(config, mixin);
}
开发者ID:ha-dai,项目名称:Misskey,代码行数:31,代码来源:load.ts

示例7: addPluginFile

 addPluginFile(filePath : string, callback: any) :void {
     var data = yaml.safeLoad(fs.readFileSync(filePath, 'utf8'));
     this.extractTasteeCode(data);
     if (callback) {
         return callback();
     }
 }
开发者ID:tastee,项目名称:tastee-core,代码行数:7,代码来源:tastee-analyser.ts

示例8: getLicenseButtons

export async function getLicenseButtons(licenseButtonFiles: Array<LicenseButtonsFile>, langWithRegion: string, id: number, name: string) {
  let data = getDefaultButtons(langWithRegion, id, name)

  for (const item of licenseButtonFiles) {
    if (item.langWithRegion !== langWithRegion) {
      continue
    }

    try {
      const fileData = safeLoad(await readFile(item.file, "utf-8")) as any
      const buttonsStr = labelToHex(fileData.lang, item.lang, item.langWithRegion) +
        labelToHex(fileData.agree, item.lang, item.langWithRegion) +
        labelToHex(fileData.disagree, item.lang, item.langWithRegion) +
        labelToHex(fileData.print, item.lang, item.langWithRegion) +
        labelToHex(fileData.save, item.lang, item.langWithRegion) +
        labelToHex(fileData.description, item.lang, item.langWithRegion)

      data = `data 'STR#' (${id}, "${name}") {\n`
      data += serializeString("0006" + buttonsStr)
      data += `\n};`

      if (log.isDebugEnabled) {
        log.debug({lang: item.langName, data}, `overwriting license buttons`)
      }
      return data
    }
    catch (e) {
      log.debug({error: e}, "cannot overwrite license buttons")
      return data
    }
  }

  return data
}
开发者ID:electron-userland,项目名称:electron-builder,代码行数:34,代码来源:licenseButtons.ts

示例9: readConfigurationFile

export function readConfigurationFile(filepath: string): RawConfigFile {
    const resolvedConfigFileExt = path.extname(filepath);
    if (/\.(json|ya?ml)/.test(resolvedConfigFileExt)) {
        const fileContent = fs.readFileSync(filepath, "utf8").replace(/^\uFEFF/, "");
        try {
            if (resolvedConfigFileExt === ".json") {
                return JSON.parse(stripComments(fileContent)) as RawConfigFile;
            } else {
                return yaml.safeLoad(fileContent, {
                    // Note: yaml.LoadOptions expects a schema value of type "any",
                    // but this trips up the no-unsafe-any rule.
                    // tslint:disable-next-line:no-unsafe-any
                    schema: yaml.JSON_SCHEMA,
                    strict: true
                }) as RawConfigFile;
            }
        } catch (e) {
            const error = e as Error;
            // include the configuration file being parsed in the error since it may differ from the directly referenced config
            throw new Error(`${error.message} in ${filepath}`);
        }
    } else {
        const rawConfigFile = require(filepath) as RawConfigFile;
        // tslint:disable-next-line no-dynamic-delete
        delete (require.cache as { [key: string]: any })[filepath];
        return rawConfigFile;
    }
}
开发者ID:andy-ms,项目名称:tslint,代码行数:28,代码来源:configuration.ts

示例10: map

 map(content => {
     try {
         return YAML.safeLoad(content, {json: true, onWarning: noop} as any);
     } catch (err) {
         return new Error(err);
     }
 })
开发者ID:hmenager,项目名称:composer,代码行数:7,代码来源:data-gateway.service.ts

示例11: expect

		expect(() => {
			const charListYAML = yaml.safeLoad(
				readFileSync('character-list/character-list.yaml', 'utf8')
			);
			expect(charListYAML.icons).to.have.length(iconCount);
			expect(charListYAML.icons[0]).to.have.all.keys(['id', 'unicode']);
		}).to.not.throw(Error);
开发者ID:gluons,项目名称:material-design-icon-chars,代码行数:7,代码来源:charList.test.ts

示例12: byConfigYaml

        function byConfigYaml() {
            let catalogYaml = jsyaml.safeLoad(fs.readFileSync(path.resolve(process.cwd(), "catalog.yml"), "utf8"));

            let configRaw: ConfigRaw = {
                builders: [target2builder(target) !],
                book: catalogYaml
            };

            return start(review => {
                review.initConfig(configRaw);
            }, {
                    reviewfile: reviewfile,
                    base: root.parsedOpts.base[0]
                })
                .then(book => {
                    process.stdout.write("completed!\n");
                    book.reports.forEach(report => {
                        let log = (_msg: string) => { };
                        switch (report.level) {
                            case ReportLevel.Info:
                                log = process.stdout.write;
                            case ReportLevel.Warning:
                                log = process.stderr.write;
                            case ReportLevel.Error:
                                log = process.stderr.write;
                        }
                        let message = "";
                        report.nodes.forEach(node => {
                            message += `[${node.location.start.line}, ${node.location.start.column}] `;
                        });
                        message += report.message + "\n";
                        log(message);
                    });
                });
        }
开发者ID:vvakame,项目名称:review.js,代码行数:35,代码来源:cli.ts

示例13: readDefinition

export async function readDefinition(
  filePath: string,
  args: Args,
  out: IOutput = new Output(),
  envVars?: any,
): Promise<{ definition: PrismaDefinition; rawJson: any }> {
  if (!fs.pathExistsSync(filePath)) {
    throw new Error(`${filePath} could not be found.`)
  }
  const file = fs.readFileSync(filePath, 'utf-8')
  const json = yaml.safeLoad(file) as PrismaDefinition
  // we need this copy because populateJson runs inplace
  const jsonCopy = { ...json }

  const vars = new Variables(filePath, args, out, envVars)
  const populatedJson = await vars.populateJson(json)
  if (populatedJson.custom) {
    delete populatedJson.custom
  }
  const valid = validate(populatedJson)
  // TODO activate as soon as the backend sends valid yaml
  if (!valid) {
    debugger
    let errorMessage =
      `Invalid prisma.yml file` + '\n' + printErrors(validate.errors!)
    throw new Error(errorMessage)
  }

  cache[file] = populatedJson
  return {
    definition: populatedJson,
    rawJson: jsonCopy,
  }
}
开发者ID:nunsie,项目名称:prisma,代码行数:34,代码来源:yaml.ts

示例14: while

    return connection.getCombinedConfig(imageDigestComposeFile).then(output => {
        var removeBuildOptions = tl.getBoolInput("removeBuildOptions");
        if (removeBuildOptions) {
            var doc = yaml.safeLoad(output);
            for (var serviceName in doc.services || {}) {
                delete doc.services[serviceName].build;
            }
            output = yaml.safeDump(doc, {lineWidth: -1} as any);
        }

        var baseResolveDir = tl.getPathInput("baseResolveDirectory");
        if (baseResolveDir) {
            // This just searches the output string and replaces all
            // occurrences of the base resolve directory. This isn't
            // precisely accurate but is a good enough solution.
            var replaced = output;
            do {
                output = replaced;
                replaced = output.replace(baseResolveDir, ".");
            } while (replaced !== output);
        }

        var outputDockerComposeFile = tl.getPathInput("outputDockerComposeFile", true);

        fs.writeFileSync(outputDockerComposeFile, output);
    });
开发者ID:DarqueWarrior,项目名称:vsts-tasks,代码行数:26,代码来源:dockercomposeconfig.ts

示例15: await

  .action(async (opts, args) => {
    // TODO Delete '--stdin' option.
    if (opts.stdin) {
      console.warn("'--stdin' option is deprecated.");
    }
    if (args.input_filename && opts.stdin) {
      process.stderr.write("Invalid parameters!\n");
      process.exit(1);
      return;
    }

    const outputFilename = opts.output[0];
    const namespace = opts.namespace[0];
    const withQuery = opts.withQuery;
    const sortProps = opts.sortProps;

    const input = await (args.input_filename ? fromFile(args.input_filename) : fromStdin());
    const model = await convert(YAML.safeLoad(input), { namespace, withQuery, sortProps });

    if (outputFilename) {
      fs.writeFileSync(outputFilename, model);
    } else {
      process.stdout.write(model);
    }
    process.exit(0);
  });
开发者ID:mstssk,项目名称:sw2dts,代码行数:26,代码来源:cli.ts


注:本文中的js-yaml.safeLoad函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。