Class: ChefConfig::PathHelper
- Inherits:
-
Object
- Object
- ChefConfig::PathHelper
- Defined in:
- lib/chef-config/path_helper.rb
Constant Summary collapse
- WIN_MAX_PATH =
Maximum characters in a standard Windows path (260 including drive letter and NUL)
259- BACKSLASH =
'\\'.freeze
- TRAILING_SLASHES_REGEX =
/[#{path_separator_regex}]+$/.freeze
- LEADING_SLASHES_REGEX =
/^[#{path_separator_regex}]+/.freeze
Class Method Summary collapse
-
.all_homes(*args) ⇒ Object
See self.home.
-
.canonical_path(path, add_prefix = true) ⇒ Object
Produces a comparable path.
-
.cleanpath(path) ⇒ Object
This is the INVERSE of Pathname#cleanpath, it converts forward slashes to backslashes for Windows.
- .dirname(path) ⇒ Object
-
.escape_glob(*parts) ⇒ Object
deprecated
Deprecated.
this method is deprecated. Please use escape_glob_dirs
-
.escape_glob_dir(*parts) ⇒ Object
This function does not switch to backslashes for windows This is because only forwardslashes should be used with dir (even for windows).
-
.home(*args) ⇒ String
Retrieves the “home directory” of the current user while trying to ascertain the existence of said directory.
-
.is_sip_path?(path, node) ⇒ Boolean
Determine if the given path is protected by macOS System Integrity Protection.
- .join(*args) ⇒ Object
- .path_separator ⇒ Object
- .paths_eql?(path1, path2) ⇒ Boolean
-
.per_tool_home_environment=(env_var) ⇒ nil
Set the project-specific home directory environment variable.
- .printable?(string) ⇒ Boolean
- .relative_path_from(from, to) ⇒ Object
-
.split_args(line) ⇒ Object
Splits a string into an array of tokens as commands and arguments.
- .validate_path(path) ⇒ Object
- .windows_max_length_exceeded?(path) ⇒ Boolean
-
.writable_sip_path?(path) ⇒ Boolean
Determine if the given path is on the exception list for macOS System Integrity Protection.
Class Method Details
.all_homes(*args) ⇒ Object
See self.home. This method performs a similar operation except that it yields all the different possible values of ‘HOME’ that one could have on this platform. Hence, on windows, if HOMEDRIVEHOMEPATH and USERPROFILE are different, the provided block will be called twice. This method goes out and checks the existence of each location at the time of the call.
The return is a list of all the returned values from each block invocation or a list of paths if no block is provided.
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 |
# File 'lib/chef-config/path_helper.rb', line 216 def self.all_homes(*args) paths = [] paths << ENV[@@per_tool_home_environment] if defined?(@@per_tool_home_environment) && @@per_tool_home_environment && ENV[@@per_tool_home_environment] paths << ENV["CHEF_HOME"] if ENV["CHEF_HOME"] if ChefUtils.windows? # By default, Ruby uses the the following environment variables to determine Dir.home: # HOME # HOMEDRIVE HOMEPATH # USERPROFILE # Ruby only checks to see if the variable is specified - not if the directory actually exists. # On Windows, HOMEDRIVE HOMEPATH can point to a different location (such as an unavailable network mounted drive) # while USERPROFILE points to the location where the user application settings and profile are stored. HOME # is not defined as an environment variable (usually). If the home path actually uses UNC, then the prefix is # HOMESHARE instead of HOMEDRIVE. # # We instead walk down the following and only include paths that actually exist. # HOME # HOMEDRIVE HOMEPATH # HOMESHARE HOMEPATH # USERPROFILE paths << ENV["HOME"] paths << ENV["HOMEDRIVE"] + ENV["HOMEPATH"] if ENV["HOMEDRIVE"] && ENV["HOMEPATH"] paths << ENV["HOMESHARE"] + ENV["HOMEPATH"] if ENV["HOMESHARE"] && ENV["HOMEPATH"] paths << ENV["USERPROFILE"] end paths << Dir.home if ENV["HOME"] # Depending on what environment variables we're using, the slashes can go in any which way. # Just change them all to / to keep things consistent. # Note: Maybe this is a bad idea on some unixy systems where \ might be a valid character depending on # the particular brand of kool-aid you consume. This code assumes that \ and / are both # path separators on any system being used. paths = paths.map { |home_path| home_path.gsub(path_separator, ::File::SEPARATOR) if home_path } # Filter out duplicate paths and paths that don't exist. valid_paths = paths.select { |home_path| home_path && Dir.exist?(home_path.force_encoding("utf-8")) } valid_paths = valid_paths.uniq # Join all optional path elements at the end. # If a block is provided, invoke it - otherwise just return what we've got. joined_paths = valid_paths.map { |home_path| File.join(home_path, *args) } if block_given? joined_paths.each { |p| yield p } else joined_paths end end |
.canonical_path(path, add_prefix = true) ⇒ Object
Produces a comparable path.
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
# File 'lib/chef-config/path_helper.rb', line 111 def self.canonical_path(path, add_prefix = true) # First remove extra separators and resolve any relative paths abs_path = File.absolute_path(path) if ChefUtils.windows? # Add the \\?\ API prefix on Windows unless add_prefix is false # Downcase on Windows where paths are still case-insensitive abs_path.gsub!(::File::SEPARATOR, path_separator) if add_prefix && abs_path !~ /^\\\\?\\/ abs_path.insert(0, "\\\\?\\") end abs_path.downcase! end abs_path end |
.cleanpath(path) ⇒ Object
This is the INVERSE of Pathname#cleanpath, it converts forward slashes to backslashes for Windows. Since the Ruby API and the Windows APIs all consume forward slashes, this helper function should only be used for DISPLAY logic to send strings back to the user with backslashes. Internally, filename paths should generally be stored with forward slashes for consistency. It is not necessary or desired to blindly convert pathnames to have backslashes on Windows.
Generally, if the user isn’t going to be seeing it, you should be using Pathname#cleanpath instead of this function.
140 141 142 143 144 145 146 147 |
# File 'lib/chef-config/path_helper.rb', line 140 def self.cleanpath(path) path = Pathname.new(path).cleanpath.to_s # ensure all forward slashes are backslashes if ChefUtils.windows? path = path.gsub(File::SEPARATOR, path_separator) end path end |
.dirname(path) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/chef-config/path_helper.rb', line 29 def self.dirname(path) if ChefUtils.windows? # Find the first slash, not counting trailing slashes end_slash = path.size loop do slash = path.rindex(/[#{Regexp.escape(File::SEPARATOR)}#{Regexp.escape(path_separator)}]/, end_slash - 1) if !slash return end_slash == path.size ? "." : path_separator elsif slash == end_slash - 1 end_slash = slash else return path[0..slash - 1] end end else ::File.dirname(path) end end |
.escape_glob(*parts) ⇒ Object
this method is deprecated. Please use escape_glob_dirs
Paths which may contain glob-reserved characters need to be escaped before globbing can be done. stackoverflow.com/questions/14127343
157 158 159 160 |
# File 'lib/chef-config/path_helper.rb', line 157 def self.escape_glob(*parts) path = cleanpath(join(*parts)) path.gsub(/[\\\{\}\[\]\*\?]/) { |x| "\\" + x } end |
.escape_glob_dir(*parts) ⇒ Object
This function does not switch to backslashes for windows This is because only forwardslashes should be used with dir (even for windows)
164 165 166 167 |
# File 'lib/chef-config/path_helper.rb', line 164 def self.escape_glob_dir(*parts) path = Pathname.new(join(*parts)).cleanpath.to_s path.gsub(/[\\\{\}\[\]\*\?]/) { |x| "\\" + x } end |
.home(*args) ⇒ String
Retrieves the “home directory” of the current user while trying to ascertain the existence of said directory. The path returned uses / for all separators (the ruby standard format). If the home directory doesn’t exist or an error is otherwise encountered, nil is returned.
If a set of path elements is provided, they are appended as-is to the home path if the homepath exists.
If an optional block is provided, the joined path is passed to that block if the home path is valid and the result of the block is returned instead.
Home-path discovery is performed once. If a path is discovered, that value is memoized so that subsequent calls to home_dir don’t bounce around.
201 202 203 204 205 206 207 |
# File 'lib/chef-config/path_helper.rb', line 201 def self.home(*args) @@home_dir ||= all_homes { |p| break p } if @@home_dir path = File.join(@@home_dir, *args) block_given? ? (yield path) : path end end |
.is_sip_path?(path, node) ⇒ Boolean
Determine if the given path is protected by macOS System Integrity Protection.
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 |
# File 'lib/chef-config/path_helper.rb', line 266 def self.is_sip_path?(path, node) if ChefUtils.macos? # @todo: parse rootless.conf for this? sip_paths = [ "/System", "/bin", "/sbin", "/usr" ] sip_paths.each do |sip_path| ChefConfig.logger.info("#{sip_path} is a SIP path, checking if it is in the exceptions list.") return true if path.start_with?(sip_path) end false else false end end |
.join(*args) ⇒ Object
63 64 65 66 67 68 69 |
# File 'lib/chef-config/path_helper.rb', line 63 def self.join(*args) args.flatten.inject do |joined_path, component| joined_path = joined_path.sub(TRAILING_SLASHES_REGEX, "") component = component.sub(LEADING_SLASHES_REGEX, "") joined_path + "#{path_separator}#{component}" end end |
.path_separator ⇒ Object
50 51 52 53 54 55 56 |
# File 'lib/chef-config/path_helper.rb', line 50 def self.path_separator if ChefUtils.windows? File::ALT_SEPARATOR || BACKSLASH else File::SEPARATOR end end |
.paths_eql?(path1, path2) ⇒ Boolean
149 150 151 |
# File 'lib/chef-config/path_helper.rb', line 149 def self.paths_eql?(path1, path2) canonical_path(path1) == canonical_path(path2) end |
.per_tool_home_environment=(env_var) ⇒ nil
Set the project-specific home directory environment variable.
This can be used to allow per-tool home directory aliases like $KNIFE_HOME.
179 180 181 182 183 |
# File 'lib/chef-config/path_helper.rb', line 179 def self.per_tool_home_environment=(env_var) @@per_tool_home_environment = env_var # Reset this in case .home was already called. @@home_dir = nil end |
.printable?(string) ⇒ Boolean
100 101 102 103 104 105 106 107 108 |
# File 'lib/chef-config/path_helper.rb', line 100 def self.printable?(string) # returns true if string is free of non-printable characters (escape sequences) # this returns false for whitespace escape sequences as well, e.g. \n\t if /[^[:print:]]/.match?(string) false else true end end |
.relative_path_from(from, to) ⇒ Object
169 170 171 |
# File 'lib/chef-config/path_helper.rb', line 169 def self.relative_path_from(from, to) Pathname.new(cleanpath(to)).relative_path_from(Pathname.new(cleanpath(from))) end |
.split_args(line) ⇒ Object
Splits a string into an array of tokens as commands and arguments
str = ‘command with “some arguments”’ split_args(str) => [“command”, “with”, “"some arguments"”]
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 |
# File 'lib/chef-config/path_helper.rb', line 302 def self.split_args(line) cmd_args = [] field = "" line.scan(/\s*(?>([^\s\\"]+|"([^"]*)"|'([^']*)')|(\S))(\s|\z)?/m) do |word, within_dq, within_sq, esc, sep| # Append the string with Word & Escape Character field << (word || esc.gsub(/\\(.)/, '\\1')) # Re-build the field when any whitespace character or # End of string is encountered if sep cmd_args << field field = "" end end cmd_args end |
.validate_path(path) ⇒ Object
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/chef-config/path_helper.rb', line 71 def self.validate_path(path) if ChefUtils.windows? unless printable?(path) msg = "Path '#{path}' contains non-printable characters. Check that backslashes are escaped with another backslash (e.g. C:\\\\Windows) in double-quoted strings." ChefConfig.logger.error(msg) raise ChefConfig::InvalidPath, msg end if windows_max_length_exceeded?(path) ChefConfig.logger.trace("Path '#{path}' is longer than #{WIN_MAX_PATH}, prefixing with'\\\\?\\'") path.insert(0, "\\\\?\\") end end path end |
.windows_max_length_exceeded?(path) ⇒ Boolean
88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/chef-config/path_helper.rb', line 88 def self.windows_max_length_exceeded?(path) # Check to see if paths without the \\?\ prefix are over the maximum allowed length for the Windows API # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx unless /^\\\\?\\/.match?(path) if path.length > WIN_MAX_PATH return true end end false end |
.writable_sip_path?(path) ⇒ Boolean
Determine if the given path is on the exception list for macOS System Integrity Protection.
283 284 285 286 287 288 289 290 291 292 293 294 295 |
# File 'lib/chef-config/path_helper.rb', line 283 def self.writable_sip_path?(path) # todo: parse rootless.conf for this? sip_exceptions = [ "/System/Library/Caches", "/System/Library/Extensions", "/System/Library/Speech", "/System/Library/User Template", "/usr/libexec/cups", "/usr/local", "/usr/share/man" ] sip_exceptions.each do |exception_path| return true if path.start_with?(exception_path) end ChefConfig.logger.error("Cannot write to a SIP path #{path} on macOS!") false end |