PseudoAtomicOrbitalsDatasets / make_artifacts.jl
qiaojunfeng's picture
Initial datasets: Si, Cu, Pt, Bi, CrI3
506ffc1
Raw History Blame Contribute Delete
5.68 kB
#!/usr/bin/env -S julia --project
# Generate `artifacts/*.tar.gz` and `Artifacts.toml` from `datasets/*/`.
#
# julia --project make_artifacts.jl dryrun # list folders to (re)pack
# julia --project make_artifacts.jl # pack, with Hugging Face URLs
# julia --project make_artifacts.jl local # pack, with file:// URLs (local tests)
#
# Adapted from `make_artifacts.jl` of WannierDatasets.
# Artifacts docs: https://pkgdocs.julialang.org/v1/artifacts/
using Pkg
Pkg.instantiate()
using Tar, Inflate, SHA, TOML
using Dates: unix2datetime
const artifacts_dir = joinpath(@__DIR__, "artifacts")
const datasets_dir = joinpath(@__DIR__, "datasets")
const deploy_branch = "artifacts"
const base_url = "https://huggingface.co/datasets/atomology/PseudoAtomicOrbitalsDatasets/resolve/$(deploy_branch)"
"""
Create the artifact tarball of `datasets/<folder>` and return its
`Artifacts.toml` entry. `local_url = true` writes a file:// URL, for testing.
"""
function create_artifact(folder::AbstractString; local_url::Bool = false)
fullpath = joinpath(datasets_dir, folder)
isdir(fullpath) || return
mkpath(artifacts_dir)
# `inputs/` holds files used to generate a dataset, not the dataset. The
# README is kept: it carries the license notices of the pseudopotentials.
tar_excludes = ["inputs", ".gitignore"]
# Use pigz for parallel compression when available
compress_prog = Sys.which("pigz") === nothing ? "gzip -9" : "pigz -9 -k"
tar_cmd = [
Sys.isapple() ? "gtar" : "tar",
"--exclude-vcs",
"--exclude-vcs-ignores",
"--use-compress-program=$compress_prog",
]
append!(tar_cmd, ["--exclude=" * f for f in tar_excludes])
tar_name = "$(folder).tar.gz"
outpath = joinpath(artifacts_dir, tar_name)
cd(fullpath) do
run(Cmd(vcat(tar_cmd, ["-cvf", outpath], readdir())))
end
url = local_url ? "file://$(outpath)" : "$(base_url)/$(tar_name)"
entry = Dict(
"git-tree-sha1" => Tar.tree_hash(IOBuffer(inflate_gzip(outpath))),
"lazy" => true,
"download" => [Dict("url" => url, "sha256" => bytes2hex(open(sha256, outpath)))],
)
buf = IOBuffer()
TOML.print(buf, Dict(folder => entry))
@info "New artifact:\n$(String(take!(buf)))"
return folder => entry
end
"""Hash of the latest commit that touched `path`."""
function git_hash(path::AbstractString; branch::AbstractString = "HEAD")
return read(`git log -n 1 --pretty=format:"%H" $branch -- "$path"`, String)
end
"""Date of a git commit."""
function git_date(githash::AbstractString)
timestamp = strip(read(`git show -s --format=%ct $githash`, String))
return unix2datetime(parse(Float64, timestamp))
end
"""Files of a git tree."""
function git_lstree(
path::AbstractString; args::AbstractVector{<:AbstractString} = String[],
branch::AbstractString = "HEAD",
)
output = chomp(read(`git ls-tree $args --name-only $branch -- "$path"`, String))
isempty(output) && return String[]
return split(output, '\n')
end
"""Tarballs on the deploy branch, with the commit that last touched each."""
function list_previous_artifacts()
files = try
git_lstree("."; args = ["-r"], branch = deploy_branch)
catch e
@warn "Failed to list previous artifacts. Create the deploy branch once \
with `git branch $(deploy_branch)`."
rethrow(e)
end
filter!(f -> endswith(f, ".tar.gz"), files)
return Dict(f => git_hash(f; branch = deploy_branch) for f in files)
end
"""
Folders of `datasets/` committed on `main` that are newer than their tarball
on the deploy branch.
"""
function list_new_folders()
prev_artifacts = list_previous_artifacts()
new_folders = String[]
# Exactly `datasets/`, relative and with a trailing slash, to list subfolders
dirs = map(basename, git_lstree(basename(datasets_dir) * "/"; branch = "main"))
for data in dirs
startswith(data, "_") && continue
startswith(data, ".") && continue
isdir(joinpath(datasets_dir, data)) || continue
dir_hash = git_hash(joinpath(basename(datasets_dir), data))
artifact_hash = get(prev_artifacts, "$(data).tar.gz", nothing)
if !isnothing(artifact_hash)
git_date(dir_hash) <= git_date(artifact_hash) && continue
end
push!(new_folders, data)
end
return new_folders
end
"""Remove and recreate `artifacts_dir`, after confirmation."""
function clean_artifacts_dir()
print("I will clean the `$(artifacts_dir)` folder [y/N]: ")
if lowercase(readline()) != "y"
println("Aborting...")
return false
end
rm(artifacts_dir; force = true, recursive = true)
mkpath(artifacts_dir)
println("Cleaned `$(artifacts_dir)` folder.")
return true
end
"""`Artifacts.toml` of the deploy branch, empty if there is none."""
function read_artifact_toml()
return try
TOML.parse(read(`git show $(deploy_branch):Artifacts.toml`, String))
catch
Dict{String,Any}()
end
end
function (@main)(args)
artifacts = read_artifact_toml()
new_folders = list_new_folders()
if isempty(new_folders)
println("No new folders to process.")
return
end
if "dryrun" in args
println("New folders to process:")
foreach(folder -> println("- $folder"), new_folders)
return
end
clean_artifacts_dir() || return
local_url = "local" in args
for folder in new_folders
# existing entries are replaced
push!(artifacts, create_artifact(folder; local_url))
end
open("Artifacts.toml", "w") do io
TOML.print(io, artifacts)
end
end