Skip to content

Commit

Permalink
Merge pull request #9 from johan/stringify
Browse files Browse the repository at this point in the history
A nicer CSON.stringify
  • Loading branch information
jkrems committed Dec 3, 2014
2 parents e41dff0 + 420717b commit 95df466
Show file tree
Hide file tree
Showing 5 changed files with 313 additions and 12 deletions.
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
[]
{
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', ->
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'

0 comments on commit 95df466

Please sign in to comment.