From 6f1cff4a1f4eab79ff899bd5ba55212448e4ed7d Mon Sep 17 00:00:00 2001 From: Jason Thomas Date: Thu, 22 Aug 2024 15:40:39 -0600 Subject: [PATCH] Better escaping in TemplateAccessor --- .../lib/openc3/accessors/template_accessor.rb | 13 ++++---- .../spec/accessors/template_accessor_spec.rb | 30 +++++++++++++++++++ 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/openc3/lib/openc3/accessors/template_accessor.rb b/openc3/lib/openc3/accessors/template_accessor.rb index aec3b2cb58..21b82178cf 100644 --- a/openc3/lib/openc3/accessors/template_accessor.rb +++ b/openc3/lib/openc3/accessors/template_accessor.rb @@ -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 diff --git a/openc3/spec/accessors/template_accessor_spec.rb b/openc3/spec/accessors/template_accessor_spec.rb index 41dfae3a5b..d335cb612f 100644 --- a/openc3/spec/accessors/template_accessor_spec.rb +++ b/openc3/spec/accessors/template_accessor_spec.rb @@ -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 , ($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