Module: Overcommit::Utils
- Defined in:
- lib/overcommit/utils.rb,
lib/overcommit/utils/file_utils.rb,
lib/overcommit/utils/messages_utils.rb
Overview
Utility functions for general use.
Defined Under Namespace
Modules: FileUtils, MessagesUtils Classes: Version
Class Attribute Summary collapse
-
.log ⇒ Overcommit::Logger
Logger with which to send debug output.
Class Method Summary collapse
-
.broken_symlink?(file) ⇒ true, false
Returns whether a file is a broken symlink.
-
.camel_case(str) ⇒ Object
Converts a string containing underscores/hyphens/spaces into CamelCase.
-
.convert_glob_to_absolute(glob) ⇒ String
Convert a glob pattern to an absolute path glob pattern rooted from the repository root directory.
-
.execute(initial_args, options = {}) ⇒ Overcommit::Subprocess::Result
Execute a command in a subprocess, capturing exit status and output from both standard and error streams.
-
.execute_in_background(args) ⇒ ChildProcess
Execute a command in a subprocess, returning immediately.
-
.git_dir ⇒ String
Returns an absolute path to the .git directory for a repo.
-
.in_path?(cmd) ⇒ true, false
Whether a command can be found given the current environment path.
-
.matches_path?(pattern, path) ⇒ Boolean
Return whether a pattern matches the given path.
-
.parent_command ⇒ String?
Return the parent command that triggered this hook run.
-
.processor_count ⇒ Object
Return the number of processors used by the OS for process scheduling.
-
.repo_root ⇒ String
Returns an absolute path to the root of the repository.
- .script_path(script) ⇒ Object
-
.snake_case(str) ⇒ Object
Shamelessly stolen from: stackoverflow.com/questions/1509915/converting-camel-case-to-underscore-case-in-ruby.
-
.strip_color_codes(text) ⇒ String
Remove ANSI escape sequences from a string.
-
.supported_hook_type_classes ⇒ Object
Returns a list of supported hook classes (PreCommit, CommitMsg, etc.).
-
.supported_hook_types ⇒ Object
Returns a list of supported hook types (pre-commit, commit-msg, etc.).
-
.with_environment(env) ⇒ Object
Calls a block of code with a modified set of environment variables, restoring them once the code has executed.
Class Attribute Details
.log ⇒ Overcommit::Logger
Returns logger with which to send debug output.
33 34 35 |
# File 'lib/overcommit/utils.rb', line 33 def log @log end |
Class Method Details
.broken_symlink?(file) ⇒ true, false
Returns whether a file is a broken symlink.
240 241 242 243 244 |
# File 'lib/overcommit/utils.rb', line 240 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.
98 99 100 |
# File 'lib/overcommit/utils.rb', line 98 def camel_case(str) str.split(/_|-| /).map { |part| part.sub(/^\w/, &: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.
251 252 253 |
# File 'lib/overcommit/utils.rb', line 251 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.
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
# File 'lib/overcommit/utils.rb', line 179 def execute(initial_args, = {}) if initial_args.include?('|') raise Overcommit::Exceptions::InvalidCommandArgs, 'Cannot pipe commands with the `execute` helper' end result = if (splittable_args = .fetch(:args) { [] }).any? debug(initial_args.join(' ') + " ... (#{splittable_args.length} splittable args)") Overcommit::CommandSplitter.execute(initial_args, ) else debug(initial_args.join(' ')) Overcommit::Subprocess.spawn(initial_args, ) 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.
208 209 210 211 212 213 214 215 216 |
# File 'lib/overcommit/utils.rb', line 208 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 ⇒ String
Returns an absolute path to the .git directory for a repo.
62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/overcommit/utils.rb', line 62 def git_dir @git_dir ||= begin cmd = %w[git rev-parse] cmd << (GIT_VERSION < '2.5' ? '--git-dir' : '--git-common-dir') result = execute(cmd) unless result.success? raise Overcommit::Exceptions::InvalidGitRepo, 'Unable to determine location of GIT_DIR. ' \ 'Not a recognizable Git repository!' end File.(result.stdout.chomp("\n"), Dir.pwd) end end |
.in_path?(cmd) ⇒ true, false
Returns whether a command can be found given the current environment path.
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
# File 'lib/overcommit/utils.rb', line 120 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.
259 260 261 262 263 264 265 |
# File 'lib/overcommit/utils.rb', line 259 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_command ⇒ String?
Return the parent command that triggered this hook run
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
# File 'lib/overcommit/utils.rb', line 139 def parent_command # When run in Docker containers, there may be no parent process. return if Process.ppid.zero? 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 rescue Errno::EPERM, Errno::ENOENT # Process information may not be available, such as inside sandboxed environments nil end |
.processor_count ⇒ Object
Return the number of processors used by the OS for process scheduling.
219 220 221 |
# File 'lib/overcommit/utils.rb', line 219 def processor_count @processor_count ||= Etc.nprocessors end |
.repo_root ⇒ String
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.
46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/overcommit/utils.rb', line 46 def repo_root @repo_root ||= begin result = execute(%w[git rev-parse --show-toplevel]) unless result.success? raise Overcommit::Exceptions::InvalidGitRepo, 'Unable to determine location of GIT_DIR. ' \ 'Not a recognizable Git repository!' end result.stdout.chomp("\n") end end |
.script_path(script) ⇒ Object
35 36 37 |
# File 'lib/overcommit/utils.rb', line 35 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
89 90 91 92 93 94 95 |
# File 'lib/overcommit/utils.rb', line 89 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.
83 84 85 |
# File 'lib/overcommit/utils.rb', line 83 def strip_color_codes(text) text.gsub(/\e\[(\d+)(;\d+)*m/, '') end |
.supported_hook_type_classes ⇒ Object
Returns a list of supported hook classes (PreCommit, CommitMsg, etc.)
111 112 113 114 115 |
# File 'lib/overcommit/utils.rb', line 111 def supported_hook_type_classes supported_hook_types.map do |file| file.split('-').map(&:capitalize).join end end |
.supported_hook_types ⇒ Object
Returns a list of supported hook types (pre-commit, commit-msg, etc.)
103 104 105 106 107 108 |
# File 'lib/overcommit/utils.rb', line 103 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.
225 226 227 228 229 230 231 232 233 234 235 |
# File 'lib/overcommit/utils.rb', line 225 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 |