Module: Overcommit::Utils

Defined in:
lib/overcommit/utils.rb,
lib/overcommit/utils/file_utils.rb

Overview

Utility functions for general use.

Defined Under Namespace

Modules: FileUtils Classes: Version

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.logOvercommit::Logger

Returns logger with which to send debug output.

Returns:



30
31
32
# File 'lib/overcommit/utils.rb', line 30

def log
  @log
end

Class Method Details

.broken_symlink?(file) ⇒ true, false

Returns whether a file is a broken symlink.

Returns:

  • (true, false)


231
232
233
234
235
# File 'lib/overcommit/utils.rb', line 231

def broken_symlink?(file)
  # JRuby's implementation of File.exist? returns true for broken
  # symlinks, so we need use File.size?
  Overcommit::Utils::FileUtils.symlink?(file) && File.size?(file).nil?
end

.camel_case(str) ⇒ Object

Converts a string containing underscores/hyphens/spaces into CamelCase.



102
103
104
# File 'lib/overcommit/utils.rb', line 102

def camel_case(str)
  str.split(/_|-| /).map { |part| part.sub(/^\w/) { |c| c.upcase } }.join
end

.convert_glob_to_absolute(glob) ⇒ String

Convert a glob pattern to an absolute path glob pattern rooted from the repository root directory.

Parameters:

  • glob (String)

Returns:

  • (String)


242
243
244
# File 'lib/overcommit/utils.rb', line 242

def convert_glob_to_absolute(glob)
  File.join(repo_root, glob)
end

.execute(initial_args, options = {}) ⇒ Overcommit::Subprocess::Result

Execute a command in a subprocess, capturing exit status and output from both standard and error streams.

This is intended to provide a centralized place to perform any checks or filtering of the command before executing it.

The ‘args` option provides a convenient way of splitting up long argument lists which would otherwise exceed the maximum command line length of the OS. It will break up the list into chunks and run the command with the same prefix `initial_args`, finally combining the output together at the end.

This requires that the external command you are running can have its work split up in this way and still produce the same resultant output when outputs of the individual commands are concatenated back together.

Parameters:

  • initial_args (Array<String>)
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :args (Array<String>)

    long list of arguments to split up

Returns:



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/overcommit/utils.rb', line 175

def execute(initial_args, options = {})
  if initial_args.include?('|')
    raise Overcommit::Exceptions::InvalidCommandArgs,
          'Cannot pipe commands with the `execute` helper'
  end

  result =
    if (splittable_args = options.fetch(:args, [])).any?
      debug(initial_args.join(' ') + " ... (#{splittable_args.length} splittable args)")
      Overcommit::CommandSplitter.execute(initial_args, options)
    else
      debug(initial_args.join(' '))
      Overcommit::Subprocess.spawn(initial_args, options)
    end

  debug("EXIT STATUS: #{result.status}")
  debug("STDOUT: #{result.stdout.inspect}")
  debug("STDERR: #{result.stderr.inspect}")

  result
end

.execute_in_background(args) ⇒ ChildProcess

Execute a command in a subprocess, returning immediately.

This provides a convenient way to execute long-running processes for which we do not need to know the result.

Parameters:

  • args (Array<String>)

Returns:

  • (ChildProcess)

    detached process spawned in the background



204
205
206
207
208
209
210
211
212
# File 'lib/overcommit/utils.rb', line 204

def execute_in_background(args)
  if args.include?('|')
    raise Overcommit::Exceptions::InvalidCommandArgs,
          'Cannot pipe commands with the `execute_in_background` helper'
  end

  debug("Spawning background task: #{args.join(' ')}")
  Subprocess.spawn_detached(args)
end

.git_dir(repo_dir = repo_root) ⇒ String

Returns an absolute path to the .git directory for a repo.

Parameters:

  • repo_dir (String) (defaults to: repo_root)

    root directory of git repo

Returns:

  • (String)


62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/overcommit/utils.rb', line 62

def git_dir(repo_dir = repo_root)
  @git_dir ||=
    begin
      git_dir = File.expand_path('.git', repo_dir)

      # .git could also be a file that contains the location of the git directory
      unless File.directory?(git_dir)
        git_dir = File.read(git_dir)[/^gitdir: (.*)$/, 1]

        # Resolve relative paths
        unless git_dir.start_with?('/')
          git_dir = File.expand_path(git_dir, repo_dir)
        end
      end

      git_dir
    end
end

.in_path?(cmd) ⇒ true, false

Returns whether a command can be found given the current environment path.

Parameters:

  • cmd (String)

Returns:

  • (true, false)

    whether a command can be found given the current environment path.



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/overcommit/utils.rb', line 124

def in_path?(cmd)
  # ENV['PATH'] doesn't include the repo root, but that is a valid
  # location for executables, so we want to add it to the list of places
  # we are checking for the executable.
  paths = [repo_root] + ENV['PATH'].split(File::PATH_SEPARATOR)
  exts  = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : ['']
  paths.each do |path|
    exts.each do |ext|
      cmd_with_ext = cmd.upcase.end_with?(ext.upcase) ? cmd : "#{cmd}#{ext}"
      full_path = File.join(path, cmd_with_ext)
      return true if File.executable?(full_path)
    end
  end
  false
end

.matches_path?(pattern, path) ⇒ Boolean

Return whether a pattern matches the given path.

Parameters:

  • pattern (String)
  • path (String)

Returns:

  • (Boolean)


250
251
252
253
254
255
# File 'lib/overcommit/utils.rb', line 250

def matches_path?(pattern, path)
  File.fnmatch?(pattern, path,
                File::FNM_PATHNAME | # Wildcard doesn't match separator
                File::FNM_DOTMATCH   # Wildcards match dotfiles
  )
end

.parent_commandObject

Return the parent command that triggered this hook run



141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/overcommit/utils.rb', line 141

def parent_command
  if OS.windows?
    `wmic process where ProcessId=#{Process.ppid} get CommandLine /FORMAT:VALUE`.
      strip.
      slice(/(?<=CommandLine=).+/)
  elsif OS.cygwin?
    # Cygwin's `ps` command behaves differently than the traditional
    # Linux version, but a comparable `procps` is provided to compensate.
    `procps -ocommand= -p #{Process.ppid}`.chomp
  else
    `ps -ocommand= -p #{Process.ppid}`.chomp
  end
