Debian Codegraph @

vendor/mruby-source/lib/mruby/core_ext.rb

raw
1 autoload :Pathname, 'pathname'
2
3 class Object
4 class << self
5 def attr_block(*syms)
6 syms.flatten.each do |sym|
7 class_eval "def #{sym}(&block);block.call(@#{sym}) if block_given?;@#{sym};end"
8 end
9 end
10 end
11 end
12
13 class String
14 def relative_path_from(dir)
15 Pathname.new(File.expand_path(self)).relative_path_from(Pathname.new(File.expand_path(dir))).to_s
16 end
17
18 def relative_path
19 relative_path_from(Dir.pwd)
20 end
21
22 def remove_leading_parents
23 Pathname.new(".#{Pathname.new("/#{self}").cleanpath}").cleanpath.to_s
24 end
25
26 def replace_prefix_by(dirmap)
27 [self].replace_prefix_by(dirmap)[0]
28 end
29 end
30
31 class Array
32 # Replace the prefix of each string that is a file path that contains in its own array.
33 #
34 # dirmap is a hash whose elements are `{ "path/to/old-prefix" => "path/to/new-prefix", ... }`.
35 # If it does not match any element of dirmap, the file path is not replaced.
36 def replace_prefix_by(dirmap)
37 dirmap = dirmap.map { |older, newer| [File.join(older, "/"), File.join(newer, "/")] }
38 dirmap.sort!
39 dirmap.reverse!
40 self.flatten.map do |e|
41 map = dirmap.find { |older, newer| e.start_with?(older) }
42 e = e.sub(map[0], map[1]) if map
43 e
44 end
45 end
46 end
47
48 def install_D(src, dst)
49 _pp "INSTALL", src.relative_path, dst.relative_path
50 rm_f dst
51 mkdir_p File.dirname(dst)
52 cp src, dst
53 end
54
55 def _pp(cmd, src, tgt=nil, indent: nil)
56 return if Rake.application.options.silent
57
58 width = 5
59 template = indent ? "%#{width * indent}s %s %s" : "%-#{width}s %s %s"
60 puts template % [cmd, src, tgt ? "-> #{tgt}" : nil]
61 end