Class: Fontist::IndexCLI

Inherits:
Thor
  • Object
show all
Includes:
CLI::ClassOptions
Defined in:
lib/fontist/index_cli.rb

Instance Method Summary collapse

Methods included from CLI::ClassOptions

#handle_class_options, included, #log_level

Instance Method Details

#clearObject



224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/fontist/index_cli.rb', line 224

def clear
  handle_class_options(options)

  index_path = Fontist.system_index_path
  if File.exist?(index_path)
    File.delete(index_path)
    Fontist.ui.success("System font index cleared: #{index_path}")
  else
    Fontist.ui.say("System font index does not exist")
  end

  CLI::STATUS_SUCCESS
rescue Fontist::Errors::GeneralError => e
  Fontist.ui.error(e.message)
  CLI::STATUS_UNKNOWN_ERROR
end

#infoObject



336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'lib/fontist/index_cli.rb', line 336

def info
  handle_class_options(options)

  index_path = Fontist.system_index_path

  if File.exist?(index_path)
    index = Fontist::SystemIndex.system_index
    stats = {
      path: index_path,
      size: "#{(File.size(index_path) / 1024.0).round(2)} KB",
      fonts: index.fonts&.size || 0,
      last_scan: File.mtime(index_path).strftime("%Y-%m-%d %H:%M:%S"),
    }

    puts Paint["System Font Index Information:", :cyan, :bright]
    puts Paint["-" * 80, :cyan]
    puts "  Path:       #{Paint[stats[:path], :white]}"
    puts "  Size:       #{Paint[stats[:size], :yellow]}"
    puts "  Fonts:      #{Paint[stats[:fonts], :yellow]}"
    puts "  Last scan:  #{Paint[stats[:last_scan], :green]}"
    puts Paint["-" * 80, :cyan]
  else
    Fontist.ui.say("System font index does not exist")
    Fontist.ui.say("Run 'fontist index rebuild' to create it")
  end

  CLI::STATUS_SUCCESS
rescue Fontist::Errors::GeneralError => e
  Fontist.ui.error(e.message)
  CLI::STATUS_UNKNOWN_ERROR
end

#listObject



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/fontist/index_cli.rb', line 187

def list
  handle_class_options(options)

  index = Fontist::SystemIndex.system_index
  fonts_data = index.fonts.map do |font|
    {
      path: font.path,
      family_name: font.family_name,
      full_name: font.full_name,
      subfamily: font.subfamily,
      preferred_family_name: font.preferred_family_name,
      preferred_subfamily_name: font.preferred_subfamily_name,
    }
  end

  # Apply limit if specified
  fonts_data = fonts_data.take(options[:limit]) if options[:limit]

  case options[:format].downcase
  when "json"
    require "json"
    puts JSON.pretty_generate(fonts_data)
  when "yaml"
    require "yaml"
    puts YAML.dump(fonts_data)
  else
    Fontist.ui.error("Unknown format: #{options[:format]}. Use 'yaml' or 'json'.")
    return CLI::STATUS_UNKNOWN_ERROR
  end

  CLI::STATUS_SUCCESS
rescue Fontist::Errors::GeneralError => e
  Fontist.ui.error(e.message)
  CLI::STATUS_UNKNOWN_ERROR
end

#pathObject



171
172
173
174
175
176
177
178
179
180
# File 'lib/fontist/index_cli.rb', line 171

def path
  handle_class_options(options)

  puts Fontist.system_index_path

  CLI::STATUS_SUCCESS
rescue Fontist::Errors::GeneralError => e
  Fontist.ui.error(e.message)
  CLI::STATUS_UNKNOWN_ERROR
end

#rebuildObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/fontist/index_cli.rb', line 12

