Class: Dirfy::Parser
- Inherits:
-
Object
- Object
- Dirfy::Parser
- Defined in:
- lib/dirfy/parser.rb
Overview
Parses ASCII/Unicode tree diagrams into flat path lists.
Instance Method Summary collapse
-
#initialize(indent: 4) ⇒ Parser
constructor
A new instance of Parser.
-
#parse(lines) ⇒ Object
lines - Array<String> returns Array<String> of relative paths, dirs ending with ‘/’.
Constructor Details
#initialize(indent: 4) ⇒ Parser
Returns a new instance of Parser.
7 8 9 |
# File 'lib/dirfy/parser.rb', line 7 def initialize(indent: 4) @indent = indent end |
Instance Method Details
#parse(lines) ⇒ Object
lines - Array<String> returns Array<String> of relative paths, dirs ending with ‘/’
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 |
# File 'lib/dirfy/parser.rb', line 13 def parse(lines) stack = [] items = [] depths = [] names = [] lines.each do |raw| line = raw.rstrip next if line.strip.empty? || line.strip.start_with?("#") if line.match?(/[└├]/) # replace tree chars with spaces to count indent indent_str = line.gsub(/[│├└─]/, " ") lead_spaces = indent_str[/\A */].size depth = lead_spaces / @indent name = line.split("── ", 2).last else depth = 0 name = line.strip end stack[depth] = name stack = stack[0..depth] # build full path (no trailing slash yet) path = stack.map { |c| c.chomp("/") }.join("/") depths << depth names << name items << path end # Second pass: infer directories by depth items.each_with_index.map do |path, i| is_dir = directory?(names[i], i, depths) is_dir ? (path.end_with?("/") ? path : "#{path}/") : path end end |