From 4d02b86805b196d6f064bcfed3fc1475244fe93d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ABl=20Nison?= Date: Sun, 19 May 2019 21:57:34 +0200 Subject: [PATCH] Supports more cases --- packages/berry-parsers/sources/syml.ts | 45 ++++++++++++++----- .../sources/commands/npm/whoami.ts | 3 +- 2 files changed, 35 insertions(+), 13 deletions(-) diff --git a/packages/berry-parsers/sources/syml.ts b/packages/berry-parsers/sources/syml.ts index bef0b86b64d..5972034e7bb 100644 --- a/packages/berry-parsers/sources/syml.ts +++ b/packages/berry-parsers/sources/syml.ts @@ -1,7 +1,7 @@ // @ts-ignore -import {load} from 'js-yaml'; +import {safeLoad} from 'js-yaml'; -import {parse} from './grammars/syml'; +import {parse} from './grammars/syml'; const simpleStringPattern = /^(?![-?:,\][{}#&*!|>'"%@` \t\r\n]).([ \t]*(?![,\][{}:# \t\r\n]).)*$/; @@ -84,19 +84,42 @@ function stringifyValue(value: any, indentLevel: number): string { } export function stringifySyml(value: any) { - return stringifyValue(value, 0); -} - -export function parseSyml(source: string) { try { - try { - return load(source) as {[key: string]: any}; - } catch (error) { - return parse(source.endsWith(`\n`) ? source : `${source}\n`); - } + return stringifyValue(value, 0); } catch (error) { if (error.location) error.message = error.message.replace(/(\.)?$/, ` (line ${error.location.start.line}, column ${error.location.start.column})$1`); throw error; } } + +function parseViaPeg(source: string) { + if (!source.endsWith(`\n`)) + source += `\n`; + + return parse(source); +} + +function parseViaJsYaml(source: string) { + let value; + + try { + value = safeLoad(source); + } catch (error) { + return parseViaPeg(source); + } + + // Empty files are parsed as `null` instead of an empty object + if (value === null) + return {} as {[key: string]: string}; + + // Files that contain single invalid line are treated as a raw string + if (typeof value === `string`) + return parseViaPeg(source); + + return value as {[key: string]: string}; +} + +export function parseSyml(source: string) { + return parseViaJsYaml(source); +} diff --git a/packages/plugin-npm-cli/sources/commands/npm/whoami.ts b/packages/plugin-npm-cli/sources/commands/npm/whoami.ts index 4138646b871..902924b5729 100644 --- a/packages/plugin-npm-cli/sources/commands/npm/whoami.ts +++ b/packages/plugin-npm-cli/sources/commands/npm/whoami.ts @@ -34,9 +34,8 @@ export default (clipanion: Clipanion, pluginConfiguration: PluginConfiguration) const report = await StreamReport.start({configuration, stdout}, async report => { let ident: Ident | null = null; - if (scope) { + if (scope) ident = structUtils.makeIdent(scope, ``); - } try { const response = await npmHttpUtils.get(`/-/whoami`, { configuration, ident, authType: npmHttpUtils.AuthType.ALWAYS_AUTH, json: true });