def rebuild
  handle_class_options(options)

  # Track overall timing
  start_time = Time.now

  # Always create stats for progress display
  stats = Fontist::IndexStats.new

  puts Paint["Rebuilding system font index from scratch...", :cyan, :bright]
  puts Paint["-" * 80, :cyan]

  # Show platform information
  os = Fontist::Utils::System.user_os
  os_name = case os
            when :macosx then "macOS"
            when :linux then "Linux"
            when :windows then "Windows"
            else os.to_s.capitalize
            end
  puts Paint["Platform: ", :white] + Paint[os_name, :yellow, :bright]
  puts

  # Track directory scanning time
  scan_start = Time.now

  # Show directories being scanned with spinner and counts
  puts Paint["Scanning directories:", :cyan]
  system_config = SystemFont.system_config
  templates = system_config["system"][os.to_s]["paths"]
  expanded_paths = SystemFont.expand_paths(templates)

  spinner_chars = ["", "", "", "", "", "", "", "", "", ""]

  # Show spinner while scanning
  all_fonts = []
  spinner_thread = Thread.new do
    spinner_idx = 0
    loop do
      print "\r  #{Paint[spinner_chars[spinner_idx % spinner_chars.length],
                         :cyan]} Scanning font directories..."
      $stdout.flush
      spinner_idx += 1
      sleep 0.1
    end
  end

  # Actually glob to find all font files (system fonts)
  # Uses lowercase extensions since font files are normalized to
  # lowercase extensions during installation for cross-platform consistency
  expanded_paths.each do |pattern|
    all_fonts.concat(Dir.glob(pattern).select { |f| File.file?(f) })
  end

  # Add fontist-managed fonts
  # Uses case-insensitive glob patterns that work on all platforms,
  # including Linux where File::FNM_CASEFOLD is ignored
  fontist_patterns = Fontist::Utils.font_file_patterns(Fontist.fonts_path.join("**").to_s)
  fontist_fonts = fontist_patterns.flat_map { |pattern| Dir.glob(pattern) }
    .select { |f| File.file?(f) }
  all_fonts.concat(fontist_fonts)

  spinner_thread.kill
  print "\r#{' ' * 80}\r"

  scan_time = Time.now - scan_start

  # Group fonts by their parent directory
  fonts_by_dir = {}
  all_fonts.each do |font_path|
    dir = File.dirname(font_path)
    fonts_by_dir[dir] ||= 0
    fonts_by_dir[dir] += 1
  end

  # Sort directories and display with counts
  sorted_dirs = fonts_by_dir.keys.sort
  sorted_dirs.each do |dir|
    count = fonts_by_dir[dir]
    status = Paint["", :green]
    count_display = Paint[" (#{count} #{count == 1 ? 'font' : 'fonts'})",
                          :yellow]

    # Mark fontist managed directories
    is_fontist = dir.start_with?(Fontist.fonts_path.to_s)
    managed_tag = if is_fontist
                    " #{Paint['(fontist managed)', :black,
                              :bright]}"
                  else
                    ""
                  end

    puts "  #{status} #{Paint[dir, :white]}#{count_display}#{managed_tag}"
  end

  total_font_files = all_fonts.size
  puts
  puts Paint["Total font files found: ",
             :white] + Paint[total_font_files.to_s, :yellow, :bright]
  puts Paint["(Note: Font collections like .ttc files contain multiple fonts)",
             :black, :bright]
  puts Paint["-" * 80, :cyan]
  puts

  # Track indexing time
  indexing_start = Time.now

  # Always show progress during indexing
  index = Fontist::SystemIndex.system_index
  index.rebuild(verbose: true, stats: stats)

  indexing_time = Time.now - indexing_start

  if options[:verbose]
    stats.print_summary(verbose: true)
  end

  if options[:output]
    index.to_file(options[:output])
    Fontist.ui.success("Index saved to: #{options[:output]}")
  end

  # Calculate total time
  total_time = Time.now - start_time

  # Show final summary with collection info and timing
  total_indexed = index.fonts.size
  collection_fonts = total_indexed - total_font_files

  puts
  puts Paint["  Index file: ",
             :white] + Paint[Fontist.system_index_path, :cyan]
  puts Paint["✓ System font index rebuilt successfully", :green, :bright]
  puts Paint["  Font files processed: ",
             :white] + Paint[total_font_files.to_s, :yellow, :bright]
  puts Paint["  Total fonts indexed:  ",
             :white] + Paint[total_indexed.to_s, :yellow, :bright]
  if collection_fonts.positive?
    puts Paint["  Fonts from collections: ",
               :white] + Paint[collection_fonts.to_s,
                               :cyan] + Paint[" (.ttc/.otc files)", :black,
                                              :bright]
  end
  puts Paint["-" * 80, :cyan]
  puts Paint["⏱ Timing:", :cyan, :bright]
  puts Paint["  Directory scanning: ",
             :white] + Paint["#{scan_time.round(2)}s", :yellow]
  puts Paint["  Font indexing:       ",
             :white] + Paint["#{indexing_time.round(2)}s", :yellow]
  puts Paint["  Total time:          ",
             :white] + Paint["#{total_time.round(2)}s", :green, :bright]

  CLI::STATUS_SUCCESS
