Method: Hocon::Impl::ConfigNodeObject#change_value_on_path

Defined in:
lib/hocon/impl/config_node_object.rb

#change_value_on_path(desired_path, value, flavor) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/hocon/impl/config_node_object.rb', line 41

def change_value_on_path(desired_path, value, flavor)
  children_copy = @children.clone
  seen_non_matching = false
  # Copy the value so we can change it to null but not modify the original parameter
  value_copy = value
  i = children_copy.size
  while i >= 0 do
    if children_copy[i].is_a?(Hocon::Impl::ConfigNodeSingleToken)
      t = children_copy[i].token
      # Ensure that, when we are removing settings in JSON, we don't end up with a trailing comma
      if flavor.equal?(ConfigSyntax::JSON) && !seen_non_matching && t.equal?(Tokens::COMMA)
        children_copy.delete_at(i)
      end
      i -= 1
      next
    elsif !children_copy[i].is_a?(Hocon::Impl::ConfigNodeField)
      i -= 1
      next
    end
    node = children_copy[i]
    key = node.path.value

    # Delete all multi-element paths that start with the desired path, since technically they are duplicates
    if (value_copy.nil? && key == desired_path) || (key.starts_with(desired_path) && !(key == desired_path))
      children_copy.delete_at(i)
      # Remove any whitespace or commas after the deleted setting
      j = i
      while j < children_copy.size
        if children_copy[j].is_a?(Hocon::Impl::ConfigNodeSingleToken)
          t = children_copy[j].token
          if Tokens.ignored_whitespace?(t) || t.equal?(Tokens::COMMA)
            children_copy.delete_at(j)
            j -= 1
          else
            break
          end
        else
          break
        end
        j += 1
      end
    elsif key == desired_path
      seen_non_matching = true
      before = i - 1 > 0 ? children_copy[i - 1] : nil
      if value.is_a?(Hocon::Impl::ConfigNodeComplexValue) && before.is_a?(Hocon::Impl::ConfigNodeSingleToken) &&
          Tokens.ignored_whitespace?(before.token)
        indented_value = value.indent_text(before)
      else
        indented_value = value
      end
      children_copy[i] = node.replace_value(indented_value)
      value_copy = nil
    elsif desired_path.starts_with(key)
      seen_non_matching = true
      if node.value.is_a?(self.class)
        remaining_path = desired_path.sub_path_to_end(key.length)
        children_copy[i] = node.replace_value(node.value.change_value_on_path(remaining_path, value_copy, flavor))
        if !value_copy.nil? && !(node == @children[i])
          value_copy = nil
        end
      end
    else
      seen_non_matching = true
    end
    i -= 1
  end
  self.class.new(children_copy)
end