Module: Zomgit::Concerns::Findable

Included in:
Zomgit::Commands::FindCommand
Defined in:
lib/zomgit/concerns/findable.rb

Defined Under Namespace

Classes: Finder

Instance Method Summary collapse

Instance Method Details

#search(arguments, options = []) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/zomgit/concerns/findable.rb', line 44

def search(arguments, options = [])
  greedy = !!options[:greedy] && !!!options[:G]
  clean = !!options[:refine]
  files = Array.new

  case options[:filter].to_s.to_sym
  when :all
    cmds = ["ls-files --others --cached --exclude-standard"]
  when :untracked
    cmds = ["ls-files --others --exclude-standard"]
  when :tracked
    cmds = ["ls-files"]
  when :unstaged
    cmds = ["ls-files --others --exclude-standard", "diff --name-only"]
  when :staged
    cmds = ["diff --name-only --cached"]
  when :modified
    cmds = ["diff --name-only"]
  else
    cmds = ["ls-files --others --cached --exclude-standard"]
  end

  cmds.each { |c| files << `command git #{c}`.split("\n") }
  files.flatten!

  if files.count == 0
    raise Zomgit::Exceptions::NoChangesError.new("No changes matching this filter")
  end

  if arguments.count == 1 && arguments.first == "."
    found = files
  else
    indices = arguments.map { |a| a if a =~ /\A[1-9]+(?:\.{2}[0-9]+)?\Z/ }.compact

    unless indices.empty?
      index = Zomgit::Persistor.instance.index

      if index.empty?
        raise Zomgit::Exceptions::NoIndexError.new("No index found")
      end

      arguments -= indices

      indices.map! do |i|
        if i.include?("..")
          head, tail = i.split("..").map(&:to_i)

          if head > tail || head > files.count || tail > index.count
            raise Zomgit::Exceptions::InvalidIndexRangeError.new("Invalid index range: #{[head, tail].join("..")}")
          end

          index[Range.new(head - 1, tail - 1)]
        else
          ii = i.to_i

          unless ii > 0 && ii <= index.count
            raise Zomgit::Exceptions::InvalidIndexError.new("Invalid index: #{i}")
          end

          index[ii - 1]
        end
      end

      indices.flatten!
    end

    if clean
      found = files

      arguments.each do |arg|
        found = Finder.fuzzy_find(found, arg, greedy: greedy)
      end
    else
      found = Array.new

      arguments.each do |arg|
        found << Finder.fuzzy_find(files, arg, greedy: greedy)
      end

      found = found.flatten.uniq
    end

    unless indices.empty?
      found = (found + indices).uniq
    end
  end

  found
end