Sha256: 7dcbc89f87f68c71288af99d2fc3c795a2138002fceedc650f3ebb642f300c12

Contents?: true

Size: 1.3 KB

Versions: 3

Compression:

Stored size: 1.3 KB

Contents

# -*- encoding : utf-8 -*-

module Gitdocs
  class Search
    RepoDescriptor = Struct.new(:name, :index)
    SearchResult   = Struct.new(:file, :context)

    # @param [String] term
    # @return (see #search)
    def self.search(term)
      new(Share.all.map { |x| Repository.new(x) }).search(term)
    end

    # @param [Array<Gitdocs::Repository>] repositories
    def initialize(repositories)
      @repositories = repositories
    end

    # @param [String] term
    # @return [Hash<RepoDescriptor, Array<SearchResult>>]
    def search(term)
      results = {}
      @repositories.each_with_index do |repository, index|
        descriptor = RepoDescriptor.new(repository.root, index)
        results[descriptor] = search_repository(repository, term)
      end
      results.delete_if { |_key, value| value.empty? }
    end

    private

    # @param [Repository] repository
    # @param [String] term
    # @return [Array<SearchResult>]
    def search_repository(repository, term)
      return [] if term.nil? || term.empty?

      results = []
      repository.grep(term) do |file, context|
        result = results.find { |s| s.file == file }
        if result
          result.context += ' ... ' + context
        else
          results << SearchResult.new(file, context)
        end
      end
      results
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
gitdocs-0.6.2 lib/gitdocs/search.rb
gitdocs-0.6.1 lib/gitdocs/search.rb
gitdocs-0.6.0 lib/gitdocs/search.rb