end

.repo_rootString

Returns an absolute path to the root of the repository.

We do this ourselves rather than call ‘git rev-parse –show-toplevel` to solve an issue where the .git directory might not actually be valid in tests.

Returns:

  • (String)


43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/overcommit/utils.rb', line 43

def repo_root
  @repo_root ||=
    begin
      git_dir = Pathname.new(File.expand_path('.')).enum_for(:ascend).find do |path|
        File.exist?(File.join(path, '.git'))
      end

      unless git_dir
        raise Overcommit::Exceptions::InvalidGitRepo, 'no .git directory found'
      end

      git_dir.to_s
    end
end

.script_path(script) ⇒ Object



32
33
34
# File 'lib/overcommit/utils.rb', line 32

def script_path(script)
  File.join(Overcommit::HOME, 'libexec', script)
end

.snake_case(str) ⇒ Object

Shamelessly stolen from: stackoverflow.com/questions/1509915/converting-camel-case-to-underscore-case-in-ruby



93
94
95
96
97
98
99
# File 'lib/overcommit/utils.rb', line 93

def snake_case(str)
  str.gsub(/::/, '/').
      gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').
      gsub(/([a-z\d])([A-Z])/, '\1_\2').
      tr('-', '_').
      downcase
end

.strip_color_codes(text) ⇒ String

Remove ANSI escape sequences from a string.

This is useful for stripping colorized output from external tools.

Parameters:

  • text (String)

Returns:

  • (String)


87
88
89
# File 'lib/overcommit/utils.rb', line 87

def strip_color_codes(text)
  text.gsub(/\e\[(\d+)(;\d+)*m/, '')
end

.supported_hook_type_classesObject

Returns a list of supported hook classes (PreCommit, CommitMsg, etc.)



115
116
117
118
119
# File 'lib/overcommit/utils.rb', line 115

def supported_hook_type_classes
  supported_hook_types.map do |file|
    file.split('-').map(&:capitalize).join
  end
end

.supported_hook_typesObject

Returns a list of supported hook types (pre-commit, commit-msg, etc.)



107
108
109
110
111
112
# File 'lib/overcommit/utils.rb', line 107

def supported_hook_types
  Dir[File.join(HOOK_DIRECTORY, '*')].
    select { |file| File.directory?(file) }.
    reject { |file| File.basename(file) == 'shared' }.
    map { |file| File.basename(file).tr('_', '-') }
end

.with_environment(env) ⇒ Object

Calls a block of code with a modified set of environment variables, restoring them once the code has executed.



216
217
218
219
220
221
222
223
224
225
226
# File 'lib/overcommit/utils.rb', line 216

def with_environment(env)
  old_env = {}
  env.each do |var, value|
    old_env[var] = ENV[var.to_s]
    ENV[var.to_s] = value
  end

  yield
ensure
  old_env.each { |var, value| ENV[var.to_s] = value }
end