Class: Mfd::Cli

Inherits:
Object
  • Object
show all
Defined in:
lib/mfd/cli.rb

Constant Summary collapse

NOW =
Time.now

Instance Method Summary collapse

Constructor Details

#initializeCli

Returns a new instance of Cli.



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/mfd/cli.rb', line 9

def initialize
  @predicates = ['(true)']
  @print_command = false
  @ascii_null = false
  @live = false
  @count = false
  @list_kinds = false
  @list_content_types = false

  @opt = OptionParser.new
  declare_options!
end

Instance Method Details

#calculate_size(size_str) ⇒ Object



351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/mfd/cli.rb', line 351

def calculate_size(size_str)
  case size_str
  when /(\d+)t$/i
    Regexp.last_match(1).to_i * 1024**4
  when /(\d+)g$/i
    Regexp.last_match(1).to_i * 1024**3
  when /(\d+)m$/i
    Regexp.last_match(1).to_i * 1024**2
  when /(\d+)k$/i
    Regexp.last_match(1).to_i * 1024
  else
    Regexp.last_match(1).to_i
  end
end

#calculate_time(time_str) ⇒ Object



366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# File 'lib/mfd/cli.rb', line 366

def calculate_time(time_str)
  datum = Time.gm 2001

  case time_str
  when /^(\d+)S$/
    NOW - datum - Regexp.last_match(1).to_i
  when /^(\d+)M$/
    NOW - datum - Regexp.last_match(1).to_i * 60
  when /^(\d+)H$/
    NOW - datum - Regexp.last_match(1).to_i * 3600
  when /^(\d+)d$/
    NOW - datum - Regexp.last_match(1).to_i * 86_400
  when /^(\d+)m$/
    NOW - datum - Regexp.last_match(1).to_i * 2_592_000
  when /^(\d+)Y$/
    NOW - datum - Regexp.last_match(1).to_i * 946_080_000
  else
    ymd = time_str.split(/\D+/)
    Time.local(*ymd) - datum
  end
end

#declare_options!Object



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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
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
# File 'lib/mfd/cli.rb', line 61

def declare_options!
  @opt.banner = <<-BANNER
  mdfind4 - a better mdfind built upon mdfind3

  Spotlight 是 OS X 上非常好用的一个桌面搜索工具,mdfind 是Spotlight 的 CLI frontend,
  虽然 mdfind 的功能足够强大,但是界面非常不友好,例如,要搜索电脑中2013年的文件大小大于 1MB
  的jpg图像文件,需要一个非常复杂的命令。mdfind4 对mdfind进行封装,提供比较易用的界面

  mdfind3: https://gist.github.com/4086771

  usage: mdfind4 [options] [search dir]

    通过指定若干选项来搜索文件系统中被 Spotlight 索引的文件,每个选项之间是逻辑与的关系. 默认将
    搜索文件系统中所有的被索引文件,可以通过最后一个参数来约束其只在某个目录中进行搜索.

    % mdfind4 --content-type com.omnigroup.omnigraffle.graffle --from 2011/11/1 -t '2013-01-01 14:30:24'
    % mdfind4 --query '关键字' --content-type 'com.adobe.pdf'
    % mdfind4 -e mp3 -b10M

  options:

    以下选项均支持以一个 "@" 符号开头, 后跟一个文件名,表示此选项的值将从给定的文件中提取:

      • -f, --from
      • -t, --to
      • -F, --from-create
      • -T, --to-create
      • -c, --content-type
      • -k, --kind
      • -b, --biggerthan
      • -s, --smallerthan

  BANNER

  @opt.on('-f from', '--from from', "e.g. --from 2010/1/1
    #{' ' * 35}搜索\"文件最后修改时间\"等于或晚于指定时间的文件,时间格式为\"YYYY-mm-dd HH:MM:SS\"
    #{' ' * 35}其中可以使用任意非数字字符作为分隔符,也可以只指定日期部分。
    #{' ' * 35}另外, -f 选项还支持指定一个数字后跟一个字母的形式来指定时间,
    #{' ' * 35}支持的字符包括: S, M, H, d, m, Y,分别表示: 秒, 分, 时,
    #{' ' * 35}天, 月, 年, 其中一个月等于 30 天, 一年等于 365 天.
    #{' ' * 35}例如, 搜索最近 10 天的文件: -f 10d
    ") do |from|
    @predicates << 'kMDItemFSContentChangeDate >= %i' % (from.start_with?('@') ?
      prop_value_from_file(from, 'kMDItemFSContentChangeDate') : calculate_time(from))
  end

  @opt.on('-t to', '--to to', "搜索\"文件最后修改时间\"等于或早于指定时间的文件, 格式同\"-f\"选项
    ") do |to|
    @predicates << 'kMDItemFSContentChangeDate <= %i' % (to.start_with?('@') ?
      prop_value_from_file(to, 'kMDItemFSContentChangeDate') : calculate_time(to))
  end

  @opt.on('-F from', '--from-create from', "搜索\"文件创建时间\"等于或晚于指定时间的文件, 格式同\"-f\"选项
    ") do |from|
    @predicates << 'kMDItemFSCreationDate >= %i' % (from.start_with?('@') ?
      prop_value_from_file(from, 'kMDItemFSCreationDate') : calculate_time(from))
  end

  @opt.on('-T to', '--to-create to', "搜索\"文件创建时间\"等于或早于指定时间的文件, 格式同\"-f\"选项
    ") do |to|
    @predicates << 'kMDItemFSCreationDate <= %i' % (to.start_with?('@') ?
      prop_value_from_file(to, 'kMDItemFSCreationDate') : calculate_time(to))
  end

  @opt.on('-q query', '--query query', 'e.g. --query "关键字"
    ') do |query|
    @predicates << 'kMDItemTextContent == "%s"cdw' % escape(query)
  end

  @opt.on('-c [contenttype]', '--content-type [contenttype]', "e.g. --contenttype com.omnigroup.omnigraffle.graffle
    #{' ' * 35}搜索 \"kMDItemContentType\" 属性等于指定值的文件,可以不
    #{' ' * 35}指定完整的 Content Type,例如 Ruby 脚本的 Content Type
    #{' ' * 35}为 \"public.ruby-script\",但是可以使用下面的命令所有所有
    #{' ' * 35}Ruby 脚本文件:mdfind4 -c ruby
    #{' ' * 35}搜索文件夹(目录)而非普通文件: -c public.folder  或  -c folder
    #{' ' * 35}也可从样例目录提取: -c @~/Documents
    #{' ' * 35}若不指定选项值(mfd -c),则列出搜索范围内所有
    #{' ' * 35}kMDItemContentType 取值,便于确认可用的 Content Type。
    #{' ' * 35}限定目录时请写成: mfd -c -- ~/Documents
    ") do |contenttype|
    if contenttype.nil?
      @list_content_types = true
    else
      @predicates << 'kMDItemContentType == "%s"cdw' % (contenttype.start_with?('@') ?
        prop_value_from_file(contenttype, 'kMDItemContentType') : escape(contenttype))
    end
  end

  @opt.on('-e file-ext-name', '--type file-ext-name', ".e.g  -e 'mp3'
    #{' ' * 35}搜索文件扩展名等于指定值的文件
    ") do |type|
    if Mfd::Asset::KIND_MAP[type]
      @predicates << '(kMDItemFSName == "*.%s" || kMDItemKind == "%s"cdw)' % [type, escape(Mfd::Asset::KIND_MAP[type])]
    else
      @predicates << 'kMDItemFSName == "*.%s"' % type
    end
  end

  @opt.on('-k [kind]', '--kind [kind]', "e.g. --kind \"HTML Document\"
    #{' ' * 35}\"-k\"选项是另外一个用来指定文件类型的选项,它使用
    #{' ' * 35}\"kMDItemKind\"属性来搜索文件. 例如, 搜索邮件: \"-k 邮件信息\"
    #{' ' * 35}搜索 Safari 历史记录: \"-k 'Safari 历史记录项目'\"
    #{' ' * 35}搜索文件夹(目录): -k 文件夹  (英文系统下为 -k Folder)
    #{' ' * 35}也可从样例目录提取: -k @~/Documents
    #{' ' * 35}若不指定选项值(mfd -k 或 mfd -l),则列出内置 KIND_MAP
    #{' ' * 35}(扩展名及其对应的 kMDItemKind),不扫描磁盘。
    ") do |kind|
    if kind.nil?
      @list_kinds = true
    else
      @predicates << 'kMDItemKind == "*%s*"cdw' % (kind.start_with?('@') ?
        prop_value_from_file(kind, 'kMDItemKind') : escape(kind))
    end
  end

  @opt.on('-l', '--list-kinds', "列出内置 KIND_MAP(扩展名 → kMDItemKind),等价于不带选项值的 -k
    ") do
    @list_kinds = true
  end

  @opt.on('-b size', '--bigger-than size', "e.g. --bigger-than 100000
    #{' ' * 35}搜索文件大小大于或等于给定值的文件,可以使用 t, g, m, k 等单位,
    #{' ' * 35}例如, 搜索大于或等于 1MB 字节的文件:\"-b 1m\"
    ") do |size|
    @predicates << 'kMDItemFSSize >= %s' % (size.start_with?('@') ?
      prop_value_from_file(size, 'kMDItemFSSize') : calculate_size(size).to_s)
  end

  @opt.on('-s sizes', '--smaller-than size', "e.g. --smaller-than 100000
    #{' ' * 35}搜索文件大小小于或等于给定值的文件,可以使用 t, g, m, k 等单位,
    #{' ' * 35}例如, 搜索小于或等于 1GB 字节的文件:\"-b 1G\"
    ") do |size|
    @predicates << 'kMDItemFSSize <= %s' % (size.start_with?('@') ?
      prop_value_from_file(size, 'kMDItemFSSize') : calculate_size(size).to_s)
  end

  @opt.on('', '--prop-eq arg_value', "e.g. --prop-eq FSSize@diary.txt
    #{' ' * 35}不同类型的文件各自都有多种多样的属性,本程序支持的属性比较有限, 若需要
    #{' ' * 35}按照其他属性比较,则使用本选项以及下面三个以 \"--prop\"
    #{' ' * 35}打头的选项。可以通过 OS X 自带的 \"mdls\" 命令来查看文件的各种属性,
    #{' ' * 35}属性名称一般以 \"kMDItem\" 打头,使用这四个选项时可以只指定 \"kMDItem\"
    #{' ' * 35}后面的部分, 本选项的值的格式为 \"property@filename\", 例如,
    #{' ' * 35}搜索文件大小等于 a.txt 的所有文件:--prop-eq FSSize@./a.txt
    ") do |arg_value|
    prop_key, filename = arg_value.split('@')
    prop_key = 'kMDItem' + prop_key unless prop_key.start_with?('kMDItem')
    filename = File.expand_path filename
    @predicates << "#{prop_key} == %s" % prop_value_from_file(filename, prop_key)
  end

  @opt.on('', '--prop-ne arg_value', 'e.g. --prop-ne FSSize@diary.txt
    ') do |arg_value|
    prop_key, filename = arg_value.split('@')
    prop_key = 'kMDItem' + prop_key unless prop_key.start_with?('kMDItem')
    filename = File.expand_path filename
    @predicates << "#{prop_key} != %s" % prop_value_from_file(filename, prop_key)
  end

  @opt.on('', '--prop-le arg_value', 'e.g. --prop-le FSSize@diary.txt
    ') do |arg_value|
    prop_key, filename = arg_value.split('@')
    prop_key = 'kMDItem' + prop_key unless prop_key.start_with?('kMDItem')
    filename = File.expand_path filename
    @predicates << "#{prop_key} <= %s" % prop_value_from_file(filename, prop_key)
  end

  @opt.on('', '--prop-ge arg_value', 'e.g. --prop-ge FSSize@diary.txt
    ') do |arg_value|
    prop_key, filename = arg_value.split('@')
    prop_key = 'kMDItem' + prop_key unless prop_key.start_with?('kMDItem')
    filename = File.expand_path filename
    @predicates << "#{prop_key} >= %s" % prop_value_from_file(filename, prop_key)
  end

  @opt.on('-d url', '--downloadfrom url', '搜索从URL下载的文件') do |url|
    @predicates << 'kMDItemWhereFroms == "%s"' % "*#{escape(url)}*" # 曖昧指定
  end

  @opt.on('-n name', '--name name', '按文件名称搜索, 自动支持模糊匹配, 无需指定通配符') do |name|
    @predicates << 'kMDItemFSName == "%s"cdw' % escape(name)
  end

  @opt.on('-N name', '--name-exact name', '按文件名称精确匹配(区分大小写,需包含扩展名)') do |name|
    @predicates << 'kMDItemFSName == "%s"' % escape_literal(name)
  end

  @opt.on('-0', '--null', "Prints an ASCII NUL character after each result path.
    #{' ' * 35}This is useful when used in conjunction with
    #{' ' * 35}xargs -0.") do
    @ascii_null = true
  end

  @opt.on('', '--live', "Causes the mdfind command to provide live-updates to the
    #{' ' * 35}number of files matching the query. When an
    #{' ' * 35}update causes the query results to change the
    #{' ' * 35} number of matches is updated.  The find can
    #{' ' * 35}be cancelled by typing ctrl-C.
    ") do
    @live = true
  end

  @opt.on('', '--count', "Causes the mdfind command to output the total number of
    #{' ' * 35}matches, instead of the path to the matching
    #{' ' * 35}items.
    ") do
    @count = true
  end

  @opt.on('', '--debug', "mdfind4 通过调用 OS X 系统自带的 mdfind 命令来完成文件搜索,指定
    #{' ' * 35}本选项之后, 可以看到 mdfind4 实际调用的命令的参数
    ") do
    @print_command = true
  end
end

#each_mdfind_path(scope, query_string) ⇒ Object



333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/mfd/cli.rb', line 333

def each_mdfind_path(scope, query_string)
  cmd = "mdfind #{scope} -literal -0 '#{query_string}'"
  puts cmd if @print_command

  IO.popen(cmd, 'r') do |io|
    buf = ''
    while (chunk = io.read(65_536))
      buf << chunk
      while (idx = buf.index("\0"))
        path = buf.slice!(0, idx)
        buf.slice!(0)
        yield path unless path.empty?
      end
    end
    yield buf unless buf.empty?
  end
end

#emit_unique_md_values(attr, scope, query_string) ⇒ Object



299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/mfd/cli.rb', line 299

def emit_unique_md_values(attr, scope, query_string)
  unique = {}
  batch = []

  flush = lambda do
    unless batch.empty?
      md_values_for_paths(attr, batch).each do |value|
        next if value.empty? || unique[value]
        unique[value] = true
        puts value
        $stdout.flush
      end
      batch.clear
    end
  end

  each_mdfind_path(scope, query_string) do |path|
    next unless usable_fs_path?(path)
    batch << path
    flush.call if batch.size >= 100
  end
  flush.call
end

#escape(str) ⇒ Object



276
277
278
# File 'lib/mfd/cli.rb', line 276

def escape(str)
  str.gsub(/"/, '\\"')
end

#escape_literal(str) ⇒ Object



280
281
282
# File 'lib/mfd/cli.rb', line 280

def escape_literal(str)
  str.gsub(/[\\*?"]/) { |char| '\\' + char }
end

#list_content_types(scope, query_string) ⇒ Object



291
292
293
294
295
296
297
# File 'lib/mfd/cli.rb', line 291

def list_content_types(scope, query_string)
  if scope.empty?
    $stderr.puts '未指定搜索目录,将遍历整个 Spotlight 索引(可能非常慢)。建议加上目录,例如: mfd -c -- ~/Documents'
  end

  emit_unique_md_values('kMDItemContentType', scope, query_string)
end

#md_values_for_paths(attr, paths) ⇒ Object



323
324
325
326
327
# File 'lib/mfd/cli.rb', line 323

def md_values_for_paths(attr, paths)
  IO.popen(['mdls', '-name', attr, '-raw', '-nullMarker', '', *paths], 'r', err: File::NULL) do |io|
    io.read.split("\0")
  end
end

#parse_options!(args) ⇒ Object



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
# File 'lib/mfd/cli.rb', line 22

def parse_options!(args)
  if args.empty?
    puts @opt
    exit
  end

  @opt.parse!(args)

  if @list_kinds
    print_kind_map
    return unless @list_content_types
  end

  if args.size == 1
    dir = args.first
    dir = File.expand_path dir unless dir =~ /^\//
    scope = "-onlyin '#{escape dir}'"
  else
    scope = ''
  end

  query_string = @predicates.join(' && ')

  if @list_content_types
    list_content_types(scope, query_string)
    return
  end

  cmd = "mdfind #{scope} \
  #{@ascii_null ? '-0' : ''} \
  #{@live ? '-live' : ''} \
  #{@count ? '-count' : ''} \
'#{query_string}'"

  puts cmd if @print_command

  system cmd
end


284
285
286
287
288
289
# File 'lib/mfd/cli.rb', line 284

def print_kind_map
  width = Mfd::Asset::KIND_MAP.keys.map(&:size).max
  Mfd::Asset::KIND_MAP.sort.each do |ext, kind|
    printf "%-*s  %s\n", width, ext, kind
  end
end

#prop_value_from_file(filename, key) ⇒ Object



388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# File 'lib/mfd/cli.rb', line 388

def prop_value_from_file(filename, key)
  filename = File.expand_path filename.sub(/^@/) { '' }
  IO.popen("mdls '#{filename}'", 'r') do |io|
    while line = io.gets
      next unless line =~ /#{key}\s*=\s*(.+)/
      value_str = Regexp.last_match(1)
      case value_str
      when /^"([^"]*)"$/
        return Regexp.last_match(1)
      when /^(\d+)$/
        return Regexp.last_match(1)
      when /^(.*) \+0000$/
        ymd = Regexp.last_match(1).split(/\D+/)
        return Time.gm(*ymd) - Time.gm(2001)
      else
        next
      end
    end
    return nil
  end
end

#usable_fs_path?(path) ⇒ Boolean

Returns:

  • (Boolean)


329
330
331
# File 'lib/mfd/cli.rb', line 329

def usable_fs_path?(path)
  path.start_with?('/') && File.exist?(path)
end