Module: VER::Syntax::Detector

Defined in:
lib/ver/syntax/detector.rb

Constant Summary collapse

EXTS_LIST =
{}
HEAD_LIST =
{}

Class Method Summary collapse

Class Method Details

.detect(filename, override_name = nil) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/ver/syntax/detector.rb', line 21

def detect(filename, override_name = nil)
  path = Pathname(filename.to_s)
  path = path.readlink if path.symlink?

  VER.load('detect')

  override_name || detect_ext(path) || detect_head(path)
end

.detect_ext(path) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/ver/syntax/detector.rb', line 30

def detect_ext(path)
  basename = path.basename.to_s
  return unless basename =~ /\./

  scores = {}

  EXTS_LIST.each do |name, exts|
    lowest = nil
    exts.find do |ext|
      if basename.end_with?(ext)
        distance = Levenshtein.distance(basename, ext)
        lowest ||= distance
        lowest = distance if lowest > distance
      end
      # return name if basename.end_with?(ext)
    end
    scores[name] = lowest if lowest
  end

  found = scores.sort_by{|k,v| v }.first
  return found.first if found
end

.detect_head(path) ⇒ Object



53
54
55
56
57
58
59
60
61
# File 'lib/ver/syntax/detector.rb', line 53

def detect_head(path)
  line = path.open{|io| io.gets }
  return unless line && line.valid_encoding?

  HEAD_LIST.find do |name, head|
    return name if line =~ head
  end
rescue Errno::ENOENT
end

.exts(name, exts) ⇒ Object



9
10
11
# File 'lib/ver/syntax/detector.rb', line 9

def exts(name, exts)
  EXTS_LIST[name] = exts
end

.head(name, head) ⇒ Object



13
14
15
# File 'lib/ver/syntax/detector.rb', line 13

def head(name, head)
  HEAD_LIST[name] = head
end

.namesObject



17
18
19
# File 'lib/ver/syntax/detector.rb', line 17

def names
  [EXTS_LIST.keys, HEAD_LIST.keys].flatten.compact.sort
end