Module: MslinnUtil
- Defined in:
- lib/util.rb
Class Method Summary collapse
-
.common_prefix(paths, allow_root_match: false) ⇒ String
The longest path prefix that is a prefix of all paths in array.
-
.deref_symlink(symlink) ⇒ Object
Path to symlink.
- .ensure_ends_with(string, suffix) ⇒ Object
- .expand_env(str) ⇒ Object
- .roots(paths, level, allow_root_match: false) ⇒ Object
- .trim_to_level(paths, level) ⇒ Object
Class Method Details
.common_prefix(paths, allow_root_match: false) ⇒ String
Returns the longest path prefix that is a prefix of all paths in array. If array is empty, return ”. If only the leading slash matches, and allow_root_match is true, return ‘/’, else return ”.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/util.rb', line 6 def self.common_prefix(paths, allow_root_match: false) return '' if paths.empty? relative_paths = paths.reject { |x| x.start_with? '/' } abort "Error: common_prefix received relative paths:" + relative_paths.map { |x| " #{x}\n" } \ unless relative_paths.empty? if paths.length == 1 result = paths.first.split('/').slice(0...-1).join('/') return result.empty? && allow_root_match ? '/' : result end arr = paths.sort first = arr.first.split('/') last = arr.last.split('/') i = 0 i += 1 while first[i] == last[i] && i <= first.length result = first.slice(0, i).join('/') result.empty? && allow_root_match ? '/' : result end |
.deref_symlink(symlink) ⇒ Object
Returns Path to symlink.
65 66 67 68 |
# File 'lib/util.rb', line 65 def self.deref_symlink(symlink) require 'pathname' Pathname.new(symlink).realpath end |
.ensure_ends_with(string, suffix) ⇒ Object
70 71 72 73 |
# File 'lib/util.rb', line 70 def self.ensure_ends_with(string, suffix) string = string.delete_suffix suffix "#{string}#{suffix}" end |
.expand_env(str) ⇒ Object
75 76 77 78 79 |
# File 'lib/util.rb', line 75 def self.(str) str.gsub(/\$([a-zA-Z_][a-zA-Z0-9_]*)|\${\g<1>}|%\g<1>%/) do ENV.fetch(Regexp.last_match(1), nil) end end |
.roots(paths, level, allow_root_match: false) ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/util.rb', line 30 def self.roots(paths, level, allow_root_match: false) abort "Error: level must be positive, but it is #{level}." unless level.positive? return allow_root_match ? '/' : '' if paths.empty? abort("Error: level parameter must be positive, #{level} was supplied instead.") if level <= 0 if paths.length == 1 root = File.dirname(paths.first) return allow_root_match ? '/' : '' if root == '/' return root end loop do paths = trim_to_level(paths, level) # does this change paths in the caller? return paths.first if paths.length == 1 level -= 1 break if level.zero? end allow_root_match ? '/' : '' end |
.trim_to_level(paths, level) ⇒ Object
56 57 58 59 60 61 62 |
# File 'lib/util.rb', line 56 def self.trim_to_level(paths, level) result = paths.map do |x| elements = x.split('/').reject(&:empty?) '/' + elements[0..level - 1].join('/') end result.sort.uniq end |