File: path_pattern.rb

package info (click to toggle)
puppet-agent 7.23.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 19,092 kB
  • sloc: ruby: 245,074; sh: 456; makefile: 38; xml: 33
file content (93 lines) | stat: -rw-r--r-- 2,304 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
require 'pathname'
require_relative '../../puppet/error'

module Puppet::FileSystem
  class PathPattern
    class InvalidPattern < Puppet::Error; end

    DOTDOT = '..'.freeze
    ABSOLUTE_UNIX = /^\//
    ABSOLUTE_WINDOWS = /^[a-z]:/i
    CURRENT_DRIVE_RELATIVE_WINDOWS = /^\\/

    def self.relative(pattern)
      RelativePathPattern.new(pattern)
    end

    def self.absolute(pattern)
      AbsolutePathPattern.new(pattern)
    end

    class << self
      protected :new
    end

    # @param prefix [AbsolutePathPattern] An absolute path pattern instance
    # @return [AbsolutePathPattern] A new AbsolutePathPattern prepended with
    #   the passed prefix's pattern.
    def prefix_with(prefix)
      new_pathname = prefix.pathname + pathname
      self.class.absolute(new_pathname.to_s)
    end

    def glob
      Dir.glob(@pathstr)
    end

    def to_s
      @pathstr
    end

    protected

    attr_reader :pathname

    private

    def validate
      if @pathstr.split(Pathname::SEPARATOR_PAT).any? { |f| f == DOTDOT }
        raise(InvalidPattern, _("PathPatterns cannot be created with directory traversals."))
      elsif @pathstr.match?(CURRENT_DRIVE_RELATIVE_WINDOWS)
        raise(InvalidPattern, _("A PathPattern cannot be a Windows current drive relative path."))
      end
    end

    def initialize(pattern)
      begin
        @pathname = Pathname.new(pattern.strip)
        @pathstr = @pathname.to_s
      rescue ArgumentError => error
        raise InvalidPattern.new(_("PathPatterns cannot be created with a zero byte."), error)
      end
      validate
    end
  end

  class RelativePathPattern < PathPattern
    def absolute?
      false
    end

    def validate
      super
      if @pathstr.match?(ABSOLUTE_WINDOWS)
        raise(InvalidPattern, _("A relative PathPattern cannot be prefixed with a drive."))
      elsif @pathstr.match?(ABSOLUTE_UNIX)
        raise(InvalidPattern, _("A relative PathPattern cannot be an absolute path."))
      end
    end
  end

  class AbsolutePathPattern < PathPattern
    def absolute?
      true
    end

    def validate
      super
      if !@pathstr.match?(ABSOLUTE_UNIX) && !@pathstr.match?(ABSOLUTE_WINDOWS)
        raise(InvalidPattern, _("An absolute PathPattern cannot be a relative path."))
      end
    end
  end
end