Support custom newline symbol(s) for format option

This commit is contained in:
Dmitry Kolesnikov 2019-05-24 22:54:36 +03:00
parent 528d5b8253
commit 5dbb9b5f24
No known key found for this signature in database
GPG key ID: 7CB96BFD85501756
3 changed files with 22 additions and 4 deletions

4
.gitignore vendored
View file

@ -8,3 +8,7 @@ erl_crash.dump
.DS_Store
doc
.rebar
*.sublime-*
rebar3
_build/

View file

@ -572,8 +572,9 @@ format(JSON) -> JSON
format(JSON, Opts) -> JSON
JSON = json_text()
Opts = [option() | space | {space, N} | indent | {indent, N}]
N = pos_integer()
Opts = [option() | space | {space, N} | indent | {indent, N} | {newline, LF}]
N = pos_integer()
LF = binary()
```
`format` parses a json text (a `utf8` encoded binary) and produces a new json
@ -586,6 +587,9 @@ the option `{indent, N}` inserts a newline and `N` spaces for each level of
indentation in your json output. note that this overrides spaces inserted after
a comma. `indent` is an alias for `{indent, 1}`. the default is `{indent, 0}`
the option `{newline, LF}` defines a custom newline symbol(s).
the default is `{newline, <<$\n>>}`
raises a `badarg` error exception if input is not valid json

View file

@ -32,7 +32,8 @@
-record(config, {
space = 0,
indent = 0,
depth = 0
depth = 0,
newline = <<$\n>>
}).
-type config() :: list().
@ -62,6 +63,8 @@ parse_config([{indent, Val}|Rest], Config) when is_integer(Val), Val > 0 ->
parse_config(Rest, Config#config{indent = Val});
parse_config([indent|Rest], Config) ->
parse_config(Rest, Config#config{indent = 1});
parse_config([{newline, Val}|Rest], Config) when is_binary(Val) ->
parse_config(Rest, Config#config{newline = Val});
parse_config([{K, _}|Rest] = Options, Config) ->
case lists:member(K, jsx_config:valid_flags()) of
true -> parse_config(Rest, Config)
@ -128,7 +131,7 @@ space(Config) ->
indent(Config) ->
case Config#config.indent of
0 -> <<>>
; X when X > 0 -> <<?newline/binary, (binary:copy(?space, X * Config#config.depth))/binary>>
; X when X > 0 -> <<(Config#config.newline)/binary, (binary:copy(?space, X * Config#config.depth))/binary>>
end.
@ -383,6 +386,13 @@ format_test_() ->
[{Title, ?_assertEqual(Min, jsx:minify(Pretty))} || {Title, Min, Pretty} <- Cases] ++
[{Title, ?_assertEqual(Pretty, jsx:prettify(Min))} || {Title, Min, Pretty} <- Cases].
custom_newline_test_() ->
[
{"single key object", ?_assert(
jsx:format(<<"{\"k\":\"v\"}">>, [space, {indent, 2}, {newline, <<$\r>>}])
=:= <<"{\r \"k\": \"v\"\r}">>)
}
].
handle_event_test_() ->
Data = jsx:test_cases() ++ jsx:special_test_cases(),