File: filesystem.rb

package info (click to toggle)
ruby-shoulda-matchers 7.0.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,652 kB
  • sloc: ruby: 34,046; sh: 280; makefile: 9
file content (100 lines) | stat: -rw-r--r-- 2,119 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
94
95
96
97
98
99
100
require 'fileutils'

module Tests
  class Filesystem
    PROJECT_NAME = 'test-project'.freeze
    ROOT_DIRECTORY = Pathname.new('../../../..').expand_path(__FILE__)
    TEMP_DIRECTORY = Pathname.new('/tmp/shoulda-matchers-acceptance')
    PROJECT_DIRECTORY = TEMP_DIRECTORY.join(PROJECT_NAME)

    def root_directory
      ROOT_DIRECTORY
    end

    def temp_directory
      TEMP_DIRECTORY
    end

    def project_directory
      PROJECT_DIRECTORY
    end

    def wrap(path)
      if path.is_a?(Pathname)
        path
      else
        find_in_project(path)
      end
    end

    def within_project(&block)
      Dir.chdir(project_directory, &block)
    end

    def clean
      if temp_directory.exist?
        temp_directory.rmtree
      end
    end

    def create
      project_directory.mkpath
    end

    def find_in_project(path)
      project_directory.join(path)
    end

    def open(path, *args, &block)
      find_in_project(path).open(*args, &block)
    end

    def read(path)
      find_in_project(path).read
    end

    def write(path, content)
      pathname = wrap(path)
      create_parents_of(pathname)
      pathname.open('w') { |f| f.write(content) }
    end

    def create_parents_of(path)
      wrap(path).dirname.mkpath
    end

    def append_to_file(path, content, _options = {})
      create_parents_of(path)
      open(path, 'a') { |f| f.puts("#{content}\n") } # rubocop: disable Security/Open
    end

    def remove_from_file(path, pattern)
      unless pattern.is_a?(Regexp)
        pattern = Regexp.new("^#{Regexp.escape(pattern)}$")
      end

      transform(path) do |lines|
        lines.reject { |line| line =~ pattern }
      end
    end

    def comment_lines_matching(path, pattern)
      transform(path) do |lines|
        lines.map do |line|
          if line =~ pattern
            "###{line}"
          else
            line
          end
        end
      end
    end

    def transform(path)
      content = read(path)
      lines = content.split(/\n/)
      transformed_lines = yield lines
      write(path, "#{transformed_lines.join("\n")}\n")
    end
  end
end