Skip to content

Instantly share code, notes, and snippets.

@StefanKarpinski
Created December 28, 2012 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StefanKarpinski/4402701 to your computer and use it in GitHub Desktop.
Save StefanKarpinski/4402701 to your computer and use it in GitHub Desktop.
abstract Path
@unix_only begin
const separator = "/"
const separator_regex = r"/+"
end
@windows_only begin
const separator = "\\"
const separator_regex = r"[/\\]"
end
const isabs_regex = Regex( OS_NAME != :Windows ?
strcat(L"^(?:", separator_regex.pattern, L")(.*)$") :
strcat(L"^(?:^(\w+):|", separator_regex.pattern, L")(.*)$")
)
function normalize_path!(parts::Vector{ByteString})
i = 1
while i <= length(parts)
if parts[i] == ".." && i > 1 && parts[i-1] != ".."
del(parts,i-1:i)
i -= 1
elseif parts[i] == "."
del(parts,i)
else
i += 1
end
end
return parts
end
type AbsPath <: Path
# @windows_only drive::ByteString # ??
parts::Vector{ByteString}
function AbsPath(parts::Vector{ByteString})
while !isempty(parts) && (parts[1] == ".." || parts[1] == ".")
shift(parts)
end
new(normalize_path!(parts))
end
end
type RelPath <: Path
parts::Vector{ByteString}
RelPath(parts::Vector{ByteString}) = new(normalize_path!(parts))
end
AbsPath(v::Vector) = AbsPath(ByteString[bytestring(x) for x in v])
RelPath(v::Vector) = RelPath(ByteString[bytestring(x) for x in v])
function path(p::ByteString)
m = match(isabs_regex, p)
if m != nothing
parts = split(m.captures[end], separator_regex)
AbsPath(m.captures[1:end-1]..., parts)
else
RelPath(split(p, separator_regex))
end
end
macro p_str(p) path(p) end
@unix_only prefix(p::AbsPath) = "/"
@windows_only prefix(p::AbsPath) = "$(p.drive):"
show(io::IO, p::AbsPath) = show(io, prefix(p)*join(p.parts,separator))
show(io::IO, p::RelPath) = show(io, join(p.parts,separator))
isabspath(p::AbsPath) = true
isabspath(p::RelPath) = false
isabspath(p::String) = isabspath(path(p))
length(p::Path) = length(p.parts)
ref(p::Path, i::Integer) = p.parts[i]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment