Skip to content

Commit

Permalink
Better handling of filename/extension changes.
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed May 4, 2016
1 parent 1d868d1 commit 3ac7e81
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
26 changes: 23 additions & 3 deletions lib/build/files/path.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ module Build
module Files
# Represents a file path with an absolute root and a relative offset:
class Path
def self.split(path)
# Effectively dirname and basename:
dirname, separator, filename = path.rpartition(File::SEPARATOR)
filename, dot, extension = filename.rpartition('.')

return dirname + separator, filename, dot + extension
end

# Returns the length of the prefix which is shared by two strings.
def self.prefix_length(a, b)
[a.size, b.size].min.times{|i| return i if a[i] != b[i]}
Expand Down Expand Up @@ -128,9 +136,21 @@ def rebase(root)
self.class.new(File.join(root, relative_path), root)
end

def with(root: @root, extension: nil)
# self.relative_path should be a string so using + to add an extension should be fine.
relative_path = extension ? self.relative_path + extension : self.relative_path
def with(root: @root, extension: nil, basename: false)
relative_path = self.relative_path

if basename
dirname, filename, _ = self.class.split(relative_path)

# Replace the filename if the basename is supplied:
filename = basename if basename.is_a? String

relative_path = dirname + filename
end

if extension
relative_path = relative_path + extension
end

self.class.new(File.join(root, relative_path), root, relative_path)
end
Expand Down
2 changes: 1 addition & 1 deletion lib/build/files/version.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@

module Build
module Files
VERSION = "1.0.4"
VERSION = "1.0.5"
end
end
14 changes: 14 additions & 0 deletions spec/build/files/path_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,20 @@ module Build::Files::PathSpec
end
end

describe Build::Files::Path.new("/foo/bar.txt") do
it "should replace existing file extension" do
expect(subject.with(extension: '.jpeg', basename: true)).to be == "/foo/bar.jpeg"
end

it "should append file extension" do
expect(subject.with(extension: '.jpeg')).to be == "/foo/bar.txt.jpeg"
end

it "should change basename" do
expect(subject.with(basename: 'baz', extension: '.txt')).to be == "/foo/baz.txt"
end
end

describe Build::Files::Path.new("/foo/bar/baz", "/foo") do
it "should be inspectable" do
expect(subject.inspect).to be_include subject.root.to_s
Expand Down

0 comments on commit 3ac7e81

Please sign in to comment.