Sha256: 892a7880b93af965c0a201caecb3ff6beae6b9be37e7c1aa478c0b87485b11ba

Contents?: true

Size: 1.82 KB

Versions: 3

Compression:

Stored size: 1.82 KB

Contents

class Licensee
  class LicenseFile

    FILENAMES = %w[
      LICENSE
      LICENSE.txt
      LICENSE.md
      UNLICENSE
    ]

    attr_reader :path
    attr_accessor :contents

    def initialize(path=nil)
      @path = File.expand_path(path)
    end

    def contents
      @contents ||= File.open(path).read
    end
    alias_method :to_s, :contents
    alias_method :content, :contents

    def self.find(base_path)
      raise "Invalid directory" unless directory_exists? base_path
      file = self::FILENAMES.find { |file| file_exists?(file, base_path) }
      new(File.expand_path(file, base_path)) if file
    end

    def self.directory_exists?(base_path)
      File.directory?(base_path)
    end

    def self.file_exists?(file, base_path)
      File.exists? File.expand_path(file, base_path)
    end

    def length
      @length ||= content.length
    end

    def length_delta(license)
      (length - license.length).abs
    end

    def potential_licenses
      @potential_licenses ||= Licensee::Licenses.list.clone.select { |l| length_delta(l) < length }
    end

    def licenses_sorted
      @licenses_sorted ||= potential_licenses.sort_by { |l| length_delta(l) }
    end

    def matches
      @matches ||= begin
        licenses_sorted.each { |l| l.match = 1 - percent_changed(l) }
        licenses_sorted.sort_by { |l| l.match }.select { |l| l.match > 0}.reverse
      end
    end

    def match
      @match ||= licenses_sorted.find do |license|
        confidence = 1 - percent_changed(license)
        next unless confidence >= Licensee::CONFIDENCE_THRESHOLD
        license.match = confidence
      end
    end

    def percent_changed(license)
      (Levenshtein.distance(content, license.body).to_f / content.length.to_f).abs
    end

    def diff(options=nil)
      Diffy::Diff.new(match.body, content).to_s(options)
    end

  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
licensee-0.1.0 lib/licensee/license_file.rb
licensee-0.0.3 lib/licensee/license_file.rb
licensee-0.0.2 lib/licensee/license_file.rb