Carleslc / Simple-YAML

This Java API provides an easy-to-use way to store data and provide configurations using the YAML format.
https://carleslc.me/Simple-YAML
GNU General Public License v3.0
130 stars 38 forks source link

Comment fixes + Header & Comment Formatter #54

Closed Carleslc closed 2 years ago

Carleslc commented 2 years ago

Fixes #42

The comment parser and dumper has been reworked. Previously it was breaking when using a comment prefix # inside quotes. Now it takes into account literals and quotes for plain, double quote or single quote scalar styles.

Formatting comments #53

Header behaviour has changed to be more intuitive. Now the header is considered to be the first block comment until a blank line (i.e. with no direct key below), instead of everything above the first key like before. The comment on the first key does not overlap anymore with the header. The header and the first key comment are separated by a blank line.

getHeader() and setHeader(String) methods have been added.

getFooter() and setFooter(String) methods have been added for the last comment of the file without any key below.

In addition, now it is possible to format comments using prefixes and suffixes, globally or per comment, taking into account blank lines as comments, with some configurations available for reading comments (for instance stripping the # prefix and stripping trailing or leading blank lines), using an instance of YamlCommentFormatter or a custom format implementing CommentFormatter.

The default prefix is "# " for block comments and " # " for side comments. You can change them to add blank lines above or below the comments, or to add more spaces, # characters or section dividers.

Some default formatters are provided with the YamlCommentFormat enum, for instance the following will add blank lines for the comments of root keys (those with indent 0):

yamlFile.setCommentFormat(YamlCommentFormat.PRETTY);

The YamlCommentsExample has been improved to reflect these changes.

A new example has been added: YamlCommentsFormatExample -> test-comments-format.yml

Alternative API

An alternative API has been added using the path(String) method to set comments along with values without repeating the path. Example:

Normal API:

yamlFile.set("test.hello", "Hello");
yamlFile.setComment("test.hello", "Block comment");
yamlFile.setComment("test.hello", "Side comment", CommentType.SIDE);

Alternative API:

yamlFile.path("test.hello")
        .set("Hello")
        .comment("Block comment")
        .commentSide("Side comment");

This alternative is only available for setting values (or defaults) and comments. To read those values and comments you still need to use the normal methods.