rescue Fontist::Errors::GeneralError => e
  Fontist.ui.error(e.message)
  CLI::STATUS_UNKNOWN_ERROR
end

#updateObject



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/fontist/index_cli.rb', line 244

def update
  handle_class_options(options)

  start_time = Time.now

  puts Paint["Updating system font index incrementally...", :cyan, :bright]
  puts Paint["-" * 80, :cyan]

  # Get the system index
  index = Fontist::SystemIndex.system_index

  # Check if index exists
  unless File.exist?(Fontist.system_index_path)
    Fontist.ui.say("System font index does not exist")
    Fontist.ui.say("Run 'fontist index rebuild' to create it")
    return CLI::STATUS_UNKNOWN_ERROR
  end

  # Get initial stats
  initial_font_count = index.fonts&.size || 0
  index_mtime_before = File.mtime(Fontist.system_index_path)

  puts Paint["Initial font count: ",
             :white] + Paint[initial_font_count.to_s, :yellow]
  puts Paint["Last updated: ",
             :white] + Paint[index_mtime_before.strftime("%Y-%m-%d %H:%M:%S"),
                             :green]
  puts

  # Track the update operation
  update_start = Time.now

  # Force a rebuild to see what has changed
  # This will trigger index_changed? checks and show if it needs a full scan
  stats = Fontist::IndexStats.new if options[:verbose]

  # Reset verification to force re-check
  index.reset_verification!

  # Access the index to trigger update if needed
  updated_index = index.index

  update_time = Time.now - update_start

  # Get final stats
  final_font_count = updated_index.size
  index_mtime_after = File.exist?(Fontist.system_index_path) ? File.mtime(Fontist.system_index_path) : index_mtime_before
  was_updated = index_mtime_after > index_mtime_before

  total_time = Time.now - start_time

  # Show results
  puts
  if was_updated
    puts Paint["✓ System font index updated", :green, :bright]
  else
    puts Paint["No changes detected", :yellow]
  end

  puts Paint["-" * 80, :cyan]
  puts Paint["⏱ Timing:", :cyan, :bright]
  puts Paint["  Update check: ",
             :white] + Paint["#{update_time.round(2)}s", :yellow]
  puts Paint["  Total time:   ",
             :white] + Paint["#{total_time.round(2)}s", :green, :bright]
  puts Paint["-" * 80, :cyan]
  puts Paint["Fonts:", :cyan, :bright]
  puts Paint["  Before: ", :white] + Paint[initial_font_count.to_s, :yellow]
  puts Paint["  After:  ", :white] + Paint[final_font_count.to_s, :yellow]
  if final_font_count != initial_font_count
    diff = final_font_count - initial_font_count
    diff_str = diff.positive? ? "+#{diff}" : diff.to_s
    diff_color = if diff.positive?
                   :green
                 else
                   (diff.negative? ? :red : :yellow)
                 end
    puts Paint["  Change: ", :white] + Paint[diff_str, diff_color]
  end

  if options[:verbose] && stats
    puts
    stats.print_summary(verbose: true)
  end

  CLI::STATUS_SUCCESS
rescue Fontist::Errors::GeneralError => e
  Fontist.ui.error(e.message)
  CLI::STATUS_UNKNOWN_ERROR
end