Skip to content

Instantly share code, notes, and snippets.

@jiphex
Last active December 17, 2015 07:59
Show Gist options
  • Save jiphex/5576878 to your computer and use it in GitHub Desktop.
Save jiphex/5576878 to your computer and use it in GitHub Desktop.
Sorts a bunch of lines like this: Redirect 301 /foo/bar http://stuff Redirect 301 /foo/bar/baz/ http://stuff in a way that means that the more-specific paths appear after the shorter ones, with some intelligence.
#!/usr/bin/env ruby1.9
# Sorts a bunch of lines like this:
# Redirect 301 /foo/bar http://stuff
# Redirect 301 /foo/bar/baz/ http://stuff
# in a way that means that the more-specific paths appear before the
# shorter ones, with some intelligence.
require 'set'
class Redirect
include Comparable
attr_reader :cmd,:status,:url,:dest,:line
def initialize(line)
@line = line
(@cmd,@status,@url,@dest) = line.split
end
def <=>(other)
my_set = Set.new(@url.split("/"))
their_set = Set.new(other.url.split("/"))
if my_set.subset? their_set
return -1
elsif their_set.subset? my_set
return 1
else
return @url<=>other.url
end
end
end
ARGF.readlines.map{|a|Redirect.new(a)}.sort.reverse.each do |a|
puts a.line
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment