Debian Codegraph @

core/utils.rb

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 =begin rdoc
3 CHI内部で共通で使われるユーティリティ。
4 =end
5
6 require 'thread'
7 require 'monitor'
8 require "open-uri"
9 require 'logger'
10 require_relative 'lib/log_formatter'
11
12 $atomic = Monitor.new
13
14 # 基本的な単位であり、数学的にも重要なマジックナンバーで、至るところで使われる。
15 # これが言語仕様に含まれていないRubyは正直気が狂っていると思う。
16 # http://ja.uncyclopedia.info/wiki/Hyde
17 HYDE = 156
18
19 # Rubyのバージョンを配列で。あると便利。
20 RUBY_VERSION_ARRAY = RUBY_VERSION.split('.').map{ |i| i.to_i }.freeze
21
22 require File.join(__dir__, 'miquire')
23
24 [__dir__,
25 File.join(__dir__, 'lib'),
26 File.join(__dir__, 'miku')].each{|path|
27 $LOAD_PATH.push(File.expand_path(File.join(Dir.pwd, path)))
28 }
29
30 require_relative 'miquire'
31
32 # すべてのクラスにメモ化機能を
33 require 'memoist'
34
35 # Environment::CONFROOT内のファイル名を得る。
36 # confroot(*path)
37 # は
38 # File::expand_path(File.join(Environment::CONFROOT, *path))
39 # と等価。
40 def confroot(*path)
41 File::expand_path(File.join(Environment::CONFROOT, *path))
42 end
43 require 'environment'
44
45 # _num_ 番目の引数をそのまま返す関数を返す
46 def ret_nth(num=0)
47 lambda { |*arg| arg[num] } end
48
49 # スレッドセーフなカウンタを返す。
50 # カウンタの初期値は _count_ で、呼び出すたびに値が _increment_ づつ増える。
51 # なお、カウンタが返す値はインクリメント前の値。
52 def gen_counter(count=0, increment=1)
53 mutex = Mutex.new
54 lambda{
55 mutex.synchronize{
56 result = count
57 count += increment
58 result } } end
59
60 # ファイルの内容を文字列に読み込む
61 def file_get_contents(fn)
62 open(fn, 'rb:utf-8'.freeze){ |input|
63 input.read
64 }
65 end
66
67 # 文字列をファイルに書き込む
68 def file_put_contents(fn, body)
69 File.open(fn, 'wb'.freeze){ |put|
70 put.write body
71 body
72 }
73 end
74
75 # ファイル _fn_ の内容からオブジェクトを読み込む。
76 # _fn_ は、object_put_contents() で保存されたファイルでなければならない。
77 def object_get_contents(fn)
78 File.open(fn, 'rb'.freeze){ |input|
79 Marshal.load input
80 }
81 end
82
83 # UNIXコマンド _cmd_ が存在するか否かを返す。
84 def command_exist?(cmd)
85 system("which #{cmd} > /dev/null")
86 end
87
88 # 存在するかわからないrubyファイル _file_ を読み込む。
89 # ただし、_file_ が存在しない場合は例外を投げずにfalseを返す。
90 def require_if_exist(file)
91 require file
92 true
93 rescue LoadError
94 warn "require-if-exist: file not found: #{file}"
95 false
96 end
97
98 # _insertion_ を、 _src_ の挿入するべき場所のインデックスを返す。
99 # _order_ は順番を表す配列で、 _src_ 内のオブジェクトの前後関係を表す。
100 # _order_ 内に _insertion_ が存在しない場合は一番最後のインデックスを返す
101 def where_should_insert_it(insertion, src, order)
102 if(order.include?(insertion)) then
103 src.dup.push(insertion).sort_by{|a|
104 order.index(a) or 65536
105 }.index(insertion)
106 else
107 src.size end end
108
109 # 一般メッセージを表示する。
110 def notice(msg)
111 log Logger::INFO, msg if Mopt.error_level >= 3
112 end
113
114 alias __mikutter_original_warn warn
115 # 警告メッセージを表示する。
116 def warn(*msg, uplevel: nil)
117 case
118 when uplevel
119 __mikutter_original_warn(*msg, uplevel: uplevel)
120 when Mopt.error_level >= 2
121 msg.each do |m|
122 log Logger::WARN, m
123 end
124 end
125 end
126
127 # エラーメッセージを表示する。
128 def error(msg)
129 log Logger::ERROR, msg if Mopt.error_level >= 1
130 abort if Mopt.error_level >= 4
131 end
132
133 # --debug オプション付きで起動されている場合、インタプリタに入る。
134 # ==== Args
135 # [exception] 原因となった例外
136 # [binding] インタプリタを実行するスコープ
137 # ==== Return
138 # インタプリタから復帰したら(インタプリタが起動されたら)true、
139 # デバッグモードではない、pryがインストールされていない等、起動に失敗したらfalse
140 def into_debug_mode(exception = nil, bind = binding)
141 if Mopt.debug and not Mopt.testing
142 require_if_exist 'pry'
143 if binding.respond_to?(:pry)
144 log "error", exception if exception
145 $into_debug_mode_lock.synchronize {
146 begin
147 $into_debug_mode = Set.new
148 bind.pry
149 ensure
150 threads = $into_debug_mode
151 $into_debug_mode = false
152 threads.each &:wakeup end }
153 return true end end end
154 $into_debug_mode = false
155 $into_debug_mode_lock = Monitor.new
156
157 # 他のスレッドでinto_debug_modeが呼ばれているなら、それが終わるまでカレントスレッドをスリープさせる
158 def debugging_wait
159 if $into_debug_mode
160 $into_debug_mode << Thread.current
161 Thread.stop end end
162
163 # 引数のチェックをすべてパスした場合のみブロックを実行する
164 # チェックに引っかかった項目があればwarnを出力してブロックは実行せずにnilを返す。
165 # チェックはassocできる配列か、Hashで定義する。
166 # type_check(value => nil, # チェックしない(常にパス)
167 # value => Module, # その型とis_a?関係ならパス
168 # value => [:method, *args], # value.method(*args)が真を返せばパス
169 # value => lambda{ |x| ...}) # xにvalueを渡して実行し、真を返せばパス
170 # チェックをすべてパスしたかどうかを真偽値で返す。
171 # ブロックが指定されていれば、それを実行してブロックの実行結果を返す
172 # メモ: いずれかのタイプに一致するチェックを定義するにはtcorを使う
173 # type_check object => tcor(Array, Hash)
174 def type_check(args, &proc)
175 check_function = lambda{ |val, check|
176 if not check
177 true
178 elsif check.is_a? Array
179 val.__send__(*check)
180 elsif check.is_a? Symbol
181 val.respond_to?(check)
182 elsif check.is_a?(Class) or check.is_a?(Module)
183 val.is_a?(check)
184 elsif check.respond_to?(:call)
185 check.call(val) end }
186 error = args.find{ |a| not(check_function.call(*a)) }
187 if(error)
188 warn "argument error: #{error[0].inspect} is not passed #{error[1].inspect}"
189 warn "in #{caller_util}"
190 false
191 else
192 if proc
193 proc.call
194 else
195 true end end end
196
197 # _types_ のうちいずれかとis_a?関係ならtrueを返すProcオブジェクトを返す
198 def tcor(*types)
199 lambda{ |v| types.any?{ |c| v.is_a?(c) } } end
200
201 # type_checkと同じだが、チェックをパスしなかった場合にabortする
202 # type_checkの戻り値を返す
203 def type_strict(args, &proc)
204 args.each.with_index do |(value, constraint), index|
205 unless type_check(value => constraint, &proc)
206 raise TypeStrictError.new("The ##{index} value does not matched constraint `#{constraint}'", value: value)
207 end
208 end
209 true
210 end
211
212 # blockの評価結果がチェックをパスしなかった場合にabortする
213 def result_strict(must, &block)
214 result = block.call
215 type_strict(result => must)
216 result
217 end
218
219 # メインスレッド以外で呼び出されたらThreadErrorを投げる
220 def mainthread_only
221 unless Thread.main == Thread.current
222 raise ThreadError.new('The method can calls only main thread. but called by another thread.') end end
223
224 # メインスレッドで呼び出されたらThreadErrorを投げる
225 def no_mainthread
226 if Thread.main == Thread.current
227 raise ThreadError.new('The method can not calls main thread. but called by main thread.') end end
228
229 # utils.rbのメソッドを呼び出した最初のバックトレースを返す
230 def caller_util
231 caller.each{ |result|
232 return result unless /utils\.rb/ === result } end
233
234 # エラーログに記録する。
235 # 内部処理用。外部からは呼び出さないこと。
236 def log(prefix, object)
237 debugging_wait
238 return if $daemon # rubocop:disable Style/GlobalVars
239 begin
240 msg = object.to_s
241 msg += "\nfrom #{object.backtrace.join("\nfrom ")}" if object.is_a? Exception
242 logger.log(prefix, msg, caller_util)
243 rescue Exception => exception # rubocop:disable Lint/RescueException
244 __write_stderr("critical!: #{caller(0)}: #{exception}")
245 end
246 end
247
248 def logger
249 formatter = Mopt.color ? LogFormatter::Colorful : LogFormatter::Standard
250 $logger ||= Logger.new($stderr, formatter: formatter.new) # rubocop:disable Style/GlobalVars
251 end
252
253 FOLLOW_DIR = File.expand_path(File.join(__dir__, '..'))
254 def __write_stderr (msg)
255 $stderr.write(msg.gsub(FOLLOW_DIR, '{MIKUTTER_DIR}')+"\n")
256 end
257
258 # 環境や設定の不備で終了する。msgには、何が原因かを文字列で渡す。このメソッドは
259 # 処理を返さずにアボートする。
260 def chi_fatal_alert(msg)
261 require_if_exist 'gtk3'
262 if defined?(Gtk::MessageDialog)
263 dialog = Gtk::MessageDialog.new(nil,
264 Gtk::Dialog::DESTROY_WITH_PARENT,
265 Gtk::MessageDialog::ERROR,
266 Gtk::MessageDialog::BUTTONS_CLOSE,
267 "#{Environment::NAME} エラー")
268 dialog.secondary_text = msg.to_s
269 dialog.run
270 dialog.destroy end
271 puts msg.to_s
272 abort end
273
274 # 共通のMutexで処理を保護して実行する。
275 # atomicブロックで囲まれたコードは、別々のスレッドで同時に実行されない。
276 def atomic
277 $atomic.synchronize{ yield }
278 end
279
280 # コマンドをバックグラウンドで起動することを覗いては system() と同じ
281 def bg_system(*args)
282 Process.detach(spawn(*args))
283 end
284
285 class Module
286 # ハッシュ用のアクセサ。最初から空の連想配列が入っている
287 # 引数なしで呼び出すとハッシュ自身を返し、1つ引数を与えると、引数をキーにハッシュの値を返す
288 def attr_hash_accessor(*names)
289 names.each { |name|
290 hash = {}
291 define_method(name){ |*args|
292 case args.size
293 when 0
294 hash
295 when 1
296 hash[args[0]]
297 when 2
298 hash[args[0]] = args[1]
299 end
300 }
301 }
302 end
303
304 def memoize(*rest)
305 unless is_a?(Memoist)
306 call_place, = caller(1,1)
307 warn "Module#.memoize called in #{call_place}."
308 warn "see https://dev.mikutter.hachune.net/issues/1051"
309 extend Memoist
310 memoize(*rest)
311 end
312 end
313 end
314
315 class Object
316 # freezeできるならtrueを返す
317 def freezable?
318 true
319 end
320
321 # freezeできる場合はfreezeする。selfを返す
322 def freeze_ifn
323 freeze if freezable?
324 self
325 end
326
327 # freezeされていない同じ内容のオブジェクトを作って返す。
328 # メルト 溶けてしまいそう (実装が)dupだなんて 絶対に 言えない
329 def melt
330 if frozen? then dup else self end
331 end
332 end
333
334 #
335 # Numeric
336 #
337
338 class Numeric
339 def freezable?
340 false end end
341
342 #
343 # Array
344 #
345 class Array
346 include Comparable
347
348 def symbolize
349 result = []
350 each { |val|
351 result << if val.respond_to?(:symbolize) then val.symbolize else val end }
352 result
353 end
354
355 end
356
357 class Hash
358 # キーの名前を変換する。
359 def convert_key(rule = nil)
360 result = {}
361 self.each_pair { |key, val|
362 if rule[key]
363 result[rule[key]] = val
364 else
365 result[key.to_sym] = val end }
366 result end
367
368 # キーを全てto_symしたhashを新たにつくる
369 def symbolize
370 result = {}
371 each_pair { |key, val|
372 result[key.to_sym] = if val.respond_to?(:symbolize) then val.symbolize else val end }
373 result
374 end
375 end
376
377 #
378 # String
379 #
380
381 class String
382 def match_regexp(str)
383 if str.is_a?(String)
384 begin
385 match(Regexp.new(str))
386 rescue RegexpError => err
387 error err
388 nil
389 end
390 else
391 match(str)
392 end
393 end
394
395 def matches(regexp)
396 warn "String#matches is obsolete method. use String#scan"
397 result = []
398 each_matches(regexp){ |m, pos|
399 result << m.to_s }
400 result
401 end
402
403 def each_matches(regexp, &proc) # :yield: match, byte_index, char_index
404 warn "String#each_matches is obsolete method. use String#scan"
405 pos = 0
406 str = self
407 while(match = regexp.match(str))
408 if(proc.arity == 1)
409 proc.call(match)
410 elsif(proc.arity == 2)
411 proc.call(match, pos + match.begin(0))
412 else
413 proc.call(match, pos + match.begin(0), pos + match.begin(0)) end
414 str = match.post_match
415 pos += match.end(0) end end
416
417 # _byte_ バイト目が何文字目にあたるかを返す
418 def get_index_from_byte(byte)
419 each_char.with_index do |c, i|
420 byte -= c.to_enum(:each_byte).count
421 return i if byte < 0
422 end
423 size
424 end
425
426 def inspect
427 '"'+to_s+'"'
428 end
429
430 end
431
432 class Symbol
433 def freezable?
434 false end end
435
436 class TrueClass
437 def freezable?
438 false end end
439
440 class FalseClass
441 def freezable?
442 false end end
443
444 class NilClass
445 def freezable?
446 false end end
447
448 class Regexp
449 def to_json(*a)
450 {
451 'json_class' => self.class.name,
452 'data' => to_s
453 }.to_json(*a)
454 end
455
456 def self.json_create(o)
457 new(o['data'])
458 end
459 end
460
461 # type_strictが発生させる例外。
462 # 値が制約に合致しない場合に投げられる。
463 # valueメソッドを呼ぶと、原因となった値を得ることができる。
464 class TypeStrictError < TypeError
465 attr_reader :value
466
467 def initialize(*args, value:)
468 super(*args)
469 @value = value
470 end
471 end