Module: VagrantGitHooks::HookBuilder

Defined in:
lib/vagrant-git-hooks/hook_builder.rb

Constant Summary collapse

SHEBANG =
"#!/usr/bin/env sh"
BLOCK_START =
"# >>> vagrant-git-hooks (managed) >>>"
BLOCK_STOP =
"# <<< vagrant-git-hooks (managed) <<<"

Class Method Summary collapse

Class Method Details

.adopt_script(name:, content:, newline: "\n") ⇒ String

Wraps an existing hook body in plugin markers.

Preserves user-provided hook bodies when adopting from hooks_source, but wraps them in markers so uninstall and status can manage them later.

Parameters:

  • name (String)

    Git hook name.

  • content (String)

    Existing hook script content.

  • newline (String) (defaults to: "\n")

    Line separator used in the generated script.

Returns:

  • (String)

    Managed hook script.



37
38
39
40
41
42
43
44
45
# File 'lib/vagrant-git-hooks/hook_builder.rb', line 37

def adopt_script(name:, content:, newline: "\n")
  lines = content.to_s.split(/\r?\n/, -1)
  lines.pop if lines.last == ""

  shebang = lines.first&.start_with?("#!") ? lines.shift : SHEBANG
  head    = [shebang, BLOCK_START, "# Managed by Vagrant - adopted from hooks_source (hook: #{name})"]

  (head + lines + [BLOCK_STOP]).join(newline) + newline
end

.body_lines(commands) ⇒ Object



65
66
67
# File 'lib/vagrant-git-hooks/hook_builder.rb', line 65

def body_lines(commands)
  Array(commands).flat_map { |c| c.to_s.split("\n") }
end

.header(name, note) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/vagrant-git-hooks/hook_builder.rb', line 51

def header(name, note)
  ts = begin
    Time.now.utc.iso8601
  rescue StandardError
    Time.now.utc.to_s
  end
  [
    SHEBANG,
    BLOCK_START,
    "# Managed by Vagrant - #{note} (hook: #{name})",
    "# Generated: #{ts}"
  ]
end

.managed?(content) ⇒ Boolean

Returns:

  • (Boolean)


47
48
49
# File 'lib/vagrant-git-hooks/hook_builder.rb', line 47

def managed?(content)
  content.to_s.include?(BLOCK_START)
end

.script_for(name:, commands:, fail_on_error: true, newline: "\n") ⇒ String

Builds a managed Git hook script from configured shell commands.

Parameters:

  • name (String)

    Git hook name.

  • commands (String, Array<String>)

    Shell commands written to the hook body.

  • fail_on_error (Boolean) (defaults to: true)

    Whether to include set -e.

  • newline (String) (defaults to: "\n")

    Line separator used in the generated script.

Returns:

  • (String)

    Complete hook script.



20
21
22
23
24
25
26
# File 'lib/vagrant-git-hooks/hook_builder.rb', line 20

def script_for(name:, commands:, fail_on_error: true, newline: "\n")
  lines = header(name, "do not edit manually")
  lines << "set -e" if fail_on_error
  lines.concat(body_lines(commands))
  lines << BLOCK_STOP
  lines.join(newline) + newline
end