From 4f3ca207415a31e28249f0ebb36a659aacc89e41 Mon Sep 17 00:00:00 2001 From: Michael Miller Date: Sat, 23 Mar 2019 20:47:41 -0600 Subject: [PATCH] Parse source strings --- spec/source_spec.cr | 19 +++++++++++++++++++ src/spectator/source.cr | 12 ++++++++++++ 2 files changed, 31 insertions(+) diff --git a/spec/source_spec.cr b/spec/source_spec.cr index a4643e1..1ad6950 100644 --- a/spec/source_spec.cr +++ b/spec/source_spec.cr @@ -54,4 +54,23 @@ describe Spectator::Source do source.to_s.should match(/^(.+?)\:(\d+)$/) end end + + describe "#parse" do + it "gets the absolute path" do + file = "foo.cr" + path = File.expand_path(file) + source = Spectator::Source.parse("#{file}:42") + source.file.should eq(path) + end + + it "gets the relative path" do + source = Spectator::Source.parse("foo.cr:42") + source.path.should eq("foo.cr") + end + + it "gets the line number" do + source = Spectator::Source.parse("foo.cr:42") + source.line.should eq(42) + end + end end diff --git a/src/spectator/source.cr b/src/spectator/source.cr index 77dc19a..fa8935d 100644 --- a/src/spectator/source.cr +++ b/src/spectator/source.cr @@ -11,6 +11,18 @@ module Spectator def initialize(@file, @line) end + # Parses a source from a string. + def self.parse(string) + # Make sure to handle multiple colons. + # If this ran on Windows, there's a possibility of a colon in the path. + # The last element should always be the line number. + parts = string.split(':') + path = parts[0...-1].join(':') + line = parts.last + file = File.expand_path(path) + self.new(file, line.to_i) + end + # The relative path to the file from the current directory. # If the file isn't in the current directory or a sub-directory, # then the absolute path is provided.