Skip to content
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 49 additions & 9 deletions src/Types.jl
Original file line number Diff line number Diff line change
Expand Up @@ -459,20 +459,60 @@ end
function write_env_usage(source_file::AbstractString, usage_filepath::AbstractString)
# Don't record ghost usage
!isfile(source_file) && return

# Ensure that log dir exists
!ispath(logdir()) && mkpath(logdir())

# Generate entire entry as a string first
entry = sprint() do io
TOML.print(io, Dict(source_file => [Dict("time" => now())]))
end

# Append entry to log file in one chunk
p = TOML.Parser()
usage_file = joinpath(logdir(), usage_filepath)
open(usage_file, append=true) do io
write(io, entry)
timestamp = now()

## Atomically write usage file
while true
# read existing usage file
usage = if isfile(usage_file)
content = read(usage_file)
Base.TOML.reinit!(p, String(content); filepath=usage_file)
Base.TOML.parse(p)
else
Dict()
end

# record new usage
usage[source_file] = [Dict("time" => timestamp)]

# keep only latest usage info
for kv in usage
times = map(d->Dates.DateTime(d["time"]), usage[kv.first])
usage[kv.first] = [Dict("time" => maximum(times))]
end

# Write to a temp file in the same directory as the destination
temp_usage_file = tempname(logdir())
open(temp_usage_file, "w") do io
TOML.print(io, usage, sorted=true)
end

# Move the temp file into place, replacing the original
mv(temp_usage_file, usage_file, force = true)

# Check that the new file has what we want in it
new_usage = if isfile(usage_file)
content = read(usage_file)
Base.TOML.reinit!(p, String(content); filepath=usage_file)
Base.TOML.parse(p)
else
Dict()
end
if haskey(new_usage, source_file)
for e in new_usage[source_file]
if Dates.DateTime(e["time"]) >= timestamp
return
end
end
end
# If not, try again
end

end

function read_package(path::String)
Expand Down