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.
Files changed (85) hide show
  1. checksums.yaml +7 -0
  2. data/.claude/launch.json +11 -0
  3. data/.gitignore +11 -0
  4. data/.gitlab-ci.yml +16 -0
  5. data/AGENTS.md +88 -0
  6. data/CLAUDE.md +1 -0
  7. data/Gemfile +3 -0
  8. data/LICENSE +674 -0
  9. data/README.md +160 -0
  10. data/Rakefile +28 -0
  11. data/ai-skill/reclaimable/SKILL.md +94 -0
  12. data/benchmark/README.md +59 -0
  13. data/benchmark/experiments/lstat_scanner.rb +11 -0
  14. data/benchmark/experiments/ractor_scanner.rb +92 -0
  15. data/benchmark/experiments/verify_bulk_list.rb +34 -0
  16. data/benchmark/lib/fixture.rb +104 -0
  17. data/benchmark/lib/results.rb +62 -0
  18. data/benchmark/reports/00-baseline.md +75 -0
  19. data/benchmark/reports/01-jit.md +70 -0
  20. data/benchmark/reports/02-ractor.md +58 -0
  21. data/benchmark/reports/03-getattrlistbulk.md +84 -0
  22. data/benchmark/reports/04-others.md +52 -0
  23. data/benchmark/reports/05-outside-root.md +56 -0
  24. data/benchmark/reports/06-round2-discussion.md +374 -0
  25. data/benchmark/reports/06-round2.md +194 -0
  26. data/benchmark/reports/README.md +46 -0
  27. data/benchmark/results/baseline.yml +126 -0
  28. data/benchmark/results/bulk-list.yml +126 -0
  29. data/benchmark/results/final-yjit.yml +126 -0
  30. data/benchmark/results/final.yml +126 -0
  31. data/benchmark/results/ractor-exp.yml +38 -0
  32. data/benchmark/results/round2-after.yml +126 -0
  33. data/benchmark/results/round2-before.yml +126 -0
  34. data/benchmark/results/src-baseline.yml +32 -0
  35. data/benchmark/results/src-bulk-list.yml +32 -0
  36. data/benchmark/results/src-pair-none1.yml +38 -0
  37. data/benchmark/results/src-pair-none2.yml +38 -0
  38. data/benchmark/results/src-pair-yjit1.yml +38 -0
  39. data/benchmark/results/src-pair-yjit2.yml +38 -0
  40. data/benchmark/results/src-ractor-exp.yml +32 -0
  41. data/benchmark/results/src-round2-after1.yml +52 -0
  42. data/benchmark/results/src-round2-after2.yml +52 -0
  43. data/benchmark/results/src-round2-before1.yml +52 -0
  44. data/benchmark/results/src-round2-before2.yml +52 -0
  45. data/benchmark/results/yjit.yml +126 -0
  46. data/benchmark/results/zjit.yml +126 -0
  47. data/benchmark/run.rb +149 -0
  48. data/bin/reclaimable +10 -0
  49. data/doc/performance.md +179 -0
  50. data/lib/reclaimable/ai_skill.rb +138 -0
  51. data/lib/reclaimable/bulk_list.rb +91 -0
  52. data/lib/reclaimable/cache_dump.rb +125 -0
  53. data/lib/reclaimable/cli.rb +168 -0
  54. data/lib/reclaimable/cloud_files.rb +33 -0
  55. data/lib/reclaimable/config.rb +100 -0
  56. data/lib/reclaimable/i18n.rb +24 -0
  57. data/lib/reclaimable/locations.rb +89 -0
  58. data/lib/reclaimable/output.rb +154 -0
  59. data/lib/reclaimable/paths.rb +36 -0
  60. data/lib/reclaimable/report.rb +504 -0
  61. data/lib/reclaimable/ruby_abi.rb +69 -0
  62. data/lib/reclaimable/scan_cache.rb +97 -0
  63. data/lib/reclaimable/scanner.rb +440 -0
  64. data/lib/reclaimable/util.rb +34 -0
  65. data/lib/reclaimable.rb +42 -0
  66. data/locale/ja/LC_MESSAGES/reclaimable.mo +0 -0
  67. data/man/reclaimable.1.ronn +302 -0
  68. data/man/reclaimable.en.1 +234 -0
  69. data/man/reclaimable.ja.1 +452 -0
  70. data/po/ja/reclaimable-docs.po +668 -0
  71. data/po/ja/reclaimable.po +510 -0
  72. data/rakelib/benchmark.rake +22 -0
  73. data/rakelib/docs/japanese.rb +132 -0
  74. data/rakelib/docs/man_page.rb +73 -0
  75. data/rakelib/docs/site.rb +187 -0
  76. data/rakelib/docs/sources.rb +94 -0
  77. data/rakelib/docs/translation.rb +157 -0
  78. data/rakelib/docs.rake +62 -0
  79. data/rakelib/gettext.rake +30 -0
  80. data/rakelib/i18n.rake +199 -0
  81. data/reclaimable.gemspec +56 -0
  82. data/site/index.md +142 -0
  83. data/site/layout.html.erb +60 -0
  84. data/site/style.css +82 -0
  85. metadata +231 -0
