Skip to content

Commit

Permalink
Merge pull request #1495 from OpenC3/accessor_escape
Browse files Browse the repository at this point in the history
Better escaping in TemplateAccessor
  • Loading branch information
jmthomas authored Aug 23, 2024
2 parents a099866 + 6f1cff4 commit e118fcf
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 8 deletions.
13 changes: 5 additions & 8 deletions openc3/lib/openc3/accessors/template_accessor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,21 +38,18 @@ def configure
# Convert the template into a Regexp for reading each item
template = @packet.template.dup
template_items = template.scan(Regexp.new("#{escaped_left_char}.*?#{escaped_right_char}"))
escaped_read_template = template
if @left_char != '('
escaped_read_template = escaped_read_template.gsub('(', '\(')
end
if @right_char != ')'
escaped_read_template = escaped_read_template.gsub(')', '\)')
end
escaped_read_template = Regexp.escape(template)

@item_keys = []
template_items.each do |item|
@item_keys << item[1..-2]
# If they're using parens we have to escape them
# since we're working with the already escaped template
item = "\\#{item}" if @left_char == '('
item = "#{item[0..-2]}\\)" if @right_char == ')'
escaped_read_template.gsub!(item, "(.*)")
end
@read_regexp = Regexp.new(escaped_read_template)

@configured = true
end

Expand Down
30 changes: 30 additions & 0 deletions openc3/spec/accessors/template_accessor_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,36 @@ module OpenC3
end

describe "read_item and read_items" do
it "should escape regexp chars" do
packet = Packet.new
packet.template = 'VOLT <VOLTAGE>, ($1); VOLT? (+1)'
data = 'VOLT 5, ($1); VOLT? (+1)'
accessor = TemplateAccessor.new(packet)
packet.buffer = data

item1 = OpenStruct.new
item1.name = 'VOLTAGE'
item1.key = 'VOLTAGE'
item1.data_type = :FLOAT
value = accessor.read_item(item1, packet.buffer(false))
expect(value).to eq 5.0
end

it "should allow different delimiters" do
packet = Packet.new
packet.template = 'VOLT (VOLTAGE), *1.0; VOLT? *1.0'
data = 'VOLT 5, *1.0; VOLT? *1.0'
accessor = TemplateAccessor.new(packet, '(', ')')
packet.buffer = data

item1 = OpenStruct.new
item1.name = 'VOLTAGE'
item1.key = 'VOLTAGE'
item1.data_type = :FLOAT
value = accessor.read_item(item1, packet.buffer(false))
expect(value).to eq 5.0
end

it "should read values" do
accessor = TemplateAccessor.new(@packet)
@packet.buffer = @data
Expand Down

0 comments on commit e118fcf

Please sign in to comment.