Skip to content

Commit

Permalink
Check for leading newlines when determining if block indentation indi…
Browse files Browse the repository at this point in the history
…cator is needed (#404)

* Check for leading newlines when determining if block indentation indicator is needed

Fixes #403

* Perf: Swap order of checks for block indentation edge case
  • Loading branch information
trevorr authored and Vitaly Puzrin committed Mar 16, 2018
1 parent bb7f0cf commit bab69b5
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/js-yaml/dumper.js
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,12 @@ function isPlainSafeFirst(c) {
&& c !== CHAR_GRAVE_ACCENT;
}

// Determines whether block indentation indicator is required.
function needIndentIndicator(string) {
var leadingSpaceRe = /^\n* /;
return leadingSpaceRe.test(string);
}

var STYLE_PLAIN = 1,
STYLE_SINGLE = 2,
STYLE_LITERAL = 3,
Expand Down Expand Up @@ -301,7 +307,7 @@ function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, te
? STYLE_PLAIN : STYLE_SINGLE;
}
// Edge case: block indentation indicator can only have one digit.
if (string[0] === ' ' && indentPerLevel > 9) {
if (indentPerLevel > 9 && needIndentIndicator(string)) {
return STYLE_DOUBLE;
}
// At this point we know block styles are valid.
Expand Down Expand Up @@ -365,7 +371,7 @@ function writeScalar(state, string, level, iskey) {

// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
function blockHeader(string, indentPerLevel) {
var indentIndicator = (string[0] === ' ') ? String(indentPerLevel) : '';
var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';

// note the special case: the string '\n' counts as a "trailing" empty line.
var clip = string[string.length - 1] === '\n';
Expand Down
22 changes: 22 additions & 0 deletions test/issues/0403.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'use strict';


var assert = require('assert');
var yaml = require('../../');


test('should properly dump leading newlines and spaces', function () {
var dump, src;

src = { str: '\n a\nb' };
dump = yaml.dump(src);
assert.deepEqual(yaml.safeLoad(dump), src);

src = { str: '\n\n a\nb' };
dump = yaml.dump(src);
assert.deepEqual(yaml.safeLoad(dump), src);

src = { str: '\n a\nb' };
dump = yaml.dump(src, { indent: 10 });
assert.deepEqual(yaml.safeLoad(dump), src);
});

0 comments on commit bab69b5

Please sign in to comment.