@@ -0,0 +1,91 @@
1
+ module Reclaimable
2
+ # フォルダーの直下を getattrlistbulk(2) でまとめて読む(macOS)。
3
+ #
4
+ # Dir.children で名前を読んで名前ごとに lstat を呼ぶと、ファイル 1 つにつきシステムコールが 1 回要る。
5
+ # getattrlistbulk は、直下の全部の名前と属性(種類・リンク数・大きさ)を 1 回でまとめて返すので、
6
+ # フォルダー 1 つにつき数回で済む。走査の時間の大半は lstat なので、キャッシュの無い走査がおよそ半分の時間になる
7
+ # (benchmark/reports/ を参照)。
8
+ #
9
+ # setiopolicy_np(CloudFiles)と同じく Fiddle で呼ぶ。Fiddle が無い・macOS でないなどで使えないときは
10
+ # available? が false を返すので、呼ぶ側(Scanner#read_dir)はこれまでどおり lstat で読む
11
+ module BulkList
12
+ # <sys/attr.h>・<sys/vnode.h> の定数
13
+ ATTR_BIT_MAP_COUNT = 5
14
+ ATTR_CMN_NAME = 0x00000001
15
+ ATTR_CMN_OBJTYPE = 0x00000008
16
+ ATTR_CMN_RETURNED_ATTRS = 0x80000000
17
+ ATTR_FILE_LINKCOUNT = 0x00000001
18
+ ATTR_FILE_ALLOCSIZE = 0x00000004 # 実際にディスクを占有している量(lstat の blocks × 512 に当たる)
19
+ ATTR_FILE_DATALENGTH = 0x00000200 # 見かけの大きさ(lstat の size に当たる)
20
+ FILE_ATTRS = ATTR_FILE_LINKCOUNT | ATTR_FILE_ALLOCSIZE | ATTR_FILE_DATALENGTH
21
+ FSOPT_PACK_INVAL_ATTRS = 0x00000008 # 返せない属性も場所を空けて詰める(どの項目も同じ並びになる)
22
+ VREG = 1
23
+ VDIR = 2
24
+
25
+ # struct attrlist。求める属性は、名前・種類と、ファイルのリンク数・実占有・大きさ
26
+ ATTRLIST = [ATTR_BIT_MAP_COUNT, 0, ATTR_CMN_RETURNED_ATTRS | ATTR_CMN_NAME | ATTR_CMN_OBJTYPE, 0, 0, FILE_ATTRS, 0]
27
+ .pack("SSLLLLL").freeze
28
+ # 1 項目の並び: 項目の長さ、返ってきた属性(common・vol・dir・file・fork)、名前の位置と長さ、種類、
29
+ # リンク数、実占有、大きさ。名前の位置は「名前の位置と長さ」の欄(先頭から 24 バイト目)から数える
30
+ ENTRY = "LLLLLLlLLLqq".freeze
31
+ NAME_REF_OFFSET = 24
32
+ BUFFER_SIZE = 256 * 1024
33
+
34
+ FUNCTION = begin
35
+ require "fiddle"
36
+ Fiddle::Function.new(
37
+ Fiddle.dlopen(nil)["getattrlistbulk"],
38
+ [Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_SIZE_T, Fiddle::TYPE_UINT64_T],
39
+ Fiddle::TYPE_INT,
40
+ )
41
+ rescue LoadError, StandardError # Fiddle::DLError(関数が無い。macOS でないなど)は StandardError の一種
42
+ nil
43
+ end
44
+
45
+ module_function
46
+
47
+ def available? = !FUNCTION.nil?
48
+
49
+ # dir の直下を「小さいファイルの合計・子フォルダー名・大きいファイル名」にまとめる(Scanner#listing の形)。
50
+ # large 以上の大きさのファイルとハードリンクは、大きいファイルの側に入れる。
51
+ # 属性をもらえなかったものは名前をブロックに渡すので、ブロックは lstat で調べて、
52
+ # 大きいファイルなら :large、数えるならバイト数、無視するなら nil を返す。
53
+ # フォルダーを開けない・読めないときは Errno の例外になる(Dir.children と同じ)
54
+ def read(dir, large_threshold)
55
+ small = 0
56
+ subdirs = []
57
+ large = []
58
+ # 受け取り用のバッファーはスレッドごとに 1 つ持ち、使い回す
59
+ buf = (Thread.current[:reclaimable_bulk_list_buffer] ||= "\0".b * BUFFER_SIZE)
60
+ encoding = Encoding.find("filesystem") # Dir.children が返す名前と同じ文字コードにする
61
+ Dir.open(dir) do |d|
62
+ fd = d.fileno
63
+ # 1 回で返しきれないときは続きが返るので、0 件になるまで呼ぶ。GVL は Fiddle が手放す
64
+ while (count = FUNCTION.call(fd, ATTRLIST, buf, BUFFER_SIZE, FSOPT_PACK_INVAL_ATTRS)).positive?
65
+ offset = 0
66
+ count.times do
67
+ length, _common, _vol, _dir, file_attrs, _fork, name_offset, name_length, type, nlink, alloc, size =
68
+ buf.unpack(ENTRY, offset:)
69
+ # 名前の長さは終端の NUL を含む
70
+ name = buf.byteslice(offset + NAME_REF_OFFSET + name_offset, name_length - 1).force_encoding(encoding)
71
+ offset += length
72
+ if type == VDIR
73
+ subdirs << name
74
+ elsif file_attrs & FILE_ATTRS != FILE_ATTRS
75
+ case (found = yield(name))
76
+ when :large then large << name
77
+ when Integer then small += found
78
+ end
79
+ elsif type == VREG && (size >= large_threshold || nlink > 1)
80
+ large << name
81
+ else
82
+ small += alloc # 小さいファイルやシンボリックリンク自体
83
+ end
84
+ end
85
+ end
86
+ raise SystemCallError.new(dir, Fiddle.last_error) if count.negative?
87
+ end
88
+ [small, subdirs, large]
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,125 @@
1
+ require "json"
2
+ require "yaml"
3
+ require "time"
4
+
5
+ module Reclaimable
6
+ # 走査結果のキャッシュ(Marshal)を、人が読める表・JSON・YAML で書き出す。
7
+ # キャッシュはバイナリーで中身を確かめにくいので、何が記録されているかを見たり、ほかのツールで扱ったりするためのもの。
8
+ #
9
+ # キャッシュは 100 万フォルダーを超えることがあるので、全体を 1 つのオブジェクトにしてから変換せず、
10
+ # フォルダーごとに書き出す(JSON・YAML としては 1 つの文書になる)。
11
+ # ファイル名が UTF-8 として正しくないときは、JSON・YAML では置き換え文字(U+FFFD)にする
12
+ class CacheDump
13
+ include Util
14
+ include I18n
15
+
16
+ FORMATS = %w[text json yaml].freeze
17
+
18
+ def initialize(path, root:)
19
+ @path = path
20
+ @root = root
21
+ @data = ScanCache.read(path)
22
+ unless @data.is_a?(Hash) && @data[:version] == ScanCache::FORMAT_VERSION
23
+ raise ScanCache::VersionError, _("it was made by another version of reclaimable; run reclaimable once to remake it")
24
+ end
25
+
26
+ # キャッシュの中身は木なので、パスをキーにした平らな形に直してから書き出す
27
+ @nodes = @data[:tree] ? ScanCache.flatten(@data[:tree], root) : {}
28
+ end
29
+
30
+ def write(format, out = $stdout)
31
+ case format
32
+ when "text" then text(out)
33
+ when "json" then json(out)
34
+ when "yaml" then yaml(out)
35
+ else raise ArgumentError, format
36
+ end
37
+ end
38
+
39
+ private
40
+
41
+ # キャッシュファイル全体の情報。saved_at はファイルの更新時刻(最後に保存した時刻)
42
+ def meta
43
+ { "cache_file" => @path, "root" => @root, "saved_at" => File.mtime(@path).iso8601,
44
+ "format_version" => @data[:version], "large_file_threshold" => @data[:large],
45
+ "folders" => @nodes.size }
46
+ end
47
+
48
+ # フォルダーごとの記録。パス順に並べる。
49
+ # mtime: フォルダーの更新時刻(これが変わっていなければ、次の走査で一覧を読み直さない)
50
+ # small_files_bytes: 直下の小さいファイルの実占有バイト数の合計
51
+ # subdirectories: 直下の子フォルダーの名前
52
+ # large_files: 直下の大きいファイルとハードリンクの名前(大きいファイル、小さいハードリンクの順)
53
+ def records
54
+ return enum_for(:records) unless block_given?
55
+
56
+ @nodes.keys.sort.each do |path|
57
+ stamp, small, big, links, kids = @nodes[path]
58
+ yield({ "path" => path, "mtime" => Time.at(stamp / 1_000_000_000, stamp % 1_000_000_000, :nsec),
59
+ "small_files_bytes" => small, "subdirectories" => kids ? kids.keys : [],
60
+ # 小さいハードリンクは [名前, inode, 実占有, ...] と並んでいるので、名前だけ取り出す
61
+ "large_files" => [*big, *links&.each_slice(3)&.map(&:first)] })
62
+ end
63
+ end
64
+
65
+ # JSON・YAML に入れるときの形。時刻は ISO 8601(ナノ秒まで)、文字列は正しい UTF-8 にする
66
+ def portable(record)
67
+ record.merge("path" => clean(record["path"]), "mtime" => record["mtime"].iso8601(9),
68
+ "subdirectories" => record["subdirectories"].map { clean(it) },
69
+ "large_files" => record["large_files"].map { clean(it) })
70
+ end
71
+
72
+ def clean(str) = str.dup.force_encoding(Encoding::UTF_8).scrub
73
+
74
+ def text(out)
75
+ out.puts format(_("Cache file: %{path}"), path: tilde(@path))
76
+ out.puts format(_("Saved: %{time} / root: %{root} / %{count} folders / large files: %{large} or more"),
77
+ time: File.mtime(@path).strftime("%F %T"), root: tilde(@root), count: @nodes.size,
78
+ large: human(@data[:large]))
79
+ out.puts
80
+ out.puts [pad(_("Modified"), 19, left: true), pad(_("Small files"), 14), pad(_("Subfolders"), 14),
81
+ pad(_("Large files"), 14), _("Folder")].join(" ")
82
+ records do |r|
83
+ out.puts format("%-19s %14s %14d %14d %s", r["mtime"].strftime("%F %T"), human(r["small_files_bytes"]),
84
+ r["subdirectories"].size, r["large_files"].size, tilde(r["path"]))
85
+ end
86
+ end
87
+
88
+ # 見出しを表示幅でそろえる。日本語の訳は 1 文字が 2 桁ぶんなので、文字数では桁がずれる
89
+ def pad(str, width, left: false)
90
+ space = " " * [width - str.each_char.sum { it.bytesize > 1 ? 2 : 1 }, 0].max
91
+ left ? str + space : space + str
92
+ end
93
+
94
+ # { ...全体の情報..., "entries": [ {...}, {...} ] }
95
+ def json(out)
96
+ out.write(JSON.generate(meta).delete_suffix("}"), ',"entries":[')
97
+ records.each_with_index do |r, i|
98
+ out.write(i.zero? ? "\n" : ",\n", JSON.generate(portable(r)))
99
+ end
100
+ out.write("\n]}\n")
101
+ end
102
+
103
+ # 全体の情報のあとに entries: を続け、フォルダーごとの記録を列の項目として足していく。
104
+ # 記録は YAML のライブラリーを使わずに組み立てる(100 万件を 1 件ずつ YAML.dump すると 45 秒ほどかかるため)。
105
+ # 値は文字列・整数・文字列の列だけなので、文字列を JSON の書き方の二重引用符で囲めば YAML としても正しい
106
+ def yaml(out)
107
+ out.write(YAML.dump(meta), "entries:\n")
108
+ records do |r|
109
+ r = portable(r)
110
+ out.write("- path: #{JSON.generate(r['path'])}\n",
111
+ " mtime: #{JSON.generate(r['mtime'])}\n",
112
+ " small_files_bytes: #{r['small_files_bytes']}\n",
113
+ yaml_list("subdirectories", r["subdirectories"]),
114
+ yaml_list("large_files", r["large_files"]))
115
+ end
116
+ end
117
+
118
+ # 項目の中の文字列の列(項目の字下げに合わせて 2 桁下げる)。空なら [] と書く
119
+ def yaml_list(key, items)
120
+ return " #{key}: []\n" if items.empty?
121
+
122
+ " #{key}:\n#{items.map { " - #{JSON.generate(it)}\n" }.join}"
123
+ end
124
+ end
125
+ end
@@ -0,0 +1,168 @@
1
+ require "optparse"
2
+ require "etc"
3
+
4
+ module Reclaimable
5
+ # コマンドラインの入り口。引数を読み、出力先を開いてレポートを作る
6
+ class CLI
7
+ include Util
8
+ include I18n
9
+
10
+ def run(argv)
11
+ started = clock
12
+ opts = parse(argv)
13
+ # --ai-skill・--install-ai-skill のときは AI エージェント向けのスキルを扱うだけで、走査もレポートもしない
14
+ return AiSkill.new.show if opts[:ai_skill]
15
+ # DIR を省いた分は nil で入っているので、any? でなく empty? で調べる
16
+ return AiSkill.new.install(opts[:install_ai_skill].compact) unless opts[:install_ai_skill].empty?
17
+
18
+ # --dump-cache のときはキャッシュを書き出すだけで、走査もレポートもしない
19
+ return dump_cache(opts) if opts[:dump_cache]
20
+
21
+ config = load_config(opts[:config])
22
+ # --freeze・--unfreeze のときは設定ファイルを書き換えるだけで、レポートは作らない
23
+ return update_frozen(config, opts) if opts[:freeze].any? || opts[:unfreeze].any?
24
+
25
+ output = Output.open(save: opts[:save], dir: opts[:out_dir])
26
+ enable_jit
27
+ Report.new(opts, output:, started:, config:).run
28
+ ensure
29
+ # 終了時(中断を含む)にファイルを閉じ、どこに保存したかを知らせる
30
+ output&.close
31
+ end
32
+
33
+ private
34
+
35
+ # 走査は同じ処理をフォルダーの数だけ繰り返すので、JIT(YJIT)で 1 割ほど速くなる(benchmark/reports/ を参照)。
36
+ # 起動は少し遅くなるので、--help などすぐ終わる場合には有効にせず、走査を始める前にだけ有効にする。
37
+ # YJIT 無しでビルドされた Ruby では何もしない
38
+ def enable_jit
39
+ RubyVM::YJIT.enable if defined?(RubyVM::YJIT) && !RubyVM::YJIT.enabled?
40
+ rescue StandardError
41
+ nil # 有効にできなくても、遅くなるだけで結果は変わらない
42
+ end
43
+
44
+ # 起点(-d)ごとのキャッシュを、指定の形式で標準出力に書き出す。
45
+ # head などにつないで途中で読むのをやめられても、エラーを出さずに終える
46
+ def dump_cache(opts)
47
+ path = ScanCache.path_for(opts[:cache_dir], opts[:root])
48
+ unless File.file?(path)
49
+ abort format(_("There is no cache for %{root} yet (%{path}). Run reclaimable once to make it."),
50
+ root: tilde(opts[:root]), path: tilde(path))
51
+ end
52
+ CacheDump.new(path, root: opts[:root]).write(opts[:dump_cache])
53
+ rescue Errno::EPIPE
54
+ nil
55
+ rescue ScanCache::VersionError => e
56
+ abort format(_("Cannot read the cache %{path}: %{error}"), path: tilde(path), error: e.message)
57
+ rescue Zlib::Error, TypeError, ArgumentError => e
58
+ abort format(_("Cannot read the cache %{path}: %{error}"), path: tilde(path), error: "#{e.class}: #{e.message}")
59
+ end
60
+
61
+ # 壊れた設定ファイルを読み飛ばして走査を続けると、--freeze したときに中身を上書きして消してしまうので止める
62
+ def load_config(path)
63
+ Config.load(path || Config.default_path)
64
+ rescue Config::Error, SystemCallError, ArgumentError, TypeError => e
65
+ abort format(_("Cannot read the config file %{path}: %{error}"), path: tilde(path || Config.default_path),
66
+ error: e.message)
67
+ end
68
+
69
+ # フォルダーを測ってサイズを設定ファイルに書く(固定する)。固定を外す。
70
+ # 測るときも、クラウド上にしか無いフォルダーで止まらないようダウンロードを止めておく
71
+ def update_frozen(config, opts)
72
+ skip = []
73
+ if (why = CloudFiles.stop_downloads)
74
+ skip = CloudFiles::DIRS
75
+ warn format(_("Cannot stop downloading cloud-only files, so %{dirs} will not be scanned (%{reason})"),
76
+ dirs: skip.map { tilde(it) }.join(p_("list separator", ", ")), reason: why)
77
+ end
78
+ opts[:unfreeze].each do |dir|
79
+ if config.unfreeze_dir(dir)
80
+ puts format(_("Unfroze %{dir}"), dir: tilde(dir))
81
+ else
82
+ warn format(_("%{dir} was not frozen"), dir: tilde(dir))
83
+ end
84
+ end
85
+ enable_jit if opts[:freeze].any?
86
+ opts[:freeze].each do |dir|
87
+ st = File.stat(dir)
88
+ raise Errno::ENOTDIR, dir unless st.directory?
89
+
90
+ warn format(_("Measuring %{dir} with %{jobs} threads..."), dir: tilde(dir), jobs: opts[:jobs])
91
+ # 巨大ファイルは記録しなくてよいので、しきい値は届かない大きさにする
92
+ bytes = Scanner.new(dir, big_threshold: 1 << 62, jobs: opts[:jobs], skip:).scan
93
+ config.freeze_dir(dir, bytes:, mtime: Config.mtime_of(st))
94
+ puts format(_("Froze %{dir} at %{size}. It will not be scanned from now on."), dir: tilde(dir), size: human(bytes))
95
+ rescue SystemCallError => e
96
+ warn format(_("Cannot freeze %{dir}: %{error}"), dir: tilde(dir), error: e.message)
97
+ end
98
+ config.save
99
+ puts format(_("Saved the config file: %{path}"), path: tilde(config.path))
100
+ end
101
+
102
+ # gem に入れた man page の置き場所。rake man で作るので、ソースのまま動かすときは無いことがある
103
+ MAN_DIR = File.expand_path("../../man", __dir__)
104
+
105
+ # man page を、文言と同じ言語(LC_ALL・LC_MESSAGES・LANG で決まる)で開く。その言語の版が無ければ英語。
106
+ # man はパス(/ を含む引数)を渡すと、MANPATH を探さずにそのファイルを開く
107
+ def open_manual
108
+ path = [I18n.locale.language, "en"].map { File.join(MAN_DIR, "reclaimable.#{it}.1") }.find { File.file?(it) }
109
+ unless path
110
+ abort format(_("Cannot find the manual in %{dir}. When running from the source, make it with rake man first."),
111
+ dir: tilde(MAN_DIR))
112
+ end
113
+ exec("man", path)
114
+ rescue SystemCallError => e
115
+ abort format(_("Cannot open the manual: %{error}"), error: e.message)
116
+ end
117
+
118
+ def parse(argv)
119
+ # 置き場所の決め方は Paths を参照
120
+ opts = { top: 20, min_mb: 1024, root: HOME, save: true, out_dir: Paths.log_dir, cache_dir: Paths.cache_dir,
121
+ jobs: [Etc.nprocessors, 8].min, fresh: false, config: nil, freeze: [], unfreeze: [], dump_cache: nil,
122
+ ai_skill: false, install_ai_skill: [] }
123
+ OptionParser.new do |o|
124
+ o.banner = _("Usage: reclaimable [options]")
125
+ o.on("-n N", Integer, _("Number of entries in each ranking (default: 20)")) { opts[:top] = it }
126
+ o.on("-s MB", Integer, _("Smallest size, in MB, that counts as a large file (default: 1024)")) { opts[:min_mb] = it }
127
+ o.on("-d DIR", _("Directory to start scanning from (default: your home directory)")) { opts[:root] = File.expand_path(it) }
128
+ o.on("-o DIR", format(_("Directory to save the report and the log in (default: %{dir})"), dir: tilde(opts[:out_dir]))) do
129
+ opts[:out_dir] = File.expand_path(it)
130
+ end
131
+ o.on("--[no-]save", _("Also save the report and the log to files (default: save)")) { opts[:save] = it }
132
+ o.on("-j N", Integer, format(_("Number of threads that scan in parallel (default: %{jobs})"), jobs: opts[:jobs])) do
133
+ opts[:jobs] = it.clamp(1, 64)
134
+ end
135
+ o.on("--fresh", _("Ignore the cached scan results and scan everything again")) { opts[:fresh] = true }
136
+ o.on("--freeze DIR", _("Measure DIR once, save its size to the config file, and skip it in later scans " \
137
+ "(for large folders that never change). Can be given more than once")) do
138
+ opts[:freeze] << File.expand_path(it)
139
+ end
140
+ o.on("--unfreeze DIR", _("Remove DIR from the frozen folders, so it is scanned again")) do
141
+ opts[:unfreeze] << File.expand_path(it)
142
+ end
143
+ o.on("--dump-cache [FORMAT]", CacheDump::FORMATS,
144
+ format(_("Print the cached scan results for the start directory (-d) as %{formats} (default: text), " \
145
+ "without scanning"), formats: CacheDump::FORMATS.join(p_("list separator", ", ")))) do
146
+ opts[:dump_cache] = it || "text"
147
+ end
148
+ o.on("--config FILE", format(_("Config file to use (default: %{file})"), file: tilde(Config.default_path))) do
149
+ opts[:config] = File.expand_path(it)
150
+ end
151
+ o.on("--ai-skill", _("Show the skill for AI agents (Claude Code, Codex, and others) and how to install it")) do
152
+ opts[:ai_skill] = true
153
+ end
154
+ # DIR を省いたときは nil を入れておき、どこに入れるかを聞く
155
+ o.on("--install-ai-skill [DIR]", _("Install the skill for AI agents in the skill directory DIR, as DIR/reclaimable. " \
156
+ "Without DIR, ask where to install it. Can be given more than once")) do
157
+ opts[:install_ai_skill] << (it && File.expand_path(it))
158
+ end
159
+ # --help と同じく、ほかのオプションを読まずにすぐ開く
160
+ o.on("--man", _("Show the manual")) { open_manual }
161
+ end.parse!(argv)
162
+ opts
163
+ rescue OptionParser::ParseError => e
164
+ # 知らないオプションや、--dump-cache に無い形式を渡されたとき。バックトレースではなく理由だけを出す
165
+ abort format(_("%{error} (see reclaimable --help)"), error: e.message)
166
+ end
167
+ end
168
+ end
@@ -0,0 +1,33 @@
1
+ module Reclaimable
2
+ # iCloud Drive・Google Drive などのクラウド上にしか実体が無いファイルやフォルダー(dataless)の扱い。
3
+ # 何もしないと、そうしたフォルダーの一覧を読んだ時点で macOS がダウンロードを始め、
4
+ # それが終わるまで(通信やクラウド側の具合によっては無期限に)待たされる。
5
+ # 容量調べのためにダウンロードするのは本末転倒なので、このプロセスではダウンロードさせない。
6
+ module CloudFiles
7
+ extend I18n
8
+
9
+ # ダウンロードを止められなかったときに、代わりに降りないでおく場所
10
+ DIRS = [File.join(HOME, "Library/Mobile Documents"), File.join(HOME, "Library/CloudStorage")].freeze
11
+
12
+ # <sys/resource.h> の定数
13
+ IOPOL_TYPE_VFS_MATERIALIZE_DATALESS_FILES = 3
14
+ IOPOL_SCOPE_PROCESS = 0
15
+ IOPOL_MATERIALIZE_DATALESS_FILES_OFF = 1
16
+
17
+ module_function
18
+
19
+ # このプロセスでは dataless なファイル・フォルダーをダウンロードしないよう設定する。
20
+ # 以後、それらの中身を読もうとすると待たずに Errno::EDEADLK になる。
21
+ # setiopolicy_np を呼ぶのに Fiddle(Ruby 4.0 では bundled gem)を使う。
22
+ # Fiddle が無い・macOS でないなどで設定できなければ、理由を返す(できたら nil)
23
+ def stop_downloads
24
+ require "fiddle"
25
+ setiopolicy = Fiddle::Function.new(Fiddle.dlopen(nil)["setiopolicy_np"], [Fiddle::TYPE_INT] * 3, Fiddle::TYPE_INT)
26
+ rc = setiopolicy.call(IOPOL_TYPE_VFS_MATERIALIZE_DATALESS_FILES, IOPOL_SCOPE_PROCESS,
27
+ IOPOL_MATERIALIZE_DATALESS_FILES_OFF)
28
+ rc.zero? ? nil : format(_("setiopolicy_np failed (errno %{errno})"), errno: Fiddle.last_error)
29
+ rescue LoadError, StandardError => e # Fiddle::DLError(関数が無いなど)は StandardError の一種
30
+ "#{e.class}: #{e.message}"
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,100 @@
1
+ require "yaml"
2
+ require "date"
3
+ require "fileutils"
4
+ require "time"
5
+
6
+ module Reclaimable
7
+ # 設定ファイル(YAML)。今のところ「固定したフォルダー」だけを持つ。
8
+ #
9
+ # 固定したフォルダーは、中身が変わらないと分かっている大きなフォルダー(古いサイトのコピーなど)。
10
+ # --freeze で 1 度だけ測ってサイズをここに書き、以後の走査ではその中へ降りずにこのサイズを使う。
11
+ # ファイル数が多いと走査の時間の大半を占めることがあるので、それを省くためのもの。
12
+ #
13
+ # 置き場所は Paths.config_dir(XDG_CONFIG_HOME、macOS の規約、XDG の既定の順)。
14
+ # パスは ~ で始まる形で書く(ホームの場所が変わっても使え、手で読み書きしやすいように)。
15
+ # 手で書いたコメントは、--freeze・--unfreeze で書き直すと消える(YAML のライブラリーがコメントを保てないため)
16
+ class Config
17
+ include Util
18
+ include I18n
19
+
20
+ FILE = "config.yml"
21
+
22
+ # 設定ファイルが読めない・形がおかしい
23
+ class Error < StandardError; end
24
+
25
+ # 固定したフォルダー 1 つ。mtime はフォルダー自身の更新時刻(ナノ秒)で、
26
+ # 直下の顔ぶれが変わったか(測り直したほうがよいか)の目安に使う
27
+ Frozen = Data.define(:path, :bytes, :mtime, :measured_at)
28
+
29
+ def self.default_path = File.join(Paths.config_dir, FILE)
30
+
31
+ attr_reader :path
32
+
33
+ def self.load(path = default_path) = new(path)
34
+
35
+ # 無いファイルや空のファイルは空の設定として扱う(path が nil なら、ファイルを持たない空の設定)。
36
+ # 壊れているファイルは、気づかずに上書きして消さないよう例外にする。
37
+ # 手で書いた日時(引用符なしの 2026-11-15 など)は YAML では Time・Date になるので、それだけは読み込みを許す
38
+ def initialize(path)
39
+ @path = path
40
+ @data = (path && File.file?(path) && YAML.safe_load_file(path, permitted_classes: [Time, Date])) || {}
41
+ raise Error, format(_("%{path} is not a mapping"), path:) unless @data.is_a?(Hash)
42
+
43
+ frozen # 中身もここで確かめ、走査を始めてから落ちないようにする
44
+ rescue Psych::Exception => e
45
+ raise Error, e.message
46
+ end
47
+
48
+ # 固定したフォルダーの一覧(パスは展開済み)
49
+ def frozen
50
+ entries = @data["frozen"] || {}
51
+ raise Error, format(_("%{key} in %{path} is not a mapping"), key: "frozen", path: @path) unless entries.is_a?(Hash)
52
+
53
+ entries.map do |path, h|
54
+ raise Error, format(_("The entry for %{path} has no size (bytes)"), path:) unless h.is_a?(Hash) && h["bytes"]
55
+
56
+ Frozen.new(path: File.expand_path(path), bytes: Integer(h["bytes"]), mtime: h["mtime"],
57
+ measured_at: to_time(h["measured_at"]))
58
+ end
59
+ end
60
+
61
+ # { 展開済みのパス => バイト数 }。Scanner に渡す形
62
+ def frozen_sizes = frozen.to_h { [it.path, it.bytes] }
63
+
64
+ def freeze_dir(path, bytes:, mtime:)
65
+ (@data["frozen"] ||= {})[tilde(path)] = { "bytes" => bytes, "mtime" => mtime, "measured_at" => Time.now.iso8601 }
66
+ end
67
+
68
+ # 固定を外す。書いてあったら true
69
+ def unfreeze_dir(path)
70
+ frozen = @data["frozen"] or return false
71
+ !frozen.delete(tilde(path)).nil?
72
+ end
73
+
74
+ # 書きかけのファイルが残らないよう、一時ファイルに書いてから置き換える。
75
+ # 先頭に、何のファイルかと、コメントが消えることを書いておく
76
+ def save
77
+ FileUtils.mkdir_p(File.dirname(@path))
78
+ tmp = "#{@path}.tmp"
79
+ header = _("reclaimable config. --freeze and --unfreeze rewrite this file, so comments are not kept.")
80
+ File.write(tmp, "# #{header}\n#{YAML.dump(@data)}")
81
+ File.rename(tmp, @path)
82
+ end
83
+
84
+ # フォルダー自身の更新時刻(ナノ秒)。直下でファイルの追加・削除・改名があると変わる
85
+ def self.mtime_of(st) = st.mtime.to_i * 1_000_000_000 + st.mtime.nsec
86
+
87
+ private
88
+
89
+ def to_time(value)
90
+ case value
91
+ when nil then nil
92
+ when Time then value
93
+ when Date then value.to_time
94
+ else Time.iso8601(value.to_s)
95
+ end
96
+ rescue ArgumentError
97
+ raise Error, format(_("Cannot read the date %{value}"), value:)
98
+ end
99
+ end
100
+ end
@@ -0,0 +1,24 @@
1
+ require "gettext"
2
+
3
+ module Reclaimable
4
+ # 画面・レポート・ログの文言の翻訳(gettext)。
5
+ # 原文は英語で、訳は po/<言語>/reclaimable.po に書き、rake gettext で locale/ の .mo に変換する。
6
+ # 言語は環境変数 LC_ALL・LC_MESSAGES・LANG の順で決まり、訳が無ければ英語のまま出す。
7
+ #
8
+ # 使う側は include(モジュールの関数からなら extend)して _ と n_ を呼ぶ。
9
+ # 翻訳対象を抜き出す rxgettext は _( と n_( の呼び出しを探すので、文言は必ずリテラルで渡す
10
+ module I18n
11
+ extend GetText
12
+
13
+ # 端末やファイルの文字コードは UTF-8 とみなす(LANG=ja_JP のように文字コードの無い指定でも文字化けさせない)
14
+ bindtextdomain("reclaimable", path: File.expand_path("../../locale", __dir__), output_charset: "UTF-8")
15
+
16
+ def _(msgid) = I18n.gettext(msgid)
17
+
18
+ # 数で形が変わる文言(英語の単数・複数)。日本語では区別しない
19
+ def n_(msgid, msgid_plural, n) = I18n.ngettext(msgid, msgid_plural, n)
20
+
21
+ # 同じ原文でも使う場面で訳し分けたい文言(区切りの「, 」など)。msgctxt に場面を書く
22
+ def p_(msgctxt, msgid) = I18n.pgettext(msgctxt, msgid)
23
+ end
24
+ end
@@ -0,0 +1,89 @@
1
+ require "json"
2
+
3
+ module Reclaimable
4
+ # 走査の前に決めておく、サイズを個別に知りたい場所
5
+ module Locations
6
+ extend I18n
7
+ module_function
8
+
9
+ # 消しても再ダウンロード・再生成できることが多い既知の場所と、消したらどうなるかの目安。
10
+ # [パス, 説明] の配列を返す
11
+ def known(output)
12
+ brew_cache = output.capture("brew", "--cache")&.strip
13
+ [
14
+ [TRASH, _("Trash. Emptying it frees the space right away")],
15
+ ["~/Library/Caches", _("App caches. Quit the apps before deleting the contents; they are usually recreated as needed")],
16
+ # brew cleanup は既定では 120 日より古いものしか消さないので、全部消すときのオプションを示す
17
+ [brew_cache, _("Homebrew download cache. brew cleanup --prune=all removes all of it")],
18
+ ["~/.cache", _("Caches of command-line tools (pip, Hugging Face, and others)")],
19
+ ["~/.cache/huggingface", _("Hugging Face models and datasets. They can be downloaded again")],
20
+ ["~/.npm", _("npm cache. npm cache clean --force removes it")],
21
+ ["~/.yarn", _("yarn cache and versions")],
22
+ ["~/Library/pnpm/store", _("pnpm store. pnpm store prune removes unused packages")],
23
+ ["~/.bun/install/cache", _("bun cache")],
24
+ ["~/.nodenv/versions", _("Node.js versions installed with nodenv. Remove unused ones with nodenv uninstall")],
25
+ ["~/.cargo/registry", _("Crate sources and archives. They are downloaded again on the next build")],
26
+ ["~/.cargo/git", _("Crates from git dependencies. They are downloaded again when needed")],
27
+ ["~/.rustup/toolchains", _("Rust toolchains. Remove unused ones with rustup toolchain uninstall")],
28
+ ["~/.rubies", _("Rubies installed with ruby-install and similar tools. Unused versions can be removed")],
29
+ ["~/.pub-cache", _("Dart/Flutter package cache. It can be downloaded again")],
30
+ ["~/.gradle", _("Gradle cache")],
31
+ ["~/.android", _("Android emulator (AVD) images and more")],
32
+ ["~/Library/Android/sdk", _("Android SDK. Remove unused API levels and images with SDK Manager")],
33
+ ["~/.cocoapods", _("CocoaPods spec repositories and cache")],
34
+ ["~/Library/Developer/Xcode/DerivedData", _("Xcode intermediate build files. They are recreated on the next build")],
35
+ ["~/Library/Developer/Xcode/Archives", _("Xcode archives. Candidates for removal once shipped and no longer needed")],
36
+ ["~/Library/Developer/Xcode/iOS DeviceSupport", _("Symbols for debugging on devices. Those for old iOS versions are not needed")],
37
+ ["~/Library/Developer/CoreSimulator", _("iOS simulators. Remove old ones with xcrun simctl delete unavailable")],
38
+ ["~/.ollama/models", _("Ollama models. Remove unused ones with ollama rm")],
39
+ ["~/.lmstudio", _("LM Studio models")],
40
+ ["~/.keras", _("Keras datasets and model cache")],
41
+ ["~/ComfyUI-Installs", _("ComfyUI environments. Old installations are candidates for removal")],
42
+ ["~/ComfyUI-Shared", _("ComfyUI shared models")],
43
+ ["~/VirtualBox VMs", _("VirtualBox virtual machines. Remove unused VMs from VirtualBox")],
44
+ ["~/.vagrant.d/boxes", _("Vagrant boxes. vagrant box prune removes old versions")],
45
+ ["~/.tebako", _("tebako build cache")],
46
+ ["~/.stack", _("GHC and packages for Haskell Stack")],
47
+ ["~/.deno", _("Deno cache")],
48
+ ["~/.wp-env", _("WordPress environments for wp-env")],
49
+ ["~/Library/Application Support/MobileSync/Backup", _("Local iPhone/iPad backups. Remove old ones from Finder")],
50
+ *gem_dirs.map { [File.join(it, "doc"), _("Gem documentation (rdoc, ri). It can be rebuilt with gem rdoc")] },
51
+ ].filter_map { |path, note| [File.expand_path(path), note] if path }
52
+ end
53
+
54
+ # Docker Desktop・Colima/Lima・OrbStack・Podman・Rancher Desktop のデータ置き場。
55
+ # 既定の場所の中を指す DataFolder は重複になるので除く
56
+ def container_dirs
57
+ docker_default = File.join(HOME, "Library/Containers/com.docker.docker")
58
+ docker_data = docker_desktop_data_folder
59
+ docker_data = nil if docker_data && Util.under?(docker_data, docker_default)
60
+ [
61
+ docker_data, docker_default,
62
+ *%w[~/.colima ~/.lima ~/.orbstack].map { File.expand_path(it) },
63
+ *Dir.glob(File.join(HOME, "Library/Group Containers/*.dev.orbstack")),
64
+ File.expand_path("~/.local/share/containers"),
65
+ File.expand_path("~/Library/Application Support/rancher-desktop"),
66
+ File.expand_path("~/.docker"),
67
+ ].compact.uniq
68
+ end
69
+
70
+ # Docker Desktop はディスクイメージの保存場所を設定で変えられるので、設定ファイルから読む。
71
+ # 版によってファイル名・キー名が違うため両方試す
72
+ def docker_desktop_data_folder
73
+ dir = File.join(HOME, "Library/Group Containers/group.com.docker")
74
+ %w[settings-store.json settings.json].each do |name|
75
+ json = JSON.parse(File.read(File.join(dir, name)))
76
+ folder = json["DataFolder"] || json["dataFolder"]
77
+ return folder unless folder.nil? || folder.empty?
78
+ rescue SystemCallError, JSON::ParserError
79
+ next # ファイルが無い・読めない・壊れている場合は次の候補へ
80
+ end
81
+ nil
82
+ end
83
+
84
+ # ユーザー領域の gem 置き場(Ruby の ABI 版ごとのフォルダー)
85
+ def gem_dirs
86
+ Dir.glob([File.join(HOME, ".gem/ruby/*"), File.join(HOME, ".local/share/gem/ruby/*")]).select { File.directory?(it) }
87
+ end
88
+ end
89
+ end