Class: Schmersion::Linter

Inherits:
Object
  • Object
show all
Defined in:
lib/schmersion/linter.rb

Instance Method Summary collapse

Constructor Details

#initialize(repo) ⇒ Linter

Returns a new instance of Linter.



9
10
11
# File 'lib/schmersion/linter.rb', line 9

def initialize(repo)
  @repo = repo
end

Instance Method Details

#prepare(path, source = nil) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/schmersion/linter.rb', line 13

def prepare(path, source = nil)
  previous_commit_message = read_previous_commit_message

  return unless source.nil?

  unless File.file?(path)
    raise Error, "No commit message file at the given path (#{path})"
  end

  lines = []

  if previous_commit_message
    lines << previous_commit_message
    lines << ''
  else
    lines << "\n"
  end

  lines << '# ====================================================================='
  lines << '# Commit messages must conform to conventional commit formatting.'
  lines << '# This means each commit message must be prefixed with an appropriate'
  lines << '# type and, optionally, a scope. Your message will be validated before'
  lines << '# the commit will be created. '
  lines << '#'

  add_list_for(lines, :types)

  unless @repo.config.scopes.empty?
    lines << '#'
    add_list_for(lines, :scopes)
  end

  lines << '# ====================================================================='

  lines = lines.join("\n")

  contents = File.read(path)
  File.write(path, "#{lines}\n#\n#{contents.strip}")
end

#setup(force: false) ⇒ Object



73
74
75
76
# File 'lib/schmersion/linter.rb', line 73

def setup(force: false)
  create_hook('lint-prepare', 'prepare-commit-msg', force: force)
  create_hook('lint-validate', 'commit-msg', force: force)
end

#validate_file(path) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/schmersion/linter.rb', line 53

def validate_file(path)
  unless File.file?(path)
    raise Error, "No commit message file at the given path (#{path})"
  end

  contents = get_commit_message_from_file(File.read(path))
  return [] if contents.length.zero?

  message = Message.new(contents)

  validator = MessageValidator.new(@repo.config, message)

  unless validator.valid?
    # Save the commit message to a file if its invalid.
    save_commit_message(contents)
  end

  validator.errors
end