Skip to content

Commit

Permalink
Comment reading/write improvements
Browse files Browse the repository at this point in the history
This patch fixes some aspects of reading and writing comments:
- Multiple C++-style comments before a Json value had extra newlines appended to them. This patch removes the addition of those newlines.
- Comments written before Json values in the StyledWriter were not indented to match the indentation level of the value. This patch adds indentation to comments.
- Fixed inconsistency in newlines following C- and C++-style comments being saved as part of the comment. All newlines at the end of a comment are now removed.
- Added an additional test of comments.

https://sourceforge.net/p/jsoncpp/patches/25/
  • Loading branch information
cdunn2001 committed Apr 19, 2014
1 parent ea07973 commit 09439b7
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/lib_json/json_reader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,17 @@ Reader::readValue()

if ( collectComments_ && !commentsBefore_.empty() )
{
// Remove newline characters at the end of the comments
size_t lastNonNewline = commentsBefore_.find_last_not_of("\r\n");
if (lastNonNewline != std::string::npos)
{
commentsBefore_.erase(lastNonNewline+1);
}
else
{
commentsBefore_.clear();
}

currentValue().setComment( commentsBefore_, commentBefore );
commentsBefore_ = "";
}
Expand Down
15 changes: 14 additions & 1 deletion src/lib_json/json_writer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,20 @@ StyledWriter::writeCommentBeforeValue( const Value &root )
{
if ( !root.hasComment( commentBefore ) )
return;
document_ += normalizeEOL( root.getComment( commentBefore ) );

document_ += "\n";
writeIndent();
std::string normalizedComment = normalizeEOL( root.getComment( commentBefore ) );
std::string::const_iterator iter = normalizedComment.begin();
while ( iter != normalizedComment.end() )
{
document_ += *iter;
if ( *iter == '\n' && *(iter+1) == '/' )
writeIndent();
++iter;
}

// Comments are stripped of newlines, so add one here
document_ += "\n";
}

Expand Down
7 changes: 7 additions & 0 deletions test/data/test_comment_02.expected
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.={}
.c-test={}
.c-test.a=1
.c-test.b=2
.cpp-test={}
.cpp-test.c=3
.cpp-test.d=4
16 changes: 16 additions & 0 deletions test/data/test_comment_02.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
/* C-style comment

C-style-2 comment */
"c-test" : {
"a" : 1,
/* Internal comment c-style */
"b" : 2
},
// C++-style comment
"cpp-test" : {
// Internal comment cpp-style
"c" : 3,
"d" : 4
}
}

0 comments on commit 09439b7

Please sign in to comment.