patchyaml 0.1.0

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: cfc5b7ca990f2b4e504bcc910faad8efd99467aef4d53b58115c04c626e3a0c3
4
+ data.tar.gz: 1d63195ee9f96395da68c3583d30249217db45c9add3c19a0435fd424b41f49f
5
+ SHA512:
6
+ metadata.gz: 408cbf60cfbcb5a5003744d506dfbc6ff7aa090f09e2c57968e8469f665eae07091c922c7c65d6d94cd975cacb5a953b585090143f02ddecb53e3f5237c2cbdd
7
+ data.tar.gz: d9c9dad17bc67cad43748a63ca5f6e2125c50b17147974fbc5db65e21ccf7ed455b2e98be4736fa72677ec59a245efd2551e24ea454ff1fec4654a81da6d3f26
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,65 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.4
3
+ SuggestExtensions: false
4
+ NewCops: enable
5
+
6
+ Style/StringLiterals:
7
+ EnforcedStyle: double_quotes
8
+
9
+ Style/StringLiteralsInInterpolation:
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
14
+ Exclude:
15
+ - "**/spec/**/**"
16
+
17
+ Layout/FirstHashElementIndentation:
18
+ EnforcedStyle: consistent
19
+
20
+ Layout/EndAlignment:
21
+ EnforcedStyleAlignWith: start_of_line
22
+
23
+ Layout/MultilineMethodCallIndentation:
24
+ EnforcedStyle: indented
25
+
26
+ Style/Documentation:
27
+ Enabled: false
28
+
29
+ Layout/CaseIndentation:
30
+ EnforcedStyle: end
31
+
32
+ Layout/FirstArgumentIndentation:
33
+ EnforcedStyle: consistent_relative_to_receiver
34
+
35
+ Layout/ArgumentAlignment:
36
+ EnforcedStyle: with_fixed_indentation
37
+
38
+ Style/EmptyCaseCondition:
39
+ Enabled: false
40
+
41
+ Metrics/BlockLength:
42
+ Exclude:
43
+ - "**/spec/**/**.rb"
44
+ - "**/**/**.gemspec"
45
+
46
+ Metrics/ClassLength:
47
+ Enabled: false
48
+
49
+ Metrics/ModuleLength:
50
+ Enabled: false
51
+
52
+ Metrics/MethodLength:
53
+ Enabled: false
54
+
55
+ Metrics/AbcSize:
56
+ Enabled: false
57
+
58
+ Metrics/CyclomaticComplexity:
59
+ Enabled: false
60
+
61
+ Metrics/PerceivedComplexity:
62
+ Enabled: false
63
+
64
+ Lint/LiteralAsCondition:
65
+ Enabled: false
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ hey@vito.io.
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Vito Sartori
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,92 @@
1
+ # PatchYAML
2
+
3
+ PatchYAML is an utility library for patching YAML while optimistically keeping
4
+ the original document formatting.
5
+
6
+ ## Installation
7
+
8
+ Install the gem and add to the application's Gemfile by executing:
9
+
10
+ ```bash
11
+ bundle add patchyaml
12
+ ```
13
+
14
+ If bundler is not being used to manage dependencies, install the gem by executing:
15
+
16
+ ```bash
17
+ gem install patchyaml
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ The exposed interface is intentionally minimal. The library provide the methods
23
+ `delete`, `update`, `map_rename`, `map_add`, and `seq_add`, obtaining the
24
+ resulting changes through the `yaml` method. For instance:
25
+
26
+ ```ruby
27
+ require 'patchyaml'
28
+
29
+ editor = PatchYAML.load(<<~YAML)
30
+ mapping:
31
+ a:
32
+ sequence:
33
+ - name: a
34
+ - name: b
35
+ - name: c
36
+ - name: d
37
+ otherValue: hello
38
+ b: foo
39
+ c: true
40
+ d: [1, 2, 3, 4, foo, bar, hello]
41
+ d: 1
42
+ empty:
43
+ e: { a: 1, b: 2, c: 3 }
44
+ f: [1, 2, 3, 4, hello]
45
+ g: {}
46
+ h: []
47
+ YAML
48
+
49
+ editor
50
+ .delete("mapping.a.sequence.1")
51
+ .update("mapping.a.sequence.3.otherValue", "henlo")
52
+ .map_rename("mapping.b", to: "test")
53
+ .map_add("mapping.a", "e", "some value")
54
+ .seq_add("f", 123)
55
+
56
+ puts editor.yaml
57
+ # mapping:
58
+ # a:
59
+ # sequence:
60
+ # - name: b
61
+ # - name: c
62
+ # - name: d
63
+ # otherValue: henlo
64
+ # b: test
65
+ # c: true
66
+ # d: [1, 2, 3, 4, foo, bar, hello]
67
+ # e: some value
68
+ # d: 1
69
+ # empty:
70
+ # e: { a: 1, b: 2, c: 3 }
71
+ # f: [1, 2, 3, 4, hello, 123]
72
+ # g: {}
73
+ # h: []
74
+ ```
75
+
76
+ ## Development
77
+
78
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
79
+
80
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
81
+
82
+ ## Contributing
83
+
84
+ Bug reports and pull requests are welcome on GitHub at https://github.com/heyvito/patchyaml. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/heyvito/patchyaml/blob/master/CODE_OF_CONDUCT.md).
85
+
86
+ ## License
87
+
88
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
89
+
90
+ ## Code of Conduct
91
+
92
+ Everyone interacting in the Patchyaml project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/heyvito/patchyaml/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PatchYAML
4
+ class Editor
5
+ def process_anchor(from)
6
+ @anchors[from.anchor] = from if !from.is_a?(Psych::Nodes::Alias) && from.respond_to?(:anchor) && !from.anchor.nil?
7
+
8
+ case from
9
+ when Psych::Nodes::Stream, Psych::Nodes::Document
10
+ process_anchor(from.children.first)
11
+ when Psych::Nodes::Mapping
12
+ process_anchor_map(from)
13
+ when Psych::Nodes::Sequence
14
+ from.children.each { process_anchor(it) }
15
+ when Psych::Nodes::Scalar, Psych::Nodes::Alias
16
+ # noop
17
+ else
18
+ raise "patchyaml: Unexpected node #{from.class} in #process_anchor"
19
+ end
20
+ end
21
+
22
+ def process_anchor_map(from)
23
+ from.children.each.with_index do |item, idx|
24
+ process_anchor(item) if idx.odd?
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PatchYAML
4
+ class Editor
5
+ def initialize(data)
6
+ @anchors = {}
7
+ @pipeline = []
8
+
9
+ reload(data)
10
+ end
11
+
12
+ # Deletes a given path from the yaml
13
+ #
14
+ # path - The path to the key to be deleted
15
+ #
16
+ # Returns the same Editor instance
17
+ def delete(path) = tap { @pipeline << [:delete, path] }
18
+
19
+ # Updates an existing path in the yaml to have the provided value
20
+ #
21
+ # path - The path to the key to be updated
22
+ # value - The value to be set in the key
23
+ #
24
+ # Returns the same Editor instance
25
+ def update(path, value) = tap { @pipeline << [:update, path, value] }
26
+
27
+ # Renames a given path
28
+ #
29
+ # path - The path to the key to be renamed
30
+ # to: - The new name of the key
31
+ #
32
+ # Returns the same Editor instance
33
+ def map_rename(path, to:)
34
+ tap { @pipeline << [:rename, path, to] }
35
+ end
36
+
37
+ # Adds a new key to the yaml
38
+ #
39
+ # path - The path to the mapping that will receive the new key
40
+ # key - The new key name
41
+ # value - The new key value
42
+ #
43
+ # Returns the same Editor instance
44
+ def map_add(path, key, value)
45
+ tap { @pipeline << [:map_add, path, key, value] }
46
+ end
47
+
48
+ # Adds a new value to a sequence
49
+ #
50
+ # path - The path to the sequence that will receive the new item
51
+ # value - The value to be added to the sequence
52
+ # index: - The index to insert the value into. Defaults to nil, and
53
+ # appends to the end of the sequence.
54
+ #
55
+ # Returns the same Editor instance
56
+ def seq_add(path, value, index: nil)
57
+ tap { @pipeline << [:seq_add, path, value, index] }
58
+ end
59
+
60
+ # Returns the processed YAML after edits have been applied.
61
+ def yaml = run_pipeline
62
+
63
+ private
64
+
65
+ def reload(data)
66
+ @data = data
67
+ @line_sizes = [0] + data.split("\n").map { it.length + 1 }
68
+ begin
69
+ @stream = Psych.parse_stream(data)
70
+ rescue Psych::SyntaxError
71
+ puts "Parsing failed. Input was:\n#{@data}"
72
+ raise
73
+ end
74
+ process_anchor(@stream)
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PatchYAML
4
+ class Editor
5
+ def find(from, path)
6
+ path = QueryParser.parse(path)
7
+ # Pass through Psych::Nodes::Stream -> Psych::Nodes::Document
8
+ node = [from, nil]
9
+ path.each do |part|
10
+ node = find_node(node, part)
11
+ return [] if node.empty?
12
+ end
13
+ node
14
+ end
15
+
16
+ def find_node(from, part)
17
+ case part[:kind]
18
+ when :simple
19
+ case from.first
20
+ when Psych::Nodes::Stream, Psych::Nodes::Document
21
+ find_node([from.first.children.first, from], part)
22
+ when Psych::Nodes::Mapping
23
+ find_mapping_key(from.first, part[:value])
24
+ when Psych::Nodes::Sequence
25
+ [from.first.children.find { it.respond_to?(:value) && it.value == part[:value] }, from.first]
26
+ when Psych::Nodes::Alias
27
+ node = @anchors[from.first.anchor]
28
+ raise "patchyaml: Unknown anchor #{from.anchor} defined by #{from.first}" unless node
29
+
30
+ [find_node(node, part), node]
31
+ else
32
+ raise "patchyaml: Unexpected node #{from.first.class} in #find_node"
33
+ end
34
+ when :index
35
+ case from.first
36
+ when Psych::Nodes::Stream, Psych::Nodes::Document
37
+ [find_node(from.first.children.first, part[:value]), from.first]
38
+ when Psych::Nodes::Sequence
39
+ [from.first.children[part[:value]], from.first]
40
+ end
41
+ when :expression
42
+ case from.first
43
+ when Psych::Nodes::Stream, Psych::Nodes::Document
44
+ [find_node(from.first.children.first, part), from.first]
45
+ when Psych::Nodes::Sequence
46
+ v = from
47
+ .first
48
+ .children
49
+ .find { it.is_a?(Psych::Nodes::Mapping) && find_mapping_key(it, part[:key]).value == part[:value] }
50
+ [v, from]
51
+ end
52
+ end
53
+ end
54
+
55
+ def find_mapping_key(from, named)
56
+ # A mapping is basically an even-numbered array containing keys followed by their values.
57
+ # Keys are expressed as an scalar value.
58
+ i = 0
59
+ until i >= from.children.size - 1
60
+ if from.children[i].value == named
61
+ result = from.children[i + 1]
62
+ return [result, from] unless result.is_a?(Psych::Nodes::Alias)
63
+
64
+ item = @anchors[result.anchor]
65
+ raise "patchyaml: Unknown anchor #{result.anchor} defined by #{result}" unless item
66
+
67
+ return [item, from]
68
+ end
69
+
70
+ i += 2
71
+ end
72
+ [nil, from]
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,304 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PatchYAML
4
+ class Editor
5
+ def run_pipeline
6
+ run_pipeline_once until @pipeline.empty?
7
+ @data
8
+ end
9
+
10
+ private
11
+
12
+ def run_pipeline_once
13
+ op, *opts = @pipeline.shift
14
+ case op
15
+ when :delete
16
+ node_delete(opts[0])
17
+ when :rename
18
+ node_rename(opts[0], opts[1])
19
+ when :map_add
20
+ node_map_add(opts[0], opts[1], opts[2])
21
+ when :update
22
+ node_update(opts[0], opts[1])
23
+ when :seq_add
24
+ node_seq_add(opts[0], opts[1], opts[2])
25
+ else
26
+ raise Error, "patchyaml: Unknown pipeline operation #{op}"
27
+ end
28
+ reload(@data)
29
+ end
30
+
31
+ def start_offset(node)
32
+ @line_sizes[..node.start_line].sum + (node.start_column.positive? ? node.start_column : 0)
33
+ end
34
+
35
+ def end_offset(node)
36
+ @line_sizes[..node.end_line].sum + (node.end_column.positive? ? node.end_column : 0)
37
+ end
38
+
39
+ def node_delete(path)
40
+ value, parent = find(@stream, path)
41
+ case parent
42
+ when Psych::Nodes::Sequence
43
+ start_at = start_offset(value)
44
+ end_at = end_offset(value)
45
+ if parent.style == Psych::Nodes::Sequence::FLOW
46
+ # For flow-based sequences, like [1, 2, 3, 4], ensure we remove
47
+ # any leading spaces and trailing commas, as they are not part
48
+ # of the value itself. However, if the character before the space is
49
+ # a "[", keep the space.
50
+ start_at -= 1 if start_at >= 2 && @data[start_at - 1] == " " && @data[start_at - 2] != "["
51
+ end_at += 1 if @data[end_at] == ","
52
+ else
53
+ # For block-based sequences, we can remove the whole line
54
+ start_at = @line_sizes[..value.start_line].sum
55
+ end_at = @line_sizes[..value.end_line].sum
56
+ end
57
+ @data = @data[...start_at].concat(@data[end_at...])
58
+ when Psych::Nodes::Mapping
59
+ value_index = parent.children.index(value)
60
+ key_index = value_index - 1
61
+ key = parent.children[key_index]
62
+ value = parent.children[value_index]
63
+ start_at = start_offset(key)
64
+ end_at = end_offset(value)
65
+
66
+ if parent.style == Psych::Nodes::Mapping::FLOW
67
+ # For flow-based maps, like { a: 1, b: 2 }, ensure we remove
68
+ # any leading spaces and trailing commas, as they are not part
69
+ # of the k/v
70
+ start_at -= 1 if !start_at.zero? && @data[start_at - 1] == " "
71
+ end_at += 1 if @data[end_at] == ","
72
+ else
73
+ start_at = @line_sizes[..key.start_line].sum
74
+ end_at = if value.end_line == key.start_line
75
+ @line_sizes[..(value.end_line + 1)]
76
+ else
77
+ @line_sizes[..value.end_line]
78
+ end.sum
79
+ end
80
+
81
+ @data = @data[...start_at].concat(@data[end_at...])
82
+ else
83
+ raise Error, "patchyaml: BUG: cannot delete object from #{parent.class}"
84
+ end
85
+ end
86
+
87
+ def dump_yaml(value, indent: 0)
88
+ dump = Psych.dump(value, stringify_names: true).gsub(/---\s?\n?\s*/, "")
89
+ return dump if indent.zero?
90
+
91
+ arr = dump.split("\n")
92
+ ([arr[0]] + arr[1..].map { "#{" " * indent}#{it}" }).join("\n")
93
+ end
94
+
95
+ def node_update(path, new_value)
96
+ value, parent = find(@stream, path)
97
+ case parent
98
+ when Psych::Nodes::Mapping
99
+ update_mapping(value, parent, new_value)
100
+ when Psych::Nodes::Sequence
101
+ update_sequence(value, parent, new_value)
102
+ else
103
+ raise TypeError, "Cannot update value of type #{parent.class}, expected Mapping or Sequence"
104
+ end
105
+ end
106
+
107
+ # TODO: update_* does not take into consideration adding a complex, multiline
108
+ # value into an inline parent. This will certainly break things.
109
+ def update_mapping(value, parent, new_value)
110
+ key_index = parent.children.index(value) - 1
111
+ key = parent.children[key_index]
112
+ start_at = start_offset(value)
113
+ end_at = end_offset(value)
114
+ yaml_value = dump_yaml(new_value, indent: key.start_column + 2)
115
+ indent = if new_value.is_a?(Hash) || (new_value.is_a?(Array) && parent.style != Psych::Nodes::Mapping::FLOW)
116
+ start_at -= 1 while @data[start_at - 1] == " "
117
+ "\n#{" " * (key.start_column + 2)}"
118
+ else
119
+ ""
120
+ end
121
+ @data = @data[...start_at]
122
+ .concat(indent)
123
+ .concat(yaml_value)
124
+ .concat(@data[end_at...])
125
+ end
126
+
127
+ def update_sequence(value, parent, new_value)
128
+ start_at = start_offset(value)
129
+ end_at = end_offset(value)
130
+ end_at -= 1 if @data[end_at - 1] == "\n"
131
+
132
+ if parent.style == Psych::Nodes::Sequence::FLOW
133
+ if new_value.is_a?(Array) || new_value.is_a?(Hash)
134
+ raise Error, "Cannot update node as its parent is in flow-style."
135
+ end
136
+
137
+ yaml_value = dump_yaml(new_value)
138
+ yaml_value = yaml_value.strip
139
+ else
140
+ yaml_value = dump_yaml(new_value)
141
+ yaml_value = "#{yaml_value}\n" unless yaml_value.end_with?("\n")
142
+ yaml_value = "#{yaml_value}#{" " * value.end_column}"
143
+ end
144
+ @data = @data[...start_at]
145
+ .concat(yaml_value)
146
+ .concat(@data[end_at...])
147
+ end
148
+
149
+ def node_rename(path, new_name)
150
+ value, parent = find(@stream, path)
151
+ raise TypeError, "Cannot rename sequence" if parent.is_a? Psych::Nodes::Sequence
152
+
153
+ key_index = parent.children.index(value) - 1
154
+ key = parent.children[key_index]
155
+ start_at = start_offset(key)
156
+ end_at = end_offset(key)
157
+ @data = @data[...start_at].concat(new_name).concat(@data[end_at...])
158
+ end
159
+
160
+ def reindent(value, level:)
161
+ value
162
+ .split("\n")
163
+ .map { "#{" " * level}#{it}" }
164
+ .join("\n")
165
+ end
166
+
167
+ def node_map_add(path, key, value)
168
+ node, = find(@stream, path)
169
+ unless node.is_a?(Psych::Nodes::Mapping)
170
+ raise TypeError, "Cannot add key to non-mapping node of type #{node.class}"
171
+ end
172
+
173
+ encoded_value = dump_yaml(value)
174
+
175
+ # Adding an inline (flow) and block map differs a little. We are currently
176
+ # avoiding adding complex values to inline items, but adding simple
177
+ # values. For an empty node, we can add in our own style (space after
178
+ # and before curlies), otherwise, just add a comma, a space, the
179
+ # key/value, and a trailing space (if the node has a leading space after
180
+ # the curly)
181
+ @data = if node.style == Psych::Nodes::Mapping::FLOW
182
+ node_map_add_inline(node, key, value, encoded_value)
183
+ else
184
+ node_map_add_block(node, key, value, encoded_value)
185
+ end
186
+ end
187
+
188
+ def node_map_add_block(node, key, value, encoded_value)
189
+ indent_level, start_at = if node.children.length.positive?
190
+ [node.children.first.start_column, end_offset(node.children.last)]
191
+ else
192
+ [parent.first.start_column, end_offset(parent)]
193
+ end
194
+
195
+ if value.is_a?(Array) || value.is_a?(Hash)
196
+ encoded_value = reindent(encoded_value, level: indent_level + 2)
197
+ return @data[..start_at]
198
+ .concat("#{" " * indent_level}#{key}:\n#{encoded_value}")
199
+ .concat(@data[start_at...])
200
+ end
201
+
202
+ @data[..start_at]
203
+ .concat("#{" " * indent_level}#{key}: #{encoded_value.strip}")
204
+ .concat(@data[start_at...])
205
+ end
206
+
207
+ def node_map_add_inline(node, key, value, encoded_value)
208
+ raise Error, "Cannot add complex values to inline mapping" if value.is_a?(Hash) || value.is_a?(Array)
209
+
210
+ if node.children.length.positive?
211
+ end_off = end_offset(node.children.last)
212
+ start_at = start_offset(node.children.last)
213
+ start_at -= 1 if @data[start_at] == " "
214
+ return @data[..start_at]
215
+ .concat(", #{key}: #{encoded_value.strip}")
216
+ .concat(@data[end_off...])
217
+ end
218
+
219
+ end_off = end_offset(node)
220
+ start_at = start_offset(node)
221
+ start_at -= 1 if @data[start_at] == " "
222
+ @data[..start_at]
223
+ .concat(" #{key}: #{encoded_value.strip} ")
224
+ .concat(@data[(end_off - 1)...])
225
+ end
226
+
227
+ def node_seq_add(path, value, index)
228
+ node, = find(@stream, path)
229
+ unless node.is_a?(Psych::Nodes::Sequence)
230
+ raise TypeError, "Cannot add item to non-sequence node of type #{node.class}"
231
+ end
232
+
233
+ encoded_value = dump_yaml(value)
234
+
235
+ # Adding an inline (flow) and block map differs a little. We are currently
236
+ # avoiding adding complex values to inline items, but adding simple
237
+ # values. For an empty node, we can add in our own style (space after
238
+ # and before curlies), otherwise, just add a comma, a space, the
239
+ # key/value, and a trailing space (if the node has a leading space after
240
+ # the curly)
241
+ @data = if node.style == Psych::Nodes::Sequence::FLOW
242
+ node_seq_add_inline(node, value, encoded_value, index)
243
+ else
244
+ node_seq_add_block(node, value, encoded_value, index)
245
+ end
246
+ end
247
+
248
+ def node_seq_add_inline(node, value, encoded_value, index)
249
+ raise Error, "Cannot add complex values to inline mapping" if value.is_a?(Hash) || value.is_a?(Array)
250
+
251
+ if node.children.length.positive?
252
+ start_at, prefix, suffix = if index.nil?
253
+ [end_offset(node.children.last), ", ", ""]
254
+ else
255
+ item = node.children[index] || node.children.last
256
+ p, s = item == node.children.last ? [", ", ""] : ["", ", "]
257
+ [start_offset(item), p, s]
258
+ end
259
+ start_at -= 1 if @data[start_at] == " "
260
+ return @data[...start_at]
261
+ .concat(prefix)
262
+ .concat(encoded_value.strip)
263
+ .concat(suffix)
264
+ .concat(@data[start_at...])
265
+ end
266
+
267
+ end_off = end_offset(node)
268
+ start_at = start_offset(node)
269
+ start_at -= 1 if @data[start_at] == " "
270
+ @data[..start_at]
271
+ .concat(" #{encoded_value.strip} ")
272
+ .concat(@data[(end_off - 1)...])
273
+ end
274
+
275
+ def node_seq_add_block(node, value, encoded_value, index)
276
+ indent_level, start_at = if node.children.length.positive?
277
+ start = node.children.first.start_column
278
+ start_off = start_offset(node.children.first)
279
+ until @data[start_off] == "-"
280
+ start_off -= 1
281
+ start -= 1
282
+ end
283
+ ref = index.nil? ? end_offset(node.children.last) : start_offset(node.children[index])
284
+ [start, ref]
285
+ else
286
+ [parent.first.start_column, end_offset(parent)]
287
+ end
288
+ start_at -= 1 until @data[start_at - 1] == "\n" || @data[start_at].nil?
289
+
290
+ if value.is_a?(Array) || value.is_a?(Hash)
291
+ encoded_value = encoded_value.split("\n")
292
+ encoded_value = [encoded_value.first] + encoded_value[1...].map { (" " * (indent_level + 2)).concat(it) }
293
+ encoded_value = encoded_value.join("\n")
294
+ return @data[...start_at]
295
+ .concat("#{" " * indent_level}- #{encoded_value}\n")
296
+ .concat(@data[start_at...])
297
+ end
298
+
299
+ @data[...start_at]
300
+ .concat("#{" " * indent_level}- #{encoded_value.strip}")
301
+ .concat(@data[start_at...])
302
+ end
303
+ end
304
+ end
@@ -0,0 +1,147 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PatchYAML
4
+ class QueryParser
5
+ def self.parse(query) = new(query).parse
6
+
7
+ def initialize(query)
8
+ @path = []
9
+ @pos = 0
10
+ @start = 0
11
+ @query = query.each_char.to_a
12
+ @current_path = nil
13
+ end
14
+
15
+ def peek = @query[@pos]
16
+ def advance = @query[@pos].tap { @pos += 1 }
17
+ def eof? = @pos >= @query.length
18
+ def matches?(char) = peek == char
19
+ def mark = @start = @pos
20
+ def value = @query[@start...@pos].join
21
+
22
+ def digit?(value = nil)
23
+ value = peek if value.nil?
24
+ !value.nil? && value >= "0" && value <= "9"
25
+ end
26
+
27
+ def non_separator?
28
+ peek != "[" && peek != "."
29
+ end
30
+
31
+ def push_path
32
+ if @current_path
33
+ @path << @current_path
34
+ @current_path = nil
35
+ end
36
+
37
+ advance if peek == "."
38
+ mark
39
+ end
40
+
41
+ def parse
42
+ until eof?
43
+ next parse_index if digit?
44
+
45
+ case peek
46
+ when "["
47
+ parse_expression_path
48
+ when "."
49
+ push_path
50
+ else
51
+ parse_simple_path
52
+ end
53
+ end
54
+
55
+ @path
56
+ end
57
+
58
+ def parse_index
59
+ mark
60
+ advance while digit?
61
+ @current_path = { kind: :index, value: value.to_i }
62
+ push_path
63
+ end
64
+
65
+ def parse_expression_path
66
+ raise ArgumentError, "Expected '[', found #{peek} at index #{@pos}" unless peek == "["
67
+
68
+ advance # Consume [
69
+ mark
70
+ advance until peek == "]" || eof?
71
+
72
+ raise ArgumentError, "Unterminated expression path at index #{@pos}" unless peek == "]"
73
+
74
+ v = value
75
+ advance # Consume ]
76
+
77
+ unless v.include? "="
78
+ raise ArgumentError, "Invalid expression path at index #{@start}: Expected expression to be in the format " \
79
+ "key=value"
80
+ end
81
+
82
+ key, value = v.split("=", 2).map(&:strip)
83
+
84
+ value = case
85
+ when digit?(value[0])
86
+ value.to_i
87
+ when ['"', "'"].include?(value[0])
88
+ parse_quoted(value)
89
+ when "true"
90
+ true
91
+ when "false"
92
+ false
93
+ else
94
+ value
95
+ end
96
+
97
+ @current_path = { kind: :expression, key:, value: }
98
+ push_path
99
+ end
100
+
101
+ def parse_simple_path
102
+ mark
103
+ advance until !non_separator? || eof?
104
+ @current_path = { kind: :simple, value: value }
105
+ push_path
106
+ end
107
+
108
+ def parse_quoted(value)
109
+ quote = value[0]
110
+ escaping = false
111
+ v = []
112
+ chars = value[1...].each_char.to_a
113
+
114
+ until chars.empty?
115
+ ch = chars.shift
116
+
117
+ if ch == "\\"
118
+ escaping = true
119
+ next
120
+ end
121
+
122
+ if escaping
123
+ escaping = false
124
+
125
+ case ch
126
+ when quote
127
+ v << quote
128
+ else
129
+ v << "\\"
130
+ v << ch
131
+ end
132
+ next
133
+ end
134
+
135
+ break if ch == quote
136
+
137
+ v << ch
138
+ end
139
+
140
+ unless chars.empty?
141
+ raise ArgumentError, "Invalid expression #{value}: Stray #{chars.shift} after closing #{quote}"
142
+ end
143
+
144
+ v.join
145
+ end
146
+ end
147
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Patchyaml
4
+ VERSION = "0.1.0"
5
+ end
data/lib/patchyaml.rb ADDED
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+
5
+ require_relative "patchyaml/version"
6
+ require_relative "patchyaml/editor"
7
+ require_relative "patchyaml/anchors"
8
+ require_relative "patchyaml/find"
9
+ require_relative "patchyaml/query_parser"
10
+ require_relative "patchyaml/pipeline"
11
+
12
+ module PatchYAML
13
+ class Error < StandardError; end
14
+
15
+ def self.load(data)
16
+ Editor.new(data)
17
+ end
18
+
19
+ def self.load_file(path)
20
+ Editor.new(File.read(path))
21
+ end
22
+ end
metadata ADDED
@@ -0,0 +1,57 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: patchyaml
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Vito Sartori
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 2025-08-05 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: YAML Editor Utility Library
13
+ email:
14
+ - hey@vito.io
15
+ executables: []
16
+ extensions: []
17
+ extra_rdoc_files: []
18
+ files:
19
+ - ".rspec"
20
+ - ".rubocop.yml"
21
+ - CODE_OF_CONDUCT.md
22
+ - LICENSE.txt
23
+ - README.md
24
+ - Rakefile
25
+ - lib/patchyaml.rb
26
+ - lib/patchyaml/anchors.rb
27
+ - lib/patchyaml/editor.rb
28
+ - lib/patchyaml/find.rb
29
+ - lib/patchyaml/pipeline.rb
30
+ - lib/patchyaml/query_parser.rb
31
+ - lib/patchyaml/version.rb
32
+ homepage: https://github.com/heyvito/patchyaml
33
+ licenses:
34
+ - MIT
35
+ metadata:
36
+ allowed_push_host: https://rubygems.org
37
+ homepage_uri: https://github.com/heyvito/patchyaml
38
+ source_code_uri: https://github.com/heyvito/patchyaml
39
+ rubygems_mfa_required: 'true'
40
+ rdoc_options: []
41
+ require_paths:
42
+ - lib
43
+ required_ruby_version: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '3.4'
48
+ required_rubygems_version: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: '0'
53
+ requirements: []
54
+ rubygems_version: 3.6.2
55
+ specification_version: 4
56
+ summary: YAML Editor Utility Library
57
+ test_files: []