Class: Spoom::FileTree

Inherits:
Object
  • Object
show all
Defined in:
lib/spoom/file_tree.rb

Overview

Build a file hierarchy from a set of file paths.

Defined Under Namespace

Classes: CollectNodes, CollectScores, CollectStrictnesses, Node, Printer, Visitor

Instance Method Summary collapse

Constructor Details

#initialize(paths = []) ⇒ FileTree

: (?T::Enumerable paths) -> void



8
9
10
11
# File 'lib/spoom/file_tree.rb', line 8

def initialize(paths = [])
  @roots = T.let({}, T::Hash[String, Node])
  add_paths(paths)
end

Instance Method Details

#add_path(path) ⇒ Object

Add a ‘path` to the tree

This will create all nodes until the root of ‘path`. : (String path) -> Node



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/spoom/file_tree.rb', line 23

def add_path(path)
  parts = path.split("/")
  if path.empty? || parts.size == 1
    return @roots[path] ||= Node.new(parent: nil, name: path)
  end

  parent_path = T.must(parts[0...-1]).join("/")
  parent = add_path(parent_path)
  name = T.must(parts.last)
  parent.children[name] ||= Node.new(parent: parent, name: name)
end

#add_paths(paths) ⇒ Object

Add all ‘paths` to the tree : (T::Enumerable paths) -> void



15
16
17
# File 'lib/spoom/file_tree.rb', line 15

def add_paths(paths)
  paths.each { |path| add_path(path) }
end

#nodesObject

All the nodes in this tree : -> Array



43
44
45
46
47
# File 'lib/spoom/file_tree.rb', line 43

def nodes
  v = CollectNodes.new
  v.visit_tree(self)
  v.nodes
end

#nodes_strictness_scores(context) ⇒ Object

Return a map of typing scores for each node in the tree : (Context context) -> Hash[Node, Float]



57
58
59
60
61
# File 'lib/spoom/file_tree.rb', line 57

def nodes_strictness_scores(context)
  v = CollectScores.new(context)
  v.visit_tree(self)
  v.scores
end

#pathsObject

All the paths in this tree : -> Array



51
52
53
# File 'lib/spoom/file_tree.rb', line 51

def paths
  nodes.map(&:path)
end

#paths_strictness_scores(context) ⇒ Object

Return a map of typing scores for each path in the tree : (Context context) -> Hash[String, Float]



65
66
67
# File 'lib/spoom/file_tree.rb', line 65

def paths_strictness_scores(context)
  nodes_strictness_scores(context).map { |node, score| [node.path, score] }.to_h
end

: (?out: (IO | StringIO), ?colors: bool) -> void



70
71
72
73
# File 'lib/spoom/file_tree.rb', line 70

def print(out: $stdout, colors: true)
  printer = Printer.new({}, out: out, colors: colors)
  printer.visit_tree(self)
end

#rootsObject

All root nodes : -> Array



37
38
39
# File 'lib/spoom/file_tree.rb', line 37

def roots
  @roots.values
end