FilePathsBase.jl icon indicating copy to clipboard operation
FilePathsBase.jl copied to clipboard

`replace` fails for file paths

Open omus opened this issue 3 years ago • 4 comments

julia> using FilePathsBase

julia> replace(PosixPath("/a/b/c"), "b" => "c")
ERROR: MethodError: no method matching similar(::PosixPath, ::Type{String})
Closest candidates are:
  similar(::Union{LinearAlgebra.Adjoint{T, var"#s814"}, LinearAlgebra.Transpose{T, var"#s814"}} where {T, var"#s814"<:(AbstractVector{T} where T)}, ::Type{T}) where T at /Users/omus/Development/Julia/x86_64/1.6/usr/share/julia/stdlib/v1.6/LinearAlgebra/src/adjtrans.jl:230
  similar(::Union{LinearAlgebra.Adjoint{T, S}, LinearAlgebra.Transpose{T, S}} where {T, S}, ::Type{T}) where T at /Users/omus/Development/Julia/x86_64/1.6/usr/share/julia/stdlib/v1.6/LinearAlgebra/src/adjtrans.jl:234
  similar(::Union{LinearAlgebra.Adjoint{T, S}, LinearAlgebra.Transpose{T, S}} where {T, S}, ::Type{T}, ::Tuple{Vararg{Int64, N}}) where {T, N} at /Users/omus/Development/Julia/x86_64/1.6/usr/share/julia/stdlib/v1.6/LinearAlgebra/src/adjtrans.jl:235
  ...
Stacktrace:
 [1] _similar_or_copy(x::PosixPath, #unused#::Type{String})
   @ Base ./set.jl:444
 [2] replace(A::PosixPath, old_new::Pair{String, String}; count::Nothing)
   @ Base ./set.jl:559
 [3] replace(A::PosixPath, old_new::Pair{String, String})
   @ Base ./set.jl:556
 [4] top-level scope
   @ REPL[6]:1

omus avatar Jan 13 '22 16:01 omus

My current work around:

julia> using FilePathsBase

julia> replace(p::P, args...; kwargs...) where P <: AbstractPath = P(replace(string(p), args...; kwargs...))
replace (generic function with 1 method)

julia> replace(args...; kwargs...) = Base.replace(args...; kwargs...)
replace (generic function with 2 methods)

julia> replace(PosixPath("/a/b/c"), "b" => "c")
p"/a/c/c"

omus avatar Jan 13 '22 16:01 omus

FWIW, I think if we were to support this we'd have the same behaviour as a collection of strings.

julia> replace(("a", "b", "c"), "b" => "d")
("a", "d", "c")

rofinn avatar Jan 13 '22 19:01 rofinn

FWIW, I think if we were to support this we'd have the same behaviour as a collection of strings.

You mean not treating the path as a string but rather doing replacement on each component of the path?

omus avatar Jan 13 '22 19:01 omus

That's correct. I think random string operations should be reserved for subtypes of AbstractString. I also intentionally don't support startswith, endswith, regex matching, etc.

rofinn avatar Jan 13 '22 23:01 rofinn