Skip to content

Commit 4246e3d

Browse files
only keep latest usage per object
1 parent 2821f9c commit 4246e3d

File tree

1 file changed

+34
-11
lines changed

1 file changed

+34
-11
lines changed

src/Types.jl

Lines changed: 34 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -459,34 +459,57 @@ end
459459
function write_env_usage(source_file::AbstractString, usage_filepath::AbstractString)
460460
# Don't record ghost usage
461461
!isfile(source_file) && return
462-
463462
# Ensure that log dir exists
464463
!ispath(logdir()) && mkpath(logdir())
465464

466-
# Generate entire entry as a string first
467-
entry = sprint() do io
468-
TOML.print(io, Dict(source_file => [Dict("time" => now())]))
469-
end
465+
p = TOML.Parser()
466+
usage_file = joinpath(logdir(), usage_filepath)
467+
timestamp = now()
470468

471469
## Atomically write usage file
472-
usage_file = joinpath(logdir(), usage_filepath)
473470
while true
474471
# read existing usage file
475-
existing_usage = isfile(usage_file) ? read(usage_file, String) : ""
472+
usage = if isfile(usage_file)
473+
content = read(usage_file)
474+
Base.TOML.reinit!(p, String(content); filepath=usage_file)
475+
Base.TOML.parse(p)
476+
else
477+
Dict()
478+
end
479+
480+
# record new usage
481+
usage[source_file] = [Dict("time" => timestamp)]
482+
483+
# keep only latest usage info
484+
for kv in usage
485+
times = map(d->Dates.DateTime(d["time"]), usage[kv.first])
486+
usage[kv.first] = [Dict("time" => maximum(times))]
487+
end
476488

477489
# Write to a temp file in the same directory as the destination
478490
temp_usage_file = tempname(logdir())
479491
open(temp_usage_file, "w") do io
480-
write(io, existing_usage)
481-
write(io, entry)
492+
TOML.print(io, usage, sorted=true)
482493
end
483494

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

487498
# Check that the new file has what we want in it
488-
new_usage = read(usage_file, String)
489-
occursin(entry, new_usage) && break
499+
new_usage = if isfile(usage_file)
500+
content = read(usage_file)
501+
Base.TOML.reinit!(p, String(content); filepath=usage_file)
502+
Base.TOML.parse(p)
503+
else
504+
Dict()
505+
end
506+
if haskey(new_usage, source_file)
507+
for e in new_usage[source_file]
508+
if Dates.DateTime(e["time"]) >= timestamp
509+
return
510+
end
511+
end
512+
end
490513
# If not, try again
491514
end
492515

0 commit comments

Comments
 (0)