Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A nicer CSON.stringify #9

Merged
merged 2 commits into from
Dec 3, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions lib/cson-safe.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
void function () {
var CS, CSON, csr, find, isLiteral, LiteralTypes, nodeTransforms, nodeTypeString, parse, stringify, syntaxErrorMessage, transformKey, transformNode;
csr = require('coffee-script-redux');
stringify = require('./stringify');
CS = csr.Nodes;
find = function (arr, testFn) {
var element;
Expand Down Expand Up @@ -206,9 +207,6 @@ void function () {
throw new SyntaxError(syntaxErrorMessage(csNode, 'Unexpected ' + nodeTypeString(csNode)));
return transform[1](csNode);
};
stringify = function (obj, visitor, indent) {
return JSON.stringify(obj, visitor, indent);
};
parse = function (source, reviver) {
var coffeeAst;
if (reviver)
Expand Down
125 changes: 125 additions & 0 deletions lib/stringify.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/*
Copyright (c) 2014, Groupon, Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

Neither the name of GROUPON nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// Generated by CoffeeScript 2.0.0-beta8
module.exports = function (obj, visitor, indent) {
var indentLine, indentLines, jsIdentifierRE, n, newlineWrap, serialize, tripleQuotesRE;
if (typeof obj === 'undefined' || typeof obj === 'function')
return;
indent = function () {
switch (typeof indent) {
case 'string':
return indent.slice(0, 10);
case 'number':
n = Math.min(indent, 10);
if (!in$(n, [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
]))
n = 0;
return Array(n + 1).join(' ');
default:
return 0;
}
}.call(this);
if (!indent)
return JSON.stringify(obj, visitor, indent);
indentLine = function (line) {
return indent + line;
};
indentLines = function (str) {
return str && str.split('\n').map(indentLine).join('\n');
};
newlineWrap = function (str) {
return str && '\n' + str + '\n';
};
jsIdentifierRE = /^[a-z_$][a-z0-9_$]*$/i;
tripleQuotesRE = new RegExp("'''", 'g');
obj = JSON.parse(JSON.stringify(obj, visitor));
return (serialize = function (obj) {
var array, key, keypairs, object, string, val;
switch (typeof obj) {
case 'boolean':
return obj + '';
case 'number':
if (isFinite(obj)) {
return obj + '';
} else {
return 'null';
}
case 'string':
if (obj.indexOf('\n') === -1) {
return JSON.stringify(obj);
} else {
string = obj.replace(tripleQuotesRE, "\\'''");
string = newlineWrap(indentLines(string));
return "'''" + string + "'''";
}
case 'object':
if (obj === null) {
return 'null';
} else if (Array.isArray(obj)) {
array = obj.map(serialize).join('\n');
array = newlineWrap(indentLines(array));
return '[' + array + ']';
} else {
keypairs = function (accum$) {
for (key in obj) {
val = obj[key];
if (!key.match(jsIdentifierRE))
key = JSON.stringify(key);
val = serialize(val);
accum$.push('' + key + ': ' + val);
}
return accum$;
}.call(this, []);
object = keypairs.join('\n');
object = newlineWrap(indentLines(object));
return '{' + object + '}';
}
}
})(obj);
};
function in$(member, list) {
for (var i = 0, length = list.length; i < length; ++i)
if (i in list && list[i] === member)
return true;
return false;
}
7 changes: 1 addition & 6 deletions src/cson-safe.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###

csr = require 'coffee-script-redux'
stringify = require './stringify'
CS = csr.Nodes

find = (arr, testFn) ->
Expand Down Expand Up @@ -128,12 +129,6 @@ transformNode = (csNode) ->

transform[1] csNode

stringify = (obj, visitor, indent) ->
# Since CSON is a superset of JSON, we can just use the JSON serialization
# There are multiple ways to express the same thing in CSON, so trying to
# make `CSON.stringify(CSON.parse(str)) == str` work is doomed to fail
JSON.stringify obj, visitor, indent

parse = (source, reviver) ->
if reviver
throw new Error "The reviver parameter is not implemented yet"
Expand Down
69 changes: 69 additions & 0 deletions src/stringify.coffee
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# There are multiple ways to express the same thing in CSON, so trying to
# make `CSON.stringify(CSON.parse(str)) == str` work is doomed to fail
# but we can at least make output look a lot nicer than JSON.stringify's.
module.exports = (obj, visitor, indent) ->
return undefined if typeof obj in ['undefined', 'function']

# pick an indent style much as JSON.stringify does, but limited to cson legals
indent = switch typeof indent
when 'string' then indent.slice 0, 10

when 'number'
n = Math.min indent, 10
n = 0 unless n in [1..10] # do not bail on NaN and similar
Array(n + 1).join ' '

else 0

return JSON.stringify obj, visitor, indent unless indent

indentLine = (line) -> indent + line

indentLines = (str) ->
str and str.split('\n').map(indentLine).join('\n')

newlineWrap = (str) ->
str and "\n#{ str }\n"

jsIdentifierRE = /^[a-z_$][a-z0-9_$]*$/i
tripleQuotesRE = new RegExp "'''", 'g' # some syntax hilighters hate on /'''/g

# have the native JSON serializer do visitor transforms & normalization for us
obj = JSON.parse JSON.stringify obj, visitor

do serialize = (obj) ->
switch typeof obj
when 'boolean' then obj + ''

when 'number'
if isFinite obj
obj + ''
else # NaN, Infinity and -Infinity
'null'

when 'string'
if obj.indexOf('\n') is -1
JSON.stringify obj
else
string = obj.replace tripleQuotesRE, "\\'''"
string = newlineWrap indentLines string
"'''#{ string }'''"

when 'object'
if obj is null
'null'

else if Array.isArray obj
array = obj.map(serialize).join '\n'
array = newlineWrap indentLines array
"[#{ array }]"

else
keypairs = for key, val of obj
key = JSON.stringify key unless key.match jsIdentifierRE
val = serialize val
"#{ key }: #{ val }"

object = keypairs.join '\n'
object = newlineWrap indentLines object
"{#{ object }}"
120 changes: 117 additions & 3 deletions test/stringify.coffee
Original file line number Diff line number Diff line change
@@ -1,8 +1,122 @@

assert = require 'assertive'
{ equal } = require 'assertive'

CSON = require '../'
cson = (obj, visitor, space = 2) -> CSON.stringify obj, visitor, space

describe 'CSON.stringify', ->
it 'works just like JSON.stringify', ->
assert.equal '{"a":"b"}', CSON.stringify(a: 'b')
it 'handles null', ->
equal 'null', cson null

it 'handles boolean values', ->
equal 'true', cson true
equal 'false', cson false

it 'handles the empty object', ->
equal '{}', cson {}

it 'handles the empty array', ->
equal '[]', cson []

it 'handles numbers', ->
equal '0.42', cson 0.42
equal '42', cson 42
equal '1.2e+90', cson 1.2e+90

it 'handles single-line strings', ->
equal '"hello!"', cson 'hello!'

it 'handles multi-line strings', ->
equal """
'''
I am your average multi-line string,
and I have a sneaky \\''' in here, too
'''
""", cson """
I am your average multi-line string,
and I have a sneaky ''' in here, too
"""

it 'handles arrays', ->
equal '''
[
[
1
]
null
[]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know you love diff'ability - would it be worth to make this serialize as [\n]? Not feeling strong either way.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I actually ran a little poll among peers (including a few as fond of comma-first json as I am), who all barfed on it. :-) I also searched around a bit, looking at implementations, and couldn't find any who did, so it might be safer for adoption if we don't either.

I'd be okay with either, but didn't feel like sticking out my chin to promote it, especially as there is some benefit in being able to quickly glean what values are, and a json object full of empty arrays and objects gets three times as compact and gleanable the current way.

{
a: "str"
}
]
''', cson [ [1], null, [], a: 'str' ]

it 'handles objects', ->
equal '''
{
"": "empty"
"non\\nidentifier": true
default: false
nested: {
string: "too"
}
array: [
{}
[]
]
}
''', cson {
'': 'empty'
"non\nidentifier": true
default: false
nested: {
string: 'too'
}
array: [
{}
[]
]
}

it 'handles NaN and +/-Infinity like JSON.stringify does', ->
equal 'null', cson NaN
equal 'null', cson +Infinity
equal 'null', cson -Infinity

it 'handles undefined like JSON.stringify does', ->
equal undefined, cson undefined

it 'handles functions like JSON.stringify does', ->
equal undefined, cson ->

it 'works just like JSON.stringify when asking for no indentation', ->
equal '{"zeroed":0}', cson zeroed: 0, null, 0
equal '{"empty":""}', cson empty: '', null, ''

it 'accepts no more than ten indentation steps, just like JSON.stringify', ->
equal '''
{
"don't": "be silly, will'ya?"
}
''', cson {"don't": "be silly, will'ya?"}, null, Infinity

it 'lets people that really want to indent with tabs', ->
equal '''
{
\t\t"super-tabby": true
}
''', cson {'super-tabby': yes}, null, '\t\t'

it 'is bug compatible with JSON.stringify for non-whitespace indention', ->
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You of all people would call the ability to indent with colored blocks a "bug"?

screen shot 2014-12-02 at 3 43 15 pm

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

chuckles That's kind of brilliant. :-D Shame the spec says truncate at 10 chars, ansi or not. :-)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I originally had two blocks but that was too long. ^^

equal '''
{
ecma-262strange: true
}
''', cson {strange: yes}, null, 'ecma-262'

it 'handles visitor functions', ->
equal '''
{
keep: 1
}
''', cson {filter: 'me', keep: 1}, (k, v) -> v unless typeof v is 'string'