reclaimable 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/.claude/launch.json +11 -0
- data/.gitignore +11 -0
- data/.gitlab-ci.yml +16 -0
- data/AGENTS.md +88 -0
- data/CLAUDE.md +1 -0
- data/Gemfile +3 -0
- data/LICENSE +674 -0
- data/README.md +160 -0
- data/Rakefile +28 -0
- data/ai-skill/reclaimable/SKILL.md +94 -0
- data/benchmark/README.md +59 -0
- data/benchmark/experiments/lstat_scanner.rb +11 -0
- data/benchmark/experiments/ractor_scanner.rb +92 -0
- data/benchmark/experiments/verify_bulk_list.rb +34 -0
- data/benchmark/lib/fixture.rb +104 -0
- data/benchmark/lib/results.rb +62 -0
- data/benchmark/reports/00-baseline.md +75 -0
- data/benchmark/reports/01-jit.md +70 -0
- data/benchmark/reports/02-ractor.md +58 -0
- data/benchmark/reports/03-getattrlistbulk.md +84 -0
- data/benchmark/reports/04-others.md +52 -0
- data/benchmark/reports/05-outside-root.md +56 -0
- data/benchmark/reports/06-round2-discussion.md +374 -0
- data/benchmark/reports/06-round2.md +194 -0
- data/benchmark/reports/README.md +46 -0
- data/benchmark/results/baseline.yml +126 -0
- data/benchmark/results/bulk-list.yml +126 -0
- data/benchmark/results/final-yjit.yml +126 -0
- data/benchmark/results/final.yml +126 -0
- data/benchmark/results/ractor-exp.yml +38 -0
- data/benchmark/results/round2-after.yml +126 -0
- data/benchmark/results/round2-before.yml +126 -0
- data/benchmark/results/src-baseline.yml +32 -0
- data/benchmark/results/src-bulk-list.yml +32 -0
- data/benchmark/results/src-pair-none1.yml +38 -0
- data/benchmark/results/src-pair-none2.yml +38 -0
- data/benchmark/results/src-pair-yjit1.yml +38 -0
- data/benchmark/results/src-pair-yjit2.yml +38 -0
- data/benchmark/results/src-ractor-exp.yml +32 -0
- data/benchmark/results/src-round2-after1.yml +52 -0
- data/benchmark/results/src-round2-after2.yml +52 -0
- data/benchmark/results/src-round2-before1.yml +52 -0
- data/benchmark/results/src-round2-before2.yml +52 -0
- data/benchmark/results/yjit.yml +126 -0
- data/benchmark/results/zjit.yml +126 -0
- data/benchmark/run.rb +149 -0
- data/bin/reclaimable +10 -0
- data/doc/performance.md +179 -0
- data/lib/reclaimable/ai_skill.rb +138 -0
- data/lib/reclaimable/bulk_list.rb +91 -0
- data/lib/reclaimable/cache_dump.rb +125 -0
- data/lib/reclaimable/cli.rb +168 -0
- data/lib/reclaimable/cloud_files.rb +33 -0
- data/lib/reclaimable/config.rb +100 -0
- data/lib/reclaimable/i18n.rb +24 -0
- data/lib/reclaimable/locations.rb +89 -0
- data/lib/reclaimable/output.rb +154 -0
- data/lib/reclaimable/paths.rb +36 -0
- data/lib/reclaimable/report.rb +504 -0
- data/lib/reclaimable/ruby_abi.rb +69 -0
- data/lib/reclaimable/scan_cache.rb +97 -0
- data/lib/reclaimable/scanner.rb +440 -0
- data/lib/reclaimable/util.rb +34 -0
- data/lib/reclaimable.rb +42 -0
- data/locale/ja/LC_MESSAGES/reclaimable.mo +0 -0
- data/man/reclaimable.1.ronn +302 -0
- data/man/reclaimable.en.1 +234 -0
- data/man/reclaimable.ja.1 +452 -0
- data/po/ja/reclaimable-docs.po +668 -0
- data/po/ja/reclaimable.po +510 -0
- data/rakelib/benchmark.rake +22 -0
- data/rakelib/docs/japanese.rb +132 -0
- data/rakelib/docs/man_page.rb +73 -0
- data/rakelib/docs/site.rb +187 -0
- data/rakelib/docs/sources.rb +94 -0
- data/rakelib/docs/translation.rb +157 -0
- data/rakelib/docs.rake +62 -0
- data/rakelib/gettext.rake +30 -0
- data/rakelib/i18n.rake +199 -0
- data/reclaimable.gemspec +56 -0
- data/site/index.md +142 -0
- data/site/layout.html.erb +60 -0
- data/site/style.css +82 -0
- metadata +231 -0
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
module Reclaimable
|
|
2
|
+
# 走査して、節ごとにレポートを書き出す。節の並びは run を参照
|
|
3
|
+
class Report
|
|
4
|
+
include Util
|
|
5
|
+
include I18n
|
|
6
|
+
|
|
7
|
+
# docker の「1.23GB」「512MB」「12.3kB」のような 10 進単位のサイズをバイト数に直すための表
|
|
8
|
+
DECIMAL_UNITS = { "B" => 1, "kB" => 1e3, "KB" => 1e3, "MB" => 1e6, "GB" => 1e9, "TB" => 1e12 }.freeze
|
|
9
|
+
|
|
10
|
+
# 走査と関係なく結果が決まる外部コマンド。走査の前に裏で始めておき(prefetch)、節では結果を受け取るだけにする。
|
|
11
|
+
# 始めるときと受け取るときで引数が食い違わないよう、ここにまとめる
|
|
12
|
+
BREW_CLEANUP = %w[brew cleanup -n].freeze
|
|
13
|
+
OLLAMA_LIST = %w[ollama list].freeze
|
|
14
|
+
RUSTUP_TOOLCHAINS = %w[rustup toolchain list].freeze
|
|
15
|
+
SIMCTL_UNAVAILABLE = %w[xcrun simctl list devices unavailable].freeze
|
|
16
|
+
TMUTIL_SNAPSHOTS = %w[tmutil listlocalsnapshots /].freeze
|
|
17
|
+
DOCKER_CONTEXTS = ["docker", "context", "ls", "--format", "{{.Name}}"].freeze
|
|
18
|
+
|
|
19
|
+
# opts: CLI#parse の結果。started: 起動した時刻(所要時間の表示用)。config: 設定ファイル(Config)
|
|
20
|
+
def initialize(opts, output:, started:, config: Config.new(nil))
|
|
21
|
+
@config = config
|
|
22
|
+
@frozen = config.frozen
|
|
23
|
+
@frozen_sizes = config.frozen_sizes
|
|
24
|
+
@top = opts[:top]
|
|
25
|
+
@root = opts[:root]
|
|
26
|
+
@min_mb = opts[:min_mb]
|
|
27
|
+
@jobs = opts[:jobs]
|
|
28
|
+
@fresh = opts[:fresh]
|
|
29
|
+
@cache_dir = opts[:cache_dir]
|
|
30
|
+
@output = output
|
|
31
|
+
@started = started
|
|
32
|
+
# 巨大ファイルの下限と、コンテナのディスクイメージ用の下限(100MB)の小さい方で記録しておく
|
|
33
|
+
@big_record = [@min_mb * MB, 100 * MB].min
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def run
|
|
37
|
+
log format(_("Start: ruby %{ruby} / root %{root} / top %{top} / large files %{min_mb}MB or more"),
|
|
38
|
+
ruby: RUBY_VERSION, root: @root, top: @top, min_mb: @min_mb)
|
|
39
|
+
prefetch
|
|
40
|
+
@known = Locations.known(@output)
|
|
41
|
+
@container_dirs = Locations.container_dirs
|
|
42
|
+
@gem_dirs = Locations.gem_dirs
|
|
43
|
+
@skip = []
|
|
44
|
+
if (why = CloudFiles.stop_downloads)
|
|
45
|
+
# ダウンロードを止められないと、クラウド上のみのフォルダーを読んだところで止まりうるので、その一帯に降りない
|
|
46
|
+
@skip = CloudFiles::DIRS
|
|
47
|
+
notice format(_("Cannot stop downloading cloud-only files, so %{dirs} will not be scanned (%{reason})"),
|
|
48
|
+
dirs: @skip.map { tilde(it) }.join(p_("list separator", ", ")), reason: why)
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
disk
|
|
52
|
+
scan
|
|
53
|
+
folders
|
|
54
|
+
regenerable
|
|
55
|
+
artifacts
|
|
56
|
+
ruby_gems
|
|
57
|
+
containers
|
|
58
|
+
big_files
|
|
59
|
+
time_machine
|
|
60
|
+
tool_estimates
|
|
61
|
+
frozen_folders
|
|
62
|
+
unreadable
|
|
63
|
+
finish
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
private
|
|
67
|
+
|
|
68
|
+
def puts(...) = @output.report.puts(...)
|
|
69
|
+
def log(msg) = @output.log(msg)
|
|
70
|
+
def notice(msg) = @output.notice(msg)
|
|
71
|
+
def capture(*cmd) = @output.capture(*cmd)
|
|
72
|
+
|
|
73
|
+
# 時間のかかる外部コマンドを、走査の前に裏で始める。brew cleanup -n だけで 8 秒ほどかかるので、
|
|
74
|
+
# 節の中で順に動かすと、走査と同じくらいの時間をただ待つことになる(benchmark/reports/ を参照)。
|
|
75
|
+
# docker は、context の一覧 → エンジンの応答 → 内訳、と前の結果で次が決まるので、スレッドの中で順に始める。
|
|
76
|
+
# 節の側が先に来ても、同じコマンドを 2 回は動かさない(Output#capture を参照)
|
|
77
|
+
def prefetch
|
|
78
|
+
[BREW_CLEANUP, OLLAMA_LIST, RUSTUP_TOOLCHAINS, SIMCTL_UNAVAILABLE, TMUTIL_SNAPSHOTS].each { @output.prefetch(*it) }
|
|
79
|
+
RubyAbi.prefetch(@output)
|
|
80
|
+
Thread.new do
|
|
81
|
+
(@output.prefetch(*DOCKER_CONTEXTS).stdout || "").split.each do |ctx|
|
|
82
|
+
Thread.new do
|
|
83
|
+
commands = docker_commands(ctx)
|
|
84
|
+
commands.each_value { @output.prefetch(*it) } if @output.prefetch(*commands[:info]).stdout
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# docker の context ごとに問い合わせるコマンド
|
|
91
|
+
def docker_commands(ctx)
|
|
92
|
+
docker = ["docker", "--context", ctx]
|
|
93
|
+
{
|
|
94
|
+
info: [*docker, "info", "--format", "{{.ID}}"],
|
|
95
|
+
df: [*docker, "system", "df"],
|
|
96
|
+
images: [*docker, "images", "--format", "{{.Size}}\t{{.Repository}}:{{.Tag}}\t{{.CreatedSince}}"],
|
|
97
|
+
stopped: [*docker, "ps", "-a", "-s", "-f", "status=exited", "-f", "status=created",
|
|
98
|
+
"--format", "{{.Size}} {{.Names}} {{.Image}} {{.Status}}"],
|
|
99
|
+
volumes: [*docker, "volume", "ls", "-f", "dangling=true", "--format", "{{.Name}}"],
|
|
100
|
+
}
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# 見出し。長いレポートの中で区切りを見つけやすくするため
|
|
104
|
+
def section(title) = puts("\n==== #{title} ====")
|
|
105
|
+
|
|
106
|
+
# サイズと説明を桁をそろえて 1 行で出す
|
|
107
|
+
def row(bytes, text) = puts(format("%8s %s", human(bytes), text))
|
|
108
|
+
|
|
109
|
+
# ---- 1. ディスク全体 ----------------------------------------------------------------
|
|
110
|
+
|
|
111
|
+
# APFS ではユーザーデータは Data ボリュームに乗るので、そちらを優先して見る
|
|
112
|
+
def disk
|
|
113
|
+
section _("Whole disk")
|
|
114
|
+
puts capture("df", "-h", "/System/Volumes/Data") || capture("df", "-h", "/")
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# ---- 走査本体 ------------------------------------------------------------------------
|
|
118
|
+
|
|
119
|
+
def scan
|
|
120
|
+
# キャッシュがあっても毎回 lstat し直すファイルの大きさの下限。これ未満のファイルは、
|
|
121
|
+
# フォルダーの mtime が変わらない限り前回の合計を使い回す
|
|
122
|
+
large = @large = [10 * MB, @big_record].min
|
|
123
|
+
cache = ScanCache.new(@cache_dir, @root, large:, output: @output)
|
|
124
|
+
old_tree = cache.load(@fresh)
|
|
125
|
+
message = if cache.expired?
|
|
126
|
+
_("(Scanning %{root} with %{jobs} threads. The cache is older than 7 days, so everything is " \
|
|
127
|
+
"scanned again; this takes a while.)")
|
|
128
|
+
elsif old_tree.nil?
|
|
129
|
+
_("(Scanning %{root} with %{jobs} threads. There is no cache yet, so this takes a while.)")
|
|
130
|
+
else
|
|
131
|
+
_("(Scanning %{root} with %{jobs} threads, reusing the previous results.)")
|
|
132
|
+
end
|
|
133
|
+
notice format(message, root: tilde(@root), jobs: @jobs)
|
|
134
|
+
scan_started = clock
|
|
135
|
+
@scanner = Scanner.new(
|
|
136
|
+
@root,
|
|
137
|
+
watched: Set[*@known.map(&:first), *@container_dirs, *@gem_dirs],
|
|
138
|
+
big_threshold: @big_record,
|
|
139
|
+
large:,
|
|
140
|
+
record_depth: 3,
|
|
141
|
+
no_artifacts_in: [File.join(HOME, "Library"), TRASH],
|
|
142
|
+
old_tree:,
|
|
143
|
+
jobs: @jobs,
|
|
144
|
+
progress: true,
|
|
145
|
+
skip: @skip,
|
|
146
|
+
frozen: @frozen_sizes,
|
|
147
|
+
)
|
|
148
|
+
total = @scanner.scan
|
|
149
|
+
@scan_seconds = clock - scan_started
|
|
150
|
+
# 前回から何も変わっていなければ、同じ中身を書き直すことになるので省く
|
|
151
|
+
cache.save(@scanner.tree, @scanner.dirs) if @scanner.changed?
|
|
152
|
+
|
|
153
|
+
# 走査の規模をログに残す。次回と比べて増え方を見たり、時間がかかった理由を調べたりするため
|
|
154
|
+
log format(_("Scan finished: %<seconds>d s, %<dirs>d folders (%<reused>d from the cache), total %<total>s, " \
|
|
155
|
+
"%<denied>d unreadable, %<cloud>d cloud-only"),
|
|
156
|
+
seconds: @scan_seconds, dirs: @scanner.dirs, reused: @scanner.reused, total: human(total),
|
|
157
|
+
denied: @scanner.denied.size, cloud: @scanner.cloud_only.size)
|
|
158
|
+
log_timings
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
# 遅い場所を突き止めるため、タスク(サブツリー)ごとの所要時間を記録する。
|
|
162
|
+
# 並列で動くので、トップレベル別の値は「各スレッドがそこで費やした時間の合計」で、壁時計の時間とは一致しない
|
|
163
|
+
def log_timings
|
|
164
|
+
top_of = ->(path) { File.join(@root, path.delete_prefix("#{@root}/").split("/").first.to_s) }
|
|
165
|
+
by_top = @scanner.timings.each_with_object(Hash.new(0.0)) { |(sec, path), h| h[top_of.(path)] += sec }
|
|
166
|
+
line = ->(sec, path) { log format(_(" %<sec>8.1f s %<path>s"), sec:, path: tilde(path)) }
|
|
167
|
+
log format(_("Time spent by top-level folder (sum over threads), top %{top}:"), top: @top)
|
|
168
|
+
by_top.max_by(@top) { |_, sec| sec }.each { |path, sec| line.(sec, path) }
|
|
169
|
+
log format(_("Slowest subtrees, top %{top}:"), top: @top)
|
|
170
|
+
@scanner.timings.max_by(@top, &:first).each { |sec, path| line.(sec, path) }
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
# 指定パスのサイズと、その配下の大きなファイルを返す。
|
|
174
|
+
# 起点の外にある場所(-d で起点を絞った場合や、Docker の保存場所を外に移している場合)は、
|
|
175
|
+
# その場所だけ追加で走査する。存在しなければ nil
|
|
176
|
+
def measure(path)
|
|
177
|
+
return nil unless File.directory?(path)
|
|
178
|
+
|
|
179
|
+
if under?(path, @root) && @scanner.watched_sizes.key?(path)
|
|
180
|
+
[@scanner.watched_sizes[path], @scanner.big_files.select { under?(it.path, path) }]
|
|
181
|
+
elsif (bytes = @frozen_sizes[path])
|
|
182
|
+
[bytes, []] # 固定したフォルダーそのもの。中の大きなファイルは分からない
|
|
183
|
+
else
|
|
184
|
+
measure_outside(path)
|
|
185
|
+
end
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
# 起点の外の走査 1 回ぶん。total は走査した場所全体のサイズ
|
|
189
|
+
Outside = Data.define(:root, :total, :scanner)
|
|
190
|
+
|
|
191
|
+
# 起点の外にある場所を測る。
|
|
192
|
+
# 測りたい場所どうしが入れ子になっていることが多い(~/Library/Caches とその中の Homebrew、gem 置き場とその doc など)
|
|
193
|
+
# ので、いちばん外側の場所を 1 回だけ走査して、中の場所のサイズもそこから取る。
|
|
194
|
+
# 走査結果は起点と同じようにキャッシュし、次回は変わっていないフォルダーの読み直しを省く
|
|
195
|
+
def measure_outside(path)
|
|
196
|
+
@outside ||= {}
|
|
197
|
+
outer = outside_candidates.select { under?(path, it) }.min_by(&:size) || path
|
|
198
|
+
scan = (@outside[outer] ||= scan_outside(outer))
|
|
199
|
+
if path == outer
|
|
200
|
+
[scan.total, scan.scanner.big_files]
|
|
201
|
+
elsif (bytes = scan.scanner.watched_sizes[path])
|
|
202
|
+
[bytes, scan.scanner.big_files.select { under?(it.path, path) }]
|
|
203
|
+
else
|
|
204
|
+
# 外側の走査がたどり着かなかった場所(シンボリックリンクの先など)は、そこだけ走査する
|
|
205
|
+
scan = (@outside[path] ||= scan_outside(path))
|
|
206
|
+
[scan.total, scan.scanner.big_files]
|
|
207
|
+
end
|
|
208
|
+
end
|
|
209
|
+
|
|
210
|
+
# サイズを知りたい場所のうち、起点の外にあるもの
|
|
211
|
+
def outside_candidates
|
|
212
|
+
@outside_candidates ||= [*@known.map(&:first), *@container_dirs, *@gem_dirs].uniq.reject { under?(it, @root) }
|
|
213
|
+
end
|
|
214
|
+
|
|
215
|
+
def scan_outside(root)
|
|
216
|
+
cache = ScanCache.new(@cache_dir, root, large: @large, output: @output)
|
|
217
|
+
scanner = Scanner.new(root, watched: Set[*outside_candidates.select { under?(it, root) }],
|
|
218
|
+
big_threshold: @big_record, large: @large, old_tree: cache.load(@fresh),
|
|
219
|
+
skip: @skip, jobs: @jobs, frozen: @frozen_sizes)
|
|
220
|
+
total = scanner.scan
|
|
221
|
+
cache.save(scanner.tree, scanner.dirs) if scanner.changed?
|
|
222
|
+
Outside.new(root:, total:, scanner:)
|
|
223
|
+
end
|
|
224
|
+
|
|
225
|
+
# ---- 2・3. フォルダーの内訳 ------------------------------------------------------------
|
|
226
|
+
|
|
227
|
+
def folders
|
|
228
|
+
section format(_("Largest folders directly under %{dir}"), dir: tilde(@root))
|
|
229
|
+
children_of(@root)
|
|
230
|
+
|
|
231
|
+
# ~/Library はアプリのデータやキャッシュが溜まりやすく、Finder でも見えにくいので内訳を個別に見る
|
|
232
|
+
["Library", "Library/Application Support", "Library/Containers", "Library/Group Containers"].each do |rel|
|
|
233
|
+
dir = File.join(HOME, rel)
|
|
234
|
+
next unless under?(dir, @root)
|
|
235
|
+
|
|
236
|
+
section format(_("Inside %{dir}"), dir: tilde(dir))
|
|
237
|
+
children_of(dir)
|
|
238
|
+
end
|
|
239
|
+
end
|
|
240
|
+
|
|
241
|
+
# 走査時に記録した深さ 3 までのサイズから、指定フォルダーの直下の子だけを大きい順に出す
|
|
242
|
+
def children_of(dir)
|
|
243
|
+
@scanner.dir_sizes
|
|
244
|
+
.select { |path, _| File.dirname(path) == dir }
|
|
245
|
+
.max_by(@top) { |_, size| size }
|
|
246
|
+
.each { |path, size| row(size, tilde(path)) }
|
|
247
|
+
end
|
|
248
|
+
|
|
249
|
+
# ---- 4. 再生成・再取得できることが多い場所 ------------------------------------------------
|
|
250
|
+
|
|
251
|
+
# 入れ子の場所(例: Library/Caches とその中の Homebrew)は重複して数えている点に注意
|
|
252
|
+
def regenerable
|
|
253
|
+
section _("Usually regenerable or downloadable again (100MB or more)")
|
|
254
|
+
@known
|
|
255
|
+
.filter_map { |path, note| (size, = measure(path)) && [size, path, note] }
|
|
256
|
+
.select { |size, *| size >= 100 * MB } # 小さいものは削除効果が薄いので省く
|
|
257
|
+
.sort_by { |size, *| -size }
|
|
258
|
+
.each { |size, path, note| row(size, "#{tilde(path)} — #{note}") }
|
|
259
|
+
end
|
|
260
|
+
|
|
261
|
+
# ---- 5. ビルド成果物・依存パッケージ --------------------------------------------------
|
|
262
|
+
|
|
263
|
+
# プロジェクトで再ビルド・再インストールすれば戻るので、古いプロジェクトのものは削除候補になる。
|
|
264
|
+
# 日付はそのフォルダーの最終更新日で、長く触っていないプロジェクトを見分ける手がかりにする
|
|
265
|
+
def artifacts
|
|
266
|
+
section format(_("Build artifacts and dependencies (50MB or more, under %{root})"), root: tilde(@root))
|
|
267
|
+
@scanner.artifacts
|
|
268
|
+
.select { it.bytes >= 50 * MB }
|
|
269
|
+
.max_by(@top, &:bytes)
|
|
270
|
+
.each { row(it.bytes, "#{it.mtime.strftime('%F')} #{tilde(it.path)}") }
|
|
271
|
+
end
|
|
272
|
+
|
|
273
|
+
# ---- 6. Ruby の gem ------------------------------------------------------------------
|
|
274
|
+
|
|
275
|
+
# Ruby を上げると vendor/bundle/ruby/<ABI 版> や ~/.gem/ruby/<ABI 版> に旧バージョン用の gem が
|
|
276
|
+
# そのまま残りがちなので、版ごとに分けて大きさを出す。
|
|
277
|
+
# 「プロジェクトが今使う Ruby」や「インストール済みの Ruby」と合わないものに旧版候補の印を付ける。
|
|
278
|
+
def ruby_gems
|
|
279
|
+
installed = RubyAbi.installed(@output)
|
|
280
|
+
|
|
281
|
+
section _("Ruby: vendor/bundle in projects (by ABI version, 10MB or more)")
|
|
282
|
+
@scanner.vendor_ruby
|
|
283
|
+
.select { |_, size| size >= 10 * MB }
|
|
284
|
+
.sort_by { |_, size| -size }
|
|
285
|
+
.each do |path, size|
|
|
286
|
+
abi = File.basename(path)
|
|
287
|
+
want = RubyAbi.project(path.sub(%r{/vendor/bundle/ruby/[^/]+\z}, ""))
|
|
288
|
+
note = if want.nil?
|
|
289
|
+
_("Ruby version in use unknown (no .ruby-version)")
|
|
290
|
+
elsif want == abi
|
|
291
|
+
_("in use")
|
|
292
|
+
elsif installed.include?(abi)
|
|
293
|
+
format(_("possibly stale (the project uses %{want})"), want:)
|
|
294
|
+
else
|
|
295
|
+
# 対応する Ruby が見つからない ABI 版には、その旨を注記する
|
|
296
|
+
format(_("possibly stale (the project uses %{want}; no Ruby of this version found)"), want:)
|
|
297
|
+
end
|
|
298
|
+
row(size, format("%-6s %s %s", abi, note, tilde(path)))
|
|
299
|
+
end
|
|
300
|
+
|
|
301
|
+
# フォルダー名は、gem install --user-install なら ABI 版(4.0.0)、chruby ならフルの版(4.0.9)になる。
|
|
302
|
+
# どちらでも、その版の Ruby が見つからなければ旧版候補とする。
|
|
303
|
+
# ドキュメント(doc)は gem 本体より大きくなることがあり、消しても gem rdoc で作り直せるので内訳を出す
|
|
304
|
+
section _("Ruby: gems in your home directory (by version)")
|
|
305
|
+
@gem_dirs
|
|
306
|
+
.filter_map { |path| (size, = measure(path)) && [size, path] }
|
|
307
|
+
.sort_by { |size, _| -size }
|
|
308
|
+
.each do |size, path|
|
|
309
|
+
name = File.basename(path)
|
|
310
|
+
note = installed.include?(name) ? _("matching Ruby found") : _("possibly stale (no Ruby of this version found)")
|
|
311
|
+
doc, = measure(File.join(path, "doc"))
|
|
312
|
+
note += format(_(", of which docs %{size}"), size: human(doc)) if doc && doc >= 100 * MB
|
|
313
|
+
row(size, format("%-6s %s %s", name, note, tilde(path)))
|
|
314
|
+
end
|
|
315
|
+
puts format(_("Ruby ABI versions found: %{list}"), list: installed.abis.sort.join(" "))
|
|
316
|
+
versions = installed.versions.sort_by { Gem::Version.new(it) rescue Gem::Version.new("0") }
|
|
317
|
+
puts format(_("Ruby versions found: %{list}"), list: versions.join(" "))
|
|
318
|
+
end
|
|
319
|
+
|
|
320
|
+
# ---- 7. コンテナ環境 --------------------------------------------------------------------
|
|
321
|
+
|
|
322
|
+
# Docker などは「見つけにくい」と「素直に消せない」の両面があるので節を分けて見る。
|
|
323
|
+
# - 見つけにくい: 中身は仮想マシンのディスクイメージ(Docker.raw など)に詰め込まれていて、
|
|
324
|
+
# Finder では巨大な 1 ファイルにしか見えない。保存場所も設定で変えられる。
|
|
325
|
+
# - 消しにくい: ディスクイメージを直接消すとコンテナもボリュームも全部消える。
|
|
326
|
+
# docker 側で prune しても、スパースファイルなので Mac 側の空きに反映されるのが遅れることがある。
|
|
327
|
+
# そこで (a) データ置き場とディスクイメージの実占有量、(b) 動いているエンジンで prune できるものの内訳、を出す。
|
|
328
|
+
def containers
|
|
329
|
+
container_storage
|
|
330
|
+
docker_engines
|
|
331
|
+
end
|
|
332
|
+
|
|
333
|
+
def container_storage
|
|
334
|
+
section _("Containers: data folders and disk images")
|
|
335
|
+
@container_dirs.each do |dir|
|
|
336
|
+
size, bigs = measure(dir)
|
|
337
|
+
next if size.nil? || size < 100 * MB # 無いもの・小さいものは省く
|
|
338
|
+
|
|
339
|
+
row(size, tilde(dir))
|
|
340
|
+
# ディスクイメージはスパースファイルで、見かけ(上限)と実占有が大きく違うため両方出す
|
|
341
|
+
bigs.select { it.apparent >= 100 * MB }.sort_by { -it.bytes }.each do
|
|
342
|
+
row(it.bytes, format(_(" └ %{path} (apparent size %{size})"), path: tilde(it.path), size: human(it.apparent)))
|
|
343
|
+
end
|
|
344
|
+
end
|
|
345
|
+
end
|
|
346
|
+
|
|
347
|
+
# (b) docker の context を全部回るので、Docker Desktop と Colima などを併用していても両方見られる。
|
|
348
|
+
# 止まっているエンジンには問い合わせできないので、その旨だけ出す
|
|
349
|
+
def docker_engines
|
|
350
|
+
contexts = capture(*DOCKER_CONTEXTS)
|
|
351
|
+
return unless contexts
|
|
352
|
+
|
|
353
|
+
section _("Containers: by engine (start stopped engines and run again to include them)")
|
|
354
|
+
seen = {} # エンジンの ID => 最初に見た context 名
|
|
355
|
+
contexts.split.each do |ctx|
|
|
356
|
+
commands = docker_commands(ctx)
|
|
357
|
+
id = capture(*commands[:info])&.strip
|
|
358
|
+
unless id
|
|
359
|
+
puts format(_("-- %{context}: no response (stopped)"), context: ctx)
|
|
360
|
+
next
|
|
361
|
+
end
|
|
362
|
+
# Docker Desktop の default と desktop-linux のように、別の context が同じエンジンを指していることがある。
|
|
363
|
+
# 同じ内訳を二度出すと、空く量を二重に数えてしまいやすいので省く
|
|
364
|
+
if (first = seen[id])
|
|
365
|
+
puts format(_("-- %{context}: same engine as %{first} (skipped)"), context: ctx, first:)
|
|
366
|
+
next
|
|
367
|
+
end
|
|
368
|
+
seen[id] = ctx
|
|
369
|
+
|
|
370
|
+
puts format(_("-- %{context}: the RECLAIMABLE column is roughly what prune frees " \
|
|
371
|
+
"(use docker builder prune for the build cache)"), context: ctx)
|
|
372
|
+
puts capture(*commands[:df])
|
|
373
|
+
|
|
374
|
+
puts _(" Large images (<none> means dangling, removed by docker image prune)")
|
|
375
|
+
# docker images の並びは呼ぶたびに変わりうるので、同じ大きさのものは名前順にして、出力を安定させる
|
|
376
|
+
(capture(*commands[:images]) || "")
|
|
377
|
+
.lines(chomp: true).map { it.split("\t") }
|
|
378
|
+
.sort_by { |size, name, _| [-parse_decimal_size(size), name.to_s] }.first(@top)
|
|
379
|
+
.each { |size, name, created| row(parse_decimal_size(size), "#{name} #{created}") }
|
|
380
|
+
|
|
381
|
+
puts _(" Stopped containers (removed by docker container prune)")
|
|
382
|
+
puts capture(*commands[:stopped])&.lines&.first(@top)&.join
|
|
383
|
+
|
|
384
|
+
# ボリュームには DB などのデータが入っていることがあるので、消す前に中身を確かめる前提で名前だけ出す
|
|
385
|
+
puts _(" Volumes not used by any container (check their contents before docker volume rm)")
|
|
386
|
+
puts capture(*commands[:volumes])&.lines&.first(@top)&.join
|
|
387
|
+
end
|
|
388
|
+
end
|
|
389
|
+
|
|
390
|
+
# docker のサイズ表記をバイト数に直す(並べ替え用)
|
|
391
|
+
def parse_decimal_size(s) = (s.to_f * DECIMAL_UNITS.fetch(s[/[A-Za-z]+\z/], 1)).to_i
|
|
392
|
+
|
|
393
|
+
# ---- 8. 巨大ファイル --------------------------------------------------------------------
|
|
394
|
+
|
|
395
|
+
# 動画・ディスクイメージ・モデルファイル・古いインストーラーなどが見つかりやすい。
|
|
396
|
+
# 並べ替えは実占有量で行い、見かけより実占有が極端に小さいもの(クラウド上のみ・スパースファイル)には
|
|
397
|
+
# 印を付ける。それらは消しても空きがほとんど増えないため。ゴミ箱は 4 で扱うので除く。
|
|
398
|
+
# コンテナのディスクイメージもここに出るが、直接は消さず 7 の方法で減らす。
|
|
399
|
+
def big_files
|
|
400
|
+
section format(_("Files of %{min_mb}MB or more (under %{root})"), min_mb: @min_mb, root: tilde(@root))
|
|
401
|
+
@scanner.big_files
|
|
402
|
+
.select { it.apparent >= @min_mb * MB && !under?(it.path, TRASH) }
|
|
403
|
+
.max_by(@top, &:bytes)
|
|
404
|
+
.each do
|
|
405
|
+
mark = it.bytes < it.apparent / 2 ? _(" [uses less than half of its apparent size]") : ""
|
|
406
|
+
row(it.bytes, "#{it.mtime.strftime('%F')} #{tilde(it.path)}#{mark}")
|
|
407
|
+
end
|
|
408
|
+
end
|
|
409
|
+
|
|
410
|
+
# ---- 9. Time Machine ローカルスナップショット -------------------------------------------
|
|
411
|
+
|
|
412
|
+
# 「パージ可能」として扱われるが、実際には領域を使っている。
|
|
413
|
+
# 一覧は sudo 無しで取れる(削除する場合は tmutil deletelocalsnapshots を使う)
|
|
414
|
+
def time_machine
|
|
415
|
+
section _("Time Machine local snapshots")
|
|
416
|
+
puts capture(*TMUTIL_SNAPSHOTS) || _("(could not get the list)")
|
|
417
|
+
end
|
|
418
|
+
|
|
419
|
+
# ---- 10. ツール別の見積もり -------------------------------------------------------------
|
|
420
|
+
|
|
421
|
+
# 各ツール自身による「整理すると何が空くか」の情報。どれも表示だけで削除はしない(Docker は 7 で扱う)
|
|
422
|
+
def tool_estimates
|
|
423
|
+
section _("Estimates from other tools")
|
|
424
|
+
if (out = capture(*BREW_CLEANUP))
|
|
425
|
+
puts _("-- Homebrew: summary of brew cleanup -n (old versions and caches)")
|
|
426
|
+
puts out.lines.last
|
|
427
|
+
end
|
|
428
|
+
# Ollama はサーバーが起動していないと一覧が取れないので、失敗したら黙って飛ばす
|
|
429
|
+
if (out = capture(*OLLAMA_LIST))
|
|
430
|
+
puts _("-- Ollama models (remove unused ones with ollama rm <name>)")
|
|
431
|
+
puts out
|
|
432
|
+
end
|
|
433
|
+
if (out = capture(*RUSTUP_TOOLCHAINS))
|
|
434
|
+
puts _("-- Rust toolchains (remove unused ones with rustup toolchain uninstall <name>)")
|
|
435
|
+
puts out
|
|
436
|
+
end
|
|
437
|
+
# simctl は Xcode 本体が無いと失敗するので、そのときは飛ばす
|
|
438
|
+
if (out = capture(*SIMCTL_UNAVAILABLE))
|
|
439
|
+
n = out.lines.count { it.include?("(") } # 機種の行だけが括弧付き(UUID と状態)
|
|
440
|
+
puts format(_("-- Unavailable iOS simulators: %{count} (remove them with xcrun simctl delete unavailable)"), count: n)
|
|
441
|
+
end
|
|
442
|
+
end
|
|
443
|
+
|
|
444
|
+
# ---- 11. 固定したフォルダー -------------------------------------------------------------
|
|
445
|
+
|
|
446
|
+
# 走査せず、設定ファイルにあるサイズを使ったフォルダー。中の巨大ファイルやビルド成果物は上の節に出ないので、
|
|
447
|
+
# そのことが分かるよう一覧にする。フォルダー自身の更新時刻が測ったときと違えば、
|
|
448
|
+
# 直下でファイルの追加・削除があったので測り直しを勧める(深いところの変化は分からない)
|
|
449
|
+
def frozen_folders
|
|
450
|
+
frozen = @frozen.select { under?(it.path, @root) }
|
|
451
|
+
return if frozen.empty?
|
|
452
|
+
|
|
453
|
+
section _("Frozen folders (sizes from the config file, not scanned)")
|
|
454
|
+
frozen.sort_by { -it.bytes }.each do |f|
|
|
455
|
+
st = File.lstat(f.path) rescue nil
|
|
456
|
+
note = if st.nil?
|
|
457
|
+
_(" (not found; remove it with --unfreeze)")
|
|
458
|
+
elsif Config.mtime_of(st) != f.mtime
|
|
459
|
+
_(" (changed since it was measured; measure it again with --freeze)")
|
|
460
|
+
else
|
|
461
|
+
""
|
|
462
|
+
end
|
|
463
|
+
row(f.bytes, "#{f.measured_at&.strftime('%F') || '-'} #{tilde(f.path)}#{note}")
|
|
464
|
+
end
|
|
465
|
+
puts format(_("Config file: %{path}"), path: tilde(@config.path))
|
|
466
|
+
end
|
|
467
|
+
|
|
468
|
+
# ---- 12. 読めなかった場所 ---------------------------------------------------------------
|
|
469
|
+
|
|
470
|
+
# ここに大きそうな場所があれば上の集計から漏れているので、
|
|
471
|
+
# 必要ならターミナルにフルディスクアクセスを与えて再実行する(sudo は不要)。
|
|
472
|
+
# 読めなかったフォルダーの中へは降りていないので、親子が重複して並ぶことはない
|
|
473
|
+
def unreadable
|
|
474
|
+
section _("Unreadable locations (missing from the totals)")
|
|
475
|
+
denied = @scanner.denied.sort
|
|
476
|
+
puts count_line(denied.size)
|
|
477
|
+
denied.first(@top).each { puts tilde(it) }
|
|
478
|
+
# 画面とレポートには先頭だけ出し、全件はログに残す
|
|
479
|
+
denied.each { log format(_("Unreadable: %{path}"), path: it) }
|
|
480
|
+
|
|
481
|
+
# 中身がクラウド上にしか無いので手元の容量はほとんど使っておらず、集計から漏れても問題は小さい
|
|
482
|
+
cloud_only = @scanner.cloud_only.sort
|
|
483
|
+
return if cloud_only.empty?
|
|
484
|
+
|
|
485
|
+
section _("Cloud-only folders, not read (they use almost no local space)")
|
|
486
|
+
puts count_line(cloud_only.size)
|
|
487
|
+
cloud_only.first(@top).each { puts tilde(it) }
|
|
488
|
+
cloud_only.each { log format(_("Cloud-only: %{path}"), path: it) }
|
|
489
|
+
end
|
|
490
|
+
|
|
491
|
+
# 「N 件。先頭 M 件:」
|
|
492
|
+
def count_line(count) = format(n_("%{count} item. First %{top}:", "%{count} items. First %{top}:", count), count:, top: @top)
|
|
493
|
+
|
|
494
|
+
def finish
|
|
495
|
+
section _("Done")
|
|
496
|
+
elapsed = clock - @started
|
|
497
|
+
puts format(_("Took %<total>d s (scanning %<scan>d s, %<jobs>d threads). " \
|
|
498
|
+
"%<reused>d of the %<dirs>d scanned folders came from the cache."),
|
|
499
|
+
total: elapsed, scan: @scan_seconds, jobs: @jobs, dirs: @scanner.dirs, reused: @scanner.reused)
|
|
500
|
+
puts _("Nothing was deleted.")
|
|
501
|
+
log format(_("Finished: took %<total>d s"), total: elapsed)
|
|
502
|
+
end
|
|
503
|
+
end
|
|
504
|
+
end
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
require "rbconfig" # 通常は起動時に読み込まれているが、--disable-gems で動かした場合に備える
|
|
2
|
+
|
|
3
|
+
module Reclaimable
|
|
4
|
+
# Ruby の ABI 版(例: 3.3.0)を調べる。ABI 版は CRuby の major.minor で決まり、
|
|
5
|
+
# vendor/bundle/ruby/<ABI 版> や ~/.gem/ruby/<ABI 版> のフォルダー名になる。
|
|
6
|
+
# ただし chruby は ~/.gem/ruby/<フルの版>(例: 4.0.9)に gem を置くので、フルの版も集める
|
|
7
|
+
module RubyAbi
|
|
8
|
+
# インストール済み Ruby の ABI 版とフルの版
|
|
9
|
+
Installed = Data.define(:abis, :versions) do
|
|
10
|
+
# gem 置き場のフォルダー名(ABI 版かフルの版)に対応する Ruby があるか
|
|
11
|
+
def include?(name) = abis.include?(name) || versions.include?(name)
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
# 版を問い合わせるとき、呼び出し元(chruby など)の gem の設定を引き継がないようにする。
|
|
15
|
+
# 引き継ぐと、古い Ruby が新しい Ruby 用の gem を読み込もうとして警告を大量に出す
|
|
16
|
+
PROBE_ENV = %w[GEM_HOME GEM_PATH GEM_ROOT RUBYOPT RUBYLIB BUNDLE_GEMFILE].to_h { [it, nil] }.freeze
|
|
17
|
+
|
|
18
|
+
module_function
|
|
19
|
+
|
|
20
|
+
# インストール済み Ruby の版を集める。各 ruby を実際に起動して RbConfig と RUBY_VERSION から取るので、
|
|
21
|
+
# ディレクトリ名の付け方(ruby-3.3.5 / 3.3.5 など)に左右されない
|
|
22
|
+
def installed(output)
|
|
23
|
+
# このスクリプトを動かしている Ruby 自身も含める
|
|
24
|
+
abis = Set[RbConfig::CONFIG["ruby_version"]]
|
|
25
|
+
versions = Set[RUBY_VERSION]
|
|
26
|
+
probes.each do |probe|
|
|
27
|
+
abi, version = output.capture(*probe, env: PROBE_ENV)&.split
|
|
28
|
+
abis << abi if abi
|
|
29
|
+
versions << version if version
|
|
30
|
+
end
|
|
31
|
+
Installed.new(abis:, versions:)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# installed の問い合わせを、裏で先に始めておく(Ruby が数十あると、順に起動するだけで 2 秒ほどかかるため)
|
|
35
|
+
def prefetch(output) = probes.each { output.prefetch(*it, env: PROBE_ENV) }
|
|
36
|
+
|
|
37
|
+
# 見つかった ruby ごとの、版を問い合わせるコマンド
|
|
38
|
+
def probes
|
|
39
|
+
bins = Dir.glob([
|
|
40
|
+
"~/.rubies/*/bin/ruby", "~/.rbenv/versions/*/bin/ruby",
|
|
41
|
+
"~/.local/share/mise/installs/ruby/*/bin/ruby", "~/.asdf/installs/ruby/*/bin/ruby",
|
|
42
|
+
].map { File.expand_path(it) }) + %w[/opt/homebrew/opt/ruby/bin/ruby /usr/local/opt/ruby/bin/ruby /usr/bin/ruby]
|
|
43
|
+
# --disable-gems だと rbconfig は自動では読み込まれないので -r で読む
|
|
44
|
+
bins.select { File.executable?(it) }.map do |bin|
|
|
45
|
+
[bin, "--disable-gems", "-rrbconfig", "-e", "print RbConfig::CONFIG['ruby_version'], ' ', RUBY_VERSION"]
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# プロジェクトが使う Ruby の ABI 版を推定する。rbenv・chruby・mise と同じく、
|
|
50
|
+
# プロジェクトから親へさかのぼって最初に見つかった .ruby-version / .tool-versions を使う。
|
|
51
|
+
# 見つからない・読めない版指定(jruby など)は nil にし、旧版と決めつけず「不明」と表示する
|
|
52
|
+
def project(dir)
|
|
53
|
+
d = dir
|
|
54
|
+
until d == "/"
|
|
55
|
+
rv = File.join(d, ".ruby-version")
|
|
56
|
+
tv = File.join(d, ".tool-versions")
|
|
57
|
+
v = File.foreach(rv).first&.strip if File.file?(rv)
|
|
58
|
+
v ||= File.foreach(tv).map(&:split).find { it.first == "ruby" }&.at(1) if File.file?(tv)
|
|
59
|
+
# "ruby-3.3.5" や "3.3.5" から major.minor を取り出し、ABI 版の形(3.3.0)にする
|
|
60
|
+
return v[/\A(?:ruby-)?(\d+\.\d+)/, 1]&.then { "#{it}.0" } if v
|
|
61
|
+
|
|
62
|
+
d = File.dirname(d)
|
|
63
|
+
end
|
|
64
|
+
nil
|
|
65
|
+
rescue SystemCallError
|
|
66
|
+
nil
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
end
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
require "fileutils"
|
|
2
|
+
require "zlib"
|
|
3
|
+
|
|
4
|
+
module Reclaimable
|
|
5
|
+
# 走査結果のキャッシュ。起点ごとに 1 ファイルで、変化があればまるごと書き直すので、消えたフォルダーの記録は残らない。
|
|
6
|
+
# Marshal はこのスクリプト自身が書いたファイルだけを読む前提で使っている
|
|
7
|
+
class ScanCache
|
|
8
|
+
include Util
|
|
9
|
+
include I18n
|
|
10
|
+
|
|
11
|
+
FORMAT_VERSION = 2
|
|
12
|
+
MAX_AGE = 7 * 24 * 60 * 60 # 秒
|
|
13
|
+
|
|
14
|
+
# 形式の版が今のものと違うキャッシュを読もうとした
|
|
15
|
+
class VersionError < StandardError; end
|
|
16
|
+
|
|
17
|
+
# 起点ごとのキャッシュファイルの場所。起点のパスの / を % に置き換えてファイル名にする
|
|
18
|
+
def self.path_for(dir, root) = File.join(dir, "#{root.tr('/', '%')}.marshal.gz")
|
|
19
|
+
|
|
20
|
+
# キャッシュファイルの中身をそのまま返す。
|
|
21
|
+
# { version: 形式の版, large: 毎回 lstat し直す大きさの下限,
|
|
22
|
+
# full_scan_at: 最後にキャッシュを使わず全部走査した時刻(秒), tree: 起点のノード(Scanner を参照) }
|
|
23
|
+
#
|
|
24
|
+
# ファイルは全体を一度に読んでから展開する。Zlib::GzipReader で少しずつ読むと、外部コマンドを裏で
|
|
25
|
+
# 起動している最中(Output#prefetch)に、まれに Zlib::BufError で読めないことがあった
|
|
26
|
+
def self.read(path) = Marshal.load(Zlib.gunzip(File.binread(path)))
|
|
27
|
+
|
|
28
|
+
# 木を、フォルダーのパスをキーにした平らな Hash({ パス => ノード })に直す。
|
|
29
|
+
# 中身を一覧にするとき(--dump-cache)に使う
|
|
30
|
+
def self.flatten(node, path, out = {})
|
|
31
|
+
out[path] = node
|
|
32
|
+
node[Scanner::KIDS]&.each { |name, child| flatten(child, File.join(path, name), out) if child }
|
|
33
|
+
out
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# 前回のキャッシュが期限切れで、全部走査し直すことになったか(load のあとで分かる)
|
|
37
|
+
def expired? = @expired
|
|
38
|
+
|
|
39
|
+
# large: キャッシュがあっても毎回 lstat し直すファイルの大きさの下限。基準が変わったらキャッシュは使えない
|
|
40
|
+
def initialize(dir, root, large:, output:)
|
|
41
|
+
@path = self.class.path_for(dir, root)
|
|
42
|
+
@large = large
|
|
43
|
+
@output = output
|
|
44
|
+
@expired = false
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# 前回の走査結果の木を読む。次の場合は使わず(nil を返し)、全部走査し直す。
|
|
48
|
+
# - --fresh が指定された
|
|
49
|
+
# - 最後に全部走査してから 7 日より経った(mtime で拾えない変化、たとえばその場で書き足されたファイルや、
|
|
50
|
+
# クラウド上のファイルのダウンロードによる増加が溜まるため)。
|
|
51
|
+
# キャッシュのファイルは実行のたびに書き直すので、ファイルの更新時刻ではなく、中に書いた時刻で見る
|
|
52
|
+
# - 形式や「毎回 lstat し直す大きさ」の基準が今回と違う
|
|
53
|
+
def load(fresh)
|
|
54
|
+
@full_scan_at = Time.now.to_i # 使えるキャッシュがあれば、下でその値に置き換える
|
|
55
|
+
return nil if fresh || !File.file?(@path)
|
|
56
|
+
|
|
57
|
+
case self.class.read(@path)
|
|
58
|
+
in { version: FORMAT_VERSION, large: ^@large, full_scan_at: Integer => at, tree: Array => tree }
|
|
59
|
+
if Time.now.to_i - at > MAX_AGE
|
|
60
|
+
@expired = true
|
|
61
|
+
@output.log format(_("Not using the cache because it is older than 7 days: %{path}"), path: @path)
|
|
62
|
+
return nil
|
|
63
|
+
end
|
|
64
|
+
@full_scan_at = at
|
|
65
|
+
tree
|
|
66
|
+
else
|
|
67
|
+
@output.log format(_("Not using the cache because its format or settings differ: %{path}"), path: @path)
|
|
68
|
+
nil
|
|
69
|
+
end
|
|
70
|
+
rescue StandardError, SystemStackError => e
|
|
71
|
+
@output.log format(_("Not using the cache because it cannot be read: %{error}"), error: "#{e.class}: #{e.message}")
|
|
72
|
+
nil
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# 今回の走査結果を次回のために書く。書きかけのファイルが残らないよう、一時ファイルに書いてから置き換える。
|
|
76
|
+
# 圧縮は速さを優先する(Zlib::BEST_SPEED)。既定の圧縮率と比べてファイルは 2 割ほど大きくなるが、
|
|
77
|
+
# 書き込みにかかる時間の半分以上が圧縮なので、全体で 3 割ほど速くなる(読む側は圧縮率によらず読める)
|
|
78
|
+
#
|
|
79
|
+
# tree: 走査結果の木(Scanner#tree)。count: 走査したフォルダーの数(ログに書くだけ)。
|
|
80
|
+
# 木は深い入れ子になる。Marshal は入れ子の深さだけスタックを使うので、読み書きはメインスレッドで行う
|
|
81
|
+
# (スレッドのスタックは小さく、1,000 段ほどで SystemStackError になる)
|
|
82
|
+
def save(tree, count)
|
|
83
|
+
return unless tree # 起点を読めなかったときは、書くものが無い
|
|
84
|
+
|
|
85
|
+
FileUtils.mkdir_p(File.dirname(@path))
|
|
86
|
+
tmp = "#{@path}.tmp"
|
|
87
|
+
data = Marshal.dump({ version: FORMAT_VERSION, large: @large, full_scan_at: @full_scan_at || Time.now.to_i, tree: })
|
|
88
|
+
File.binwrite(tmp, Zlib.gzip(data, level: Zlib::BEST_SPEED))
|
|
89
|
+
File.rename(tmp, @path)
|
|
90
|
+
@output.log format(n_("Saved the cache: %{path} (%{size}, %{count} folder)",
|
|
91
|
+
"Saved the cache: %{path} (%{size}, %{count} folders)", count),
|
|
92
|
+
path: @path, size: human(File.size(@path)), count:)
|
|
93
|
+
rescue StandardError, SystemStackError => e
|
|
94
|
+
@output.log format(_("Cannot save the cache: %{error}"), error: "#{e.class}: #{e.message}")
|
|
95
|
+
end
|
|
96
|
+
end
|
|
97
|
+
end
|