yaml_editor 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: c4d94171e199ead4f730762d78bbcb675740b5f2
4
+ data.tar.gz: c39259d34ac37dc36304aa0aa1a161afc6507ff3
5
+ SHA512:
6
+ metadata.gz: 31a145372b9f7edb99b0a9c55a61ef989b6f87813bd36dc7d7b7e805632fb70bc84487ccd6b577b06537f35f879688833bc8659d962b61cbeec6b2a2a0fdc118
7
+ data.tar.gz: 1e8eb554c871218bdfa9ec4d8dbafb2ab90a3e6d4bb9a776ac7f8006f9c3feff83cdb4ac40e73ac686f06027d0ff839a90f2dd1d22d732f340dd70826057d48c
@@ -0,0 +1,3 @@
1
+ .DS_Store
2
+ *.gem
3
+ coverage
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,18 @@
1
+ # Tests
2
+
3
+ require 'rake/testtask'
4
+ require 'rubocop/rake_task'
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs |= %w[
8
+ test
9
+ lib
10
+ ]
11
+ t.test_files = FileList['test/unit/**/test_*.rb']
12
+ end
13
+
14
+ RuboCop::RakeTask.new(:rubocop) do |t|
15
+ t.fail_on_error = true
16
+ end
17
+
18
+ task default: %i[test rubocop]
@@ -0,0 +1,8 @@
1
+ # Example editor use
2
+ require_relative '../lib/yaml_editor'
3
+
4
+ testfile = File.expand_path('../../test/data/testdata.yml', __FILE__)
5
+ ed = YamlEditor.new(File.read(testfile))
6
+ ed.update('keyb', 1, 'KEY_B', val: '"This was changed"')
7
+ ed.update('keyb', 1, 'KEY_E', val: 'appended')
8
+ puts ed
@@ -0,0 +1,205 @@
1
+ require 'yaml'
2
+
3
+ # Exception class
4
+ class YamlEditorError < StandardError; end
5
+
6
+ # Editor for YAML documents
7
+ # rubocop:disable Metrics/ClassLength
8
+ class YamlEditor
9
+ # Legal indent chars
10
+ INDENTS = [' ', "\t"].freeze
11
+ COMMENTS = ['#'].freeze
12
+ QUOTES = ['\'', '"'].freeze
13
+ MIX_ERR = [YamlEditorError, 'Mixed indents'].freeze
14
+ VAL_ERR = [YamlEditorError, 'Value has mismatched quotes'].freeze
15
+ SET_ERR = [YamlEditorError,
16
+ 'We currently only support adding to hashes'].freeze
17
+ FLD_ERR = [YamlEditorError, 'Values with spaces must be quoted'].freeze
18
+
19
+ def initialize(yaml)
20
+ @doc = yaml.lines.map(&:chomp)
21
+ end
22
+
23
+ def to_yaml
24
+ @doc.join("\n") + "\n"
25
+ end
26
+
27
+ alias to_s to_yaml
28
+
29
+ # High level APIs udpate
30
+
31
+ def update(*fields, val:)
32
+ raise(*FLD_ERR) if bad_quoting?(val)
33
+ spos, _, kind, v = bracket(*fields)
34
+ if kind == :value
35
+ tag, _, comment = v
36
+ @doc[spos] = "#{tag}#{val}#{comment}"
37
+ else
38
+ append(fields, val)
39
+ end
40
+ end
41
+
42
+ # Mid level search API (query)
43
+
44
+ # Iterate through a set of fields to obtain the block
45
+ # rubocop:disable all Hookup
46
+ def bracket(*fields)
47
+ spos = 0
48
+ epos = @doc.size - 1
49
+ value = nil
50
+ # Top level document type
51
+ kind = @doc[1] =~ /\s+-/ ? :array : :hash
52
+ fields.each do |field|
53
+ if field.is_a?(Integer) && kind == :array
54
+ spos, epos = array(spos, epos)[field]
55
+ else
56
+ spos, epos, kind, value = inner_bracket(field, spos, epos)
57
+ end
58
+ break unless spos
59
+ end
60
+ [spos, epos, kind, value]
61
+ end
62
+ # rubocop:enable all
63
+
64
+ # Low level public APIs
65
+
66
+ # Calculate a block start and finish based upon a field
67
+ # rubocop:disable Metrics/MethodLength ok
68
+ # rubocop:disable Metrics/AbcSize ok
69
+ def inner_bracket(field, spos, epos)
70
+ ind = @doc[spos..epos].index { |v| v =~ /\A\s*-*\s*#{field}\:/ }
71
+ return unless ind
72
+ ind += spos
73
+ start_line = @doc[ind]
74
+ schar, snum = indented(start_line)
75
+ val = value(start_line)
76
+ return [ind, ind, :value, val] if val # Value returned if value
77
+ ind += 1
78
+ kind = array?(@doc[ind]) ? :array : :hash
79
+ # Loop until we encounter same indent level or end
80
+ @doc[ind..epos].each_with_index do |line, eind|
81
+ nchar, nnum = indented(line)
82
+ raise(*MIX_ERR) if nchar != schar
83
+ return [ind, ind + eind - 1, kind] if nnum <= snum
84
+ end
85
+ [ind, epos, kind]
86
+ end
87
+ # rubocop:enable all
88
+
89
+ # Produce a set of bracketed array lines betweem a line range
90
+ # requires that we start with a known array position containing
91
+ # the hyphen
92
+ # rubocop:disable Metrics/AbcSize ok
93
+ def array(spos, epos)
94
+ # Get initial indent level
95
+ ilvl = non_ws_index(@doc[spos])
96
+ # Produce start and end pairings
97
+ res = @doc[spos..epos].each_with_index.map do |line, ind|
98
+ nlvl = non_ws_index(line)
99
+ nlvl == ilvl ? spos + ind : nil
100
+ end
101
+ # Strip non boundaries, append a final marker and collect range groups
102
+ res.compact.push(epos + 1).each_cons(2).map do |s, f|
103
+ # Skip empty boundaries
104
+ s += 1 until hash_key?(@doc[s])
105
+ s >= f ? nil : [s, f.pred]
106
+ end
107
+ .compact
108
+ end
109
+ # rubocop:enable all
110
+
111
+ # Analyse the line for a value
112
+ def value(line)
113
+ res = line.match(/\A(?<tag>.+\:\s)(?<value>.+)\Z/)
114
+ return unless res
115
+ tag = res[:tag]
116
+ val = res[:value]
117
+ val, rest = value_split(val)
118
+ return if val.empty?
119
+ # Return the split line that could be reassembled
120
+ [tag, val, rest]
121
+ end
122
+
123
+ # RAW access
124
+ # :nocov:
125
+ def lines(range)
126
+ @doc[range]
127
+ end
128
+ # :nocov:
129
+
130
+ private
131
+
132
+ # Split the value half to capture comments etc.
133
+ def value_split(val)
134
+ # Comment only ?
135
+ return ['', val] if val.start_with?(*COMMENTS)
136
+ # No quotes ?
137
+ return split_noquote(val) unless val.start_with?(*QUOTES)
138
+ # Quotes
139
+ split_quoted(val)
140
+ end
141
+
142
+ # Simple unquoted values
143
+ def split_noquote(val)
144
+ pos = val.index(/\s/)
145
+ pos ? [val[0..pos.pred], val[pos..-1]] : [val, '']
146
+ end
147
+
148
+ # Quoted values
149
+ def split_quoted(val)
150
+ prev = quote = val[0]
151
+ pos = 1
152
+ until val[pos] == quote && prev != '\\'
153
+ prev = val[pos]
154
+ pos += 1
155
+ raise(*VAL_ERR) if pos > val.length
156
+ end
157
+ [val[0..pos], val[pos.succ..-1]]
158
+ end
159
+
160
+ # Type and count of indent char
161
+ def indented(line)
162
+ spaces = line.match(/\A\s*-*\s*/).to_s
163
+ ichars = INDENTS.map { |c| spaces.count(c) }
164
+ raise(*MIX_ERR) if ichars.count(&:nonzero?) > 1
165
+ # On zero indents we default to space and zero
166
+ iichar = ichars.index(&:nonzero?) || 0
167
+ # Add any hyphens for arrays detected inline
168
+ [INDENTS[iichar], ichars[iichar] + spaces.count('-')]
169
+ end
170
+
171
+ # Used by set in cases where the field does not exist
172
+ # rubocop:disable Metrics/AbcSize ok
173
+ def append(fields, val)
174
+ parent = fields.dup
175
+ node = parent.pop
176
+ spos, epos, = bracket(*parent)
177
+ # Must inspect inner element for type
178
+ kind = value(@doc[spos]) ? :hash : :array
179
+ raise(*SET_ERR) unless kind == :hash
180
+ ichar, inum = indented(@doc[epos])
181
+ pad = ichar * inum
182
+ @doc.insert(epos.succ, "#{pad}#{node}: #{val}")
183
+ end
184
+ # rubocop:enable all
185
+
186
+ # Are quotes missing but needed?
187
+ def bad_quoting?(val)
188
+ val.include?(' ') && !QUOTES.include?(val[0]) || false
189
+ end
190
+
191
+ # Simple position of first non whitespace
192
+ def non_ws_index(line)
193
+ line.index(/[^\s]/)
194
+ end
195
+
196
+ # Simple Hash key presence
197
+ def hash_key?(line)
198
+ line =~ /\A\s*-*\s*.+:/
199
+ end
200
+
201
+ # Array marker presence
202
+ def array?(line)
203
+ line =~ /\A\s*-/
204
+ end
205
+ end
@@ -0,0 +1,119 @@
1
+ # YAML Editor class
2
+
3
+ Do you manually edit YAML in your DevOps repos?
4
+
5
+ Do you rely on commments being in place and position order for your YAML fragments?
6
+
7
+ Do you wish you could occasionally update elements within those YAML files without losing comments or existing order?
8
+
9
+ Is sed just a little crude for the job?
10
+
11
+ If so then maybe this gem is useful to you.
12
+
13
+ # About
14
+
15
+ This gem provides a class that can be utilised to update or add entries into YAML and takes an approach of using ordered fields to access portions of the YAML document and locate sections with an API that will allow arbitrary values to be set on keys.
16
+
17
+ The initial implementation is more about getting you to the point of being able to enter new values or update existing values and does not attempt to wrap access into a plain Ruby object as a collection.
18
+
19
+ It's main API is the update API that allows one to update or append values into a YAML document with some limitations. I've taken the approach of being pragmatic and requiring the caller to be sensible about quoting values for multi word strings throwing exceptions if they are needed but not provided and chosen this initial approach to keep consistent with the simple value access APIs.
20
+
21
+ Functionally this implementation is not exhaustive but meets our use cases.
22
+ # High level API
23
+
24
+ ## #new(yaml)
25
+
26
+ Pass a YAML document as a string.
27
+
28
+ ## #to_s/#to_yaml
29
+
30
+ Output the YAML document following an edit session.
31
+
32
+ ## #update(*fields, val:)
33
+
34
+ Update a field within the YAML document using val indexed by the fields list.
35
+
36
+
37
+ # Example use (from examples folder)
38
+
39
+ ## example1.rb
40
+ ```
41
+ require_relative '../lib/yaml_editor'
42
+
43
+ testfile = File.expand_path('../../test/data/testdata.yml', __FILE__)
44
+ ed = YamlEditor.new(File.read(testfile))
45
+ ed.update('keyb', 1, 'KEY_B', val: '"This was changed"')
46
+ ed.update('keyb', 1, 'KEY_E', val: 'appended')
47
+ puts ed
48
+ ```
49
+
50
+ As we can see the position and comment associated with KEY_B have been preserved and the new KEY_E value has been appended to the 2nd array element of the 'keyb' node.
51
+
52
+ ```
53
+ [Running] ruby "/Users/andrew.smith/Ruby/yaml-formatted/examples/example1.rb"
54
+ ---
55
+ keya:
56
+ second:
57
+ KEY_A: valuea
58
+ KEY_B: valueb # Comment
59
+ KEY_C: 'value c'
60
+ KEY_D: "value d" # Comment
61
+ keyb:
62
+ -
63
+ KEY_A: valuea
64
+ KEY_B: valueb # Comment
65
+ KEY_C: 'value c'
66
+ KEY_D: "value d" # Comment
67
+ -
68
+ KEY_A: valuee
69
+ KEY_B: "This was changed" # Comment
70
+ KEY_C: 'value g'
71
+ KEY_D: "value h" # Comment
72
+ KEY_E: appended
73
+ - # Empty elements should be ignored
74
+ -
75
+ KEY_A: valuei
76
+ KEY_B: valuej # Comment
77
+ KEY_C: 'value k'
78
+ KEY_D: "value l" # Comment
79
+ - SAMELINE: "a value m"
80
+ ANOTHER: 'extra value'
81
+ - ONITSOWN: 'standalone value'
82
+ keyc:
83
+ coll:
84
+ - name: 'index 0'
85
+ - name: 'index 1'
86
+ ```
87
+
88
+ # Mid level API
89
+
90
+ The mid level API may change over time, however it is currently public.
91
+
92
+ The low level API is used to read portions of the doucment, locate entries and break lines down into component parts.
93
+
94
+ ## #bracket(*fields)
95
+
96
+ Use fields and index numbers to determine start and end line range for a document section, the kind of element being referenced and where a value to also return an array containing the line split by tag, value and comment if present.
97
+
98
+ # Low level API (semi private)
99
+
100
+ As above the low level API may be used to read portions of the document in a custom manner.
101
+
102
+ ## #inner_bracket(field, spos, epos)
103
+
104
+ Used by the bracket function this allows a single field to be searched within a hash between two line ranges.
105
+
106
+ ## #array(spos, epos)
107
+
108
+ When used with a line range containing an array it returns an array of tuples containig the start end end position for each child section.
109
+
110
+ For example use of mid and low level API please see the unit tests.
111
+
112
+ ## #lines(range)
113
+
114
+ Provide a group of lines as an array from the internal document.
115
+
116
+ ## #value(line)
117
+
118
+ Split the line into the tagged region (containing the leading spaces) up to the value, the actual value (including quotes as necessary, and any remaining text on the line such as commments.
119
+
@@ -0,0 +1,45 @@
1
+ ---
2
+ keya:
3
+ second:
4
+ KEY_A: valuea
5
+ KEY_B: valueb # Comment
6
+ KEY_C: 'value c'
7
+ KEY_D: "value d" # Comment
8
+ keyb:
9
+ -
10
+ KEY_A: valuea
11
+ KEY_B: valueb # Comment
12
+ KEY_C: 'value c'
13
+ KEY_D: "value d" # Comment
14
+ -
15
+ KEY_A: valuee
16
+ KEY_B: valuef # Comment
17
+ KEY_C: 'value g'
18
+ KEY_D: "value h" # Comment
19
+ - # Empty elements should be ignored
20
+ -
21
+ KEY_A: valuei
22
+ KEY_B: valuej # Comment
23
+ KEY_C: 'value k'
24
+ KEY_D: "value l" # Comment
25
+ - SAMELINE: "a value m"
26
+ ANOTHER: 'extra value'
27
+ - ONITSOWN: 'standalone value'
28
+ keyc:
29
+ coll:
30
+ - name: 'index 0'
31
+ - name: 'index 1'
32
+ keyd:
33
+ -
34
+ nested:
35
+ -
36
+ KEY_A: 'foo'
37
+ KEY_B: 'bar'
38
+ another:
39
+ -
40
+ KEY_A: 'one'
41
+ KEY_B: 'two'
42
+ -
43
+ toignore:
44
+ -
45
+ ignorema: 'dummy'
@@ -0,0 +1,7 @@
1
+ require 'simplecov'
2
+ SimpleCov.command_name 'test:unit'
3
+ SimpleCov.start do
4
+ add_group 'Libs', 'lib/'
5
+ track_files 'lib/*.rb'
6
+ add_filter '/test/'
7
+ end
@@ -0,0 +1,137 @@
1
+ require 'test_helper'
2
+ require 'minitest/autorun'
3
+ require 'yaml_editor'
4
+ require 'pp'
5
+
6
+ # Unit Test
7
+ # rubocop:disable Metrics/ClassLength
8
+ class TestYamlEditor < Minitest::Test
9
+ def setup
10
+ testfile = File.expand_path('../../data/testdata.yml', __FILE__)
11
+ @ed = YamlEditor.new(File.read(testfile))
12
+ end
13
+
14
+ def test_bracket_value
15
+ _spos, _epos, kind, v = @ed.bracket('keya', 'second', 'KEY_A')
16
+ assert_equal(:value, kind)
17
+ _tag, value, comment = v
18
+ assert_equal('valuea', value)
19
+ assert_empty(comment)
20
+ end
21
+
22
+ def test_bracket_value_quote
23
+ _spos, _epos, kind, v = @ed.bracket('keya', 'second', 'KEY_C')
24
+ assert_equal(:value, kind)
25
+ _tag, value, comment = v
26
+ assert_equal('\'value c\'', value)
27
+ assert_empty(comment)
28
+ end
29
+
30
+ def test_get_hash
31
+ spos, epos, kind, = @ed.bracket('keya', 'second')
32
+ assert_equal(:hash, kind)
33
+ assert_equal(3, epos - spos) # 4 values but zero based lines
34
+ end
35
+
36
+ def test_get_array
37
+ spos, epos, kind, = @ed.bracket('keyb')
38
+ assert_equal(:array, kind)
39
+ assert_equal(18, epos - spos)
40
+ end
41
+
42
+ def test_bracket_value_comment
43
+ _spos, _epos, kind, v = @ed.bracket('keya', 'second', 'KEY_D')
44
+ assert_equal(:value, kind)
45
+ tag, value, comment = v
46
+ assert_includes(tag, 'KEY_D:')
47
+ assert_equal('"value d"', value)
48
+ assert_equal(' # Comment', comment)
49
+ end
50
+
51
+ def test_array_index
52
+ spos, epos, kind, = @ed.bracket('keyb')
53
+ assert_equal(:array, kind)
54
+ arr = @ed.array(spos, epos)
55
+ assert_kind_of(Array, arr)
56
+ assert(3, arr.first.last - arr.first.first)
57
+ # Move out to another test after embedding array indexing in bracketing.
58
+ assert_includes(@ed.lines(arr.last.first), 'standalone value')
59
+ end
60
+
61
+ def test_array_bracket
62
+ _spos, _epos, kind, v = @ed.bracket('keyb', 1, 'KEY_B')
63
+ assert_equal(:value, kind)
64
+ tag, value, comment = v
65
+ assert_includes(tag, 'KEY_B:')
66
+ assert_equal('valuef', value)
67
+ assert_equal(' # Comment', comment)
68
+ end
69
+
70
+ def test_collection_hashes_0
71
+ _spos, _epos, _kind, v = @ed.bracket('keyc', 'coll', 0, 'name')
72
+ _tag, value, = v
73
+ assert_equal('\'index 0\'', value)
74
+ end
75
+
76
+ def test_collection_hashes_1
77
+ _spos, _epos, _kind, v = @ed.bracket('keyc', 'coll', 1, 'name')
78
+ _tag, value, = v
79
+ assert_equal('\'index 1\'', value)
80
+ end
81
+
82
+ def test_update
83
+ @ed.update('keyb', 1, 'KEY_D', val: 'updated')
84
+ _spos, _epos, kind, v = @ed.bracket('keyb', 1, 'KEY_D')
85
+ assert_equal(:value, kind)
86
+ tag, value, comment = v
87
+ assert_includes(tag, 'KEY_D:')
88
+ assert_equal('updated', value)
89
+ assert_equal(' # Comment', comment)
90
+ end
91
+
92
+ def test_spaced_update
93
+ @ed.update('keyb', 1, 'KEY_D', val: '"updated with spaces"')
94
+ _spos, _epos, kind, v = @ed.bracket('keyb', 1, 'KEY_D')
95
+ assert_equal(:value, kind)
96
+ tag, value, comment = v
97
+ assert_includes(tag, 'KEY_D:')
98
+ assert_equal('"updated with spaces"', value)
99
+ assert_equal(' # Comment', comment)
100
+ end
101
+
102
+ def test_bad_quotes
103
+ assert_raises(YamlEditorError) do
104
+ @ed.update('keyb', 1, 'KEY_D', val: 'should not work')
105
+ end
106
+ end
107
+
108
+ def test_update_append
109
+ @ed.update('keyb', 1, 'KEY_E', val: 'appended')
110
+ spos, epos, = @ed.bracket('keyb', 1)
111
+ assert_equal(4, epos - spos)
112
+ _spos, _epos, kind, v = @ed.inner_bracket('KEY_E', spos, epos)
113
+ assert_equal(:value, kind)
114
+ _tag, value, = v
115
+ assert_equal('appended', value)
116
+ end
117
+
118
+ def test_to_yaml
119
+ assert_equal(45, @ed.to_yaml.lines.count)
120
+ end
121
+
122
+ def test_hashes_in_collections_a
123
+ @ed.update('keyd', 0, 'nested', 0, 'KEY_A', val: 'changed')
124
+ _spos, _epos, _kind, v = @ed.bracket('keyd', 0, 'nested', 0, 'KEY_A')
125
+ tag, value, = v
126
+ assert_includes(tag, 'KEY_A:')
127
+ assert_equal('changed', value)
128
+ end
129
+
130
+ def test_hashes_in_collections_b
131
+ @ed.update('keyd', 0, 'nested', 0, 'KEY_C', val: 'appended')
132
+ _spos, _epos, _kind, v = @ed.bracket('keyd', 0, 'nested', 0, 'KEY_C')
133
+ tag, value, = v
134
+ assert_includes(tag, 'KEY_C:')
135
+ assert_equal('appended', value)
136
+ end
137
+ end
@@ -0,0 +1,23 @@
1
+ class << $LOAD_PATH
2
+ def merge!(other)
3
+ replace(self | other)
4
+ end
5
+ end
6
+
7
+ $LOAD_PATH.merge! [File.expand_path('../lib', __FILE__)]
8
+
9
+ Gem::Specification.new do |spec|
10
+ raise 'RubyGems 2.0 or newer is required.' unless spec.respond_to?(:metadata)
11
+ spec.name = 'yaml_editor'
12
+ spec.version = '0.0.2'
13
+ spec.authors = ['Andrew Smith']
14
+ spec.email = ['andrew.smith at moneysupermarket.com']
15
+
16
+ spec.summary = 'Update YAML documents preserving layout and comments'
17
+ spec.description = 'Allows update of YAML directly indexing fields within'\
18
+ ' the document without deserialisation to objects so '\
19
+ ' that order and comments may be preserved'
20
+ spec.homepage = 'https://github.com/MSMFG/rubygem_yaml_editor'
21
+ spec.license = 'Apache-2.0'
22
+ spec.files = `git ls-files -z`.split("\x0")
23
+ end
metadata ADDED
@@ -0,0 +1,55 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: yaml_editor
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.2
5
+ platform: ruby
6
+ authors:
7
+ - Andrew Smith
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2018-04-19 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Allows update of YAML directly indexing fields within the document without
14
+ deserialisation to objects so that order and comments may be preserved
15
+ email:
16
+ - andrew.smith at moneysupermarket.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - ".gitignore"
22
+ - LICENSE
23
+ - Rakefile
24
+ - examples/example1.rb
25
+ - lib/yaml_editor.rb
26
+ - readme.md
27
+ - test/data/testdata.yml
28
+ - test/test_helper.rb
29
+ - test/unit/test_yaml_editor.rb
30
+ - yaml_editor.gemspec
31
+ homepage: https://github.com/MSMFG/rubygem_yaml_editor
32
+ licenses:
33
+ - Apache-2.0
34
+ metadata: {}
35
+ post_install_message:
36
+ rdoc_options: []
37
+ require_paths:
38
+ - lib
39
+ required_ruby_version: !ruby/object:Gem::Requirement
40
+ requirements:
41
+ - - ">="
42
+ - !ruby/object:Gem::Version
43
+ version: '0'
44
+ required_rubygems_version: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: '0'
49
+ requirements: []
50
+ rubyforge_project:
51
+ rubygems_version: 2.2.5
52
+ signing_key:
53
+ specification_version: 4
54
+ summary: Update YAML documents preserving layout and comments
55
+ test_files: []