diff --git a/CHANGELOG.md b/CHANGELOG.md index 54eb3da8..c664719e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning]. - New question: AddAllcontributors to add a section and config for (#26) - `copy`, `recopy` and `update` from the copier API (#142) - When applying to existing projects, read Project.toml to infer a few values (#116) +- Automatically determines the `PackageName` from the destination folder (#151) ### Changed diff --git a/src/COPIERTemplate.jl b/src/COPIERTemplate.jl index 075185b7..e0f97b84 100644 --- a/src/COPIERTemplate.jl +++ b/src/COPIERTemplate.jl @@ -37,6 +37,14 @@ function generate(src_path, dst_path, data::Dict = Dict(); kwargs...) end data = merge(existing_data, data) end + # If the PackageName was not given or guessed from the Project.toml, use the sanitized path + if !haskey(data, "PackageName") + package_name = _sanitize_package_name(dst_path) + if package_name != "" + @info "Using sanitized path $package_name as package name" + data["PackageName"] = package_name + end + end Copier.copy(src_path, dst_path, data; kwargs...) end @@ -72,4 +80,16 @@ function _read_data_from_existing_path(dst_path) return data end +""" + package_name = _sanitize_package_name(path) + +Sanitize the `path` to guess the package_name by looking at the +base name and removing an extension. If the result is not a valid +identifier, returns "". +""" +function _sanitize_package_name(dst_path) + package_name = dst_path |> basename |> splitext |> first + return Base.isidentifier(package_name) ? package_name : "" +end + end diff --git a/test/runtests.jl b/test/runtests.jl index 3d6fffd5..f12d5473 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -147,7 +147,6 @@ end mktempdir(TMPDIR; prefix = "existing_") do dir_existing cd(dir_existing) do Pkg.generate("NewPkg") - @info walkdir(".") |> collect COPIERTemplate.generate( template_path, "NewPkg/", @@ -163,4 +162,31 @@ end @test answers["PackageOwner"] == "test" end end + + @testset "Test automatic guessing the package name from the path" begin + mktempdir(TMPDIR; prefix = "path_is_dir_") do dir_path_is_dir + cd(dir_path_is_dir) do + data = Dict(key => value for (key, value) in template_options if key != "PackageName") + mkdir("some_folder") + COPIERTemplate.generate( + template_path, + "some_folder/SomePackage1.jl", + data; + quiet = true, + vcs_ref = "HEAD", + ) + answers = YAML.load_file("some_folder/SomePackage1.jl/.copier-answers.yml") + @test answers["PackageName"] == "SomePackage1" + COPIERTemplate.generate( + template_path, + "some_folder/SomePackage2.jl", + merge(data, Dict("PackageName" => "OtherName")); + quiet = true, + vcs_ref = "HEAD", + ) + answers = YAML.load_file("some_folder/SomePackage2.jl/.copier-answers.yml") + @test answers["PackageName"] == "OtherName" + end + end + end end