r10k 3.9.2 → 3.12.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (82) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/rspec_tests.yml +1 -1
  3. data/.travis.yml +0 -10
  4. data/CHANGELOG.mkd +33 -0
  5. data/README.mkd +6 -0
  6. data/doc/dynamic-environments/configuration.mkd +25 -0
  7. data/doc/dynamic-environments/usage.mkd +26 -0
  8. data/doc/puppetfile.mkd +18 -5
  9. data/integration/Rakefile +3 -1
  10. data/integration/tests/basic_functionality/basic_deployment.rb +176 -0
  11. data/integration/tests/user_scenario/basic_workflow/negative/neg_specify_deleted_forge_module.rb +3 -9
  12. data/integration/tests/user_scenario/basic_workflow/single_env_purge_unmanaged_modules.rb +21 -25
  13. data/integration/tests/user_scenario/complex_workflow/multi_env_add_change_remove.rb +3 -3
  14. data/integration/tests/user_scenario/complex_workflow/multi_env_remove_re-add.rb +3 -3
  15. data/integration/tests/user_scenario/complex_workflow/multi_env_unamanaged.rb +3 -3
  16. data/lib/r10k/action/deploy/environment.rb +17 -2
  17. data/lib/r10k/action/deploy/module.rb +38 -7
  18. data/lib/r10k/action/puppetfile/check.rb +7 -5
  19. data/lib/r10k/action/puppetfile/install.rb +22 -16
  20. data/lib/r10k/action/puppetfile/purge.rb +12 -9
  21. data/lib/r10k/action/runner.rb +45 -10
  22. data/lib/r10k/cli/deploy.rb +5 -0
  23. data/lib/r10k/cli/puppetfile.rb +0 -1
  24. data/lib/r10k/content_synchronizer.rb +16 -4
  25. data/lib/r10k/environment/base.rb +64 -11
  26. data/lib/r10k/environment/with_modules.rb +6 -10
  27. data/lib/r10k/git/cache.rb +1 -1
  28. data/lib/r10k/git/rugged/credentials.rb +77 -0
  29. data/lib/r10k/git/stateful_repository.rb +8 -0
  30. data/lib/r10k/git.rb +3 -0
  31. data/lib/r10k/initializers.rb +4 -0
  32. data/lib/r10k/module/base.rb +42 -1
  33. data/lib/r10k/module/definition.rb +64 -0
  34. data/lib/r10k/module/forge.rb +17 -4
  35. data/lib/r10k/module/git.rb +24 -2
  36. data/lib/r10k/module/local.rb +2 -3
  37. data/lib/r10k/module/svn.rb +12 -1
  38. data/lib/r10k/module.rb +20 -2
  39. data/lib/r10k/module_loader/puppetfile/dsl.rb +42 -0
  40. data/lib/r10k/module_loader/puppetfile.rb +272 -0
  41. data/lib/r10k/puppetfile.rb +82 -160
  42. data/lib/r10k/settings/definition.rb +1 -1
  43. data/lib/r10k/settings.rb +58 -2
  44. data/lib/r10k/source/base.rb +10 -0
  45. data/lib/r10k/source/git.rb +5 -0
  46. data/lib/r10k/source/svn.rb +4 -0
  47. data/lib/r10k/util/purgeable.rb +70 -8
  48. data/lib/r10k/version.rb +1 -1
  49. data/locales/r10k.pot +165 -65
  50. data/r10k.gemspec +2 -0
  51. data/spec/fixtures/unit/action/r10k_forge_auth.yaml +4 -0
  52. data/spec/fixtures/unit/action/r10k_forge_auth_no_url.yaml +3 -0
  53. data/spec/fixtures/unit/puppetfile/forge-override/Puppetfile +8 -0
  54. data/spec/fixtures/unit/puppetfile/various-modules/Puppetfile +9 -0
  55. data/spec/fixtures/unit/puppetfile/various-modules/Puppetfile.new +9 -0
  56. data/spec/fixtures/unit/util/purgeable/managed_one/managed_subdir_1/managed_subdir_2/ignored_1 +0 -0
  57. data/spec/fixtures/unit/util/purgeable/managed_two/.hidden/unmanaged_3 +0 -0
  58. data/spec/r10k-mocks/mock_env.rb +3 -0
  59. data/spec/r10k-mocks/mock_source.rb +7 -3
  60. data/spec/unit/action/deploy/environment_spec.rb +105 -30
  61. data/spec/unit/action/deploy/module_spec.rb +232 -42
  62. data/spec/unit/action/puppetfile/check_spec.rb +17 -5
  63. data/spec/unit/action/puppetfile/install_spec.rb +42 -36
  64. data/spec/unit/action/puppetfile/purge_spec.rb +15 -17
  65. data/spec/unit/action/runner_spec.rb +122 -26
  66. data/spec/unit/environment/base_spec.rb +30 -17
  67. data/spec/unit/environment/git_spec.rb +2 -2
  68. data/spec/unit/environment/svn_spec.rb +4 -3
  69. data/spec/unit/environment/with_modules_spec.rb +2 -1
  70. data/spec/unit/git/cache_spec.rb +14 -0
  71. data/spec/unit/git/rugged/credentials_spec.rb +29 -0
  72. data/spec/unit/git/stateful_repository_spec.rb +5 -0
  73. data/spec/unit/module/base_spec.rb +54 -8
  74. data/spec/unit/module/forge_spec.rb +59 -5
  75. data/spec/unit/module/git_spec.rb +67 -17
  76. data/spec/unit/module/svn_spec.rb +35 -5
  77. data/spec/unit/module_loader/puppetfile_spec.rb +403 -0
  78. data/spec/unit/module_spec.rb +28 -0
  79. data/spec/unit/puppetfile_spec.rb +125 -189
  80. data/spec/unit/settings_spec.rb +47 -2
  81. data/spec/unit/util/purgeable_spec.rb +38 -6
  82. metadata +28 -2
@@ -8,24 +8,31 @@ module R10K
8
8
  end
9
9
 
10
10
  def self.serial_sync(modules)
11
+ updated_modules = []
11
12
  modules.each do |mod|
12
- mod.sync
13
+ updated = mod.sync
14
+ updated_modules << mod.name if updated
13
15
  end
16
+ updated_modules
14
17
  end
15
18
 
19
+ # Returns a Queue of the names of modules actually updated
16
20
  def self.concurrent_accept(modules, visitor, loader, pool_size, logger)
17
21
  mods_queue = modules_visit_queue(modules, visitor, loader)
18
22
  sync_queue(mods_queue, pool_size, logger)
19
23
  end
20
24
 
25
+ # Returns a Queue of the names of modules actually updated
21
26
  def self.concurrent_sync(modules, pool_size, logger)
22
27
  mods_queue = modules_sync_queue(modules)
23
28
  sync_queue(mods_queue, pool_size, logger)
24
29
  end
25
30
 
31
+ # Returns a Queue of the names of modules actually updated
26
32
  def self.sync_queue(mods_queue, pool_size, logger)
27
33
  logger.debug _("Updating modules with %{pool_size} threads") % {pool_size: pool_size}
28
- thread_pool = pool_size.times.map { sync_thread(mods_queue, logger) }
34
+ updated_modules = Queue.new
35
+ thread_pool = pool_size.times.map { sync_thread(mods_queue, logger, updated_modules) }
29
36
  thread_exception = nil
30
37
 
31
38
  # If any threads raise an exception the deployment is considered a failure.
@@ -33,6 +40,8 @@ module R10K
33
40
  # current work, then re-raise the first exception caught.
34
41
  begin
35
42
  thread_pool.each(&:join)
43
+ # Return the list of all modules that were actually updated
44
+ updated_modules
36
45
  rescue => e
37
46
  logger.error _("Error during concurrent deploy of a module: %{message}") % {message: e.message}
38
47
  mods_queue.clear
@@ -65,11 +74,14 @@ module R10K
65
74
  modules_by_cachedir.values.each {|mods| queue << mods }
66
75
  end
67
76
 
68
- def self.sync_thread(mods_queue, logger)
77
+ def self.sync_thread(mods_queue, logger, updated_modules)
69
78
  Thread.new do
70
79
  begin
71
80
  while mods = mods_queue.pop(true) do
72
- mods.each { |mod| mod.sync }
81
+ mods.each do |mod|
82
+ updated = mod.sync
83
+ updated_modules << mod.name if updated
84
+ end
73
85
  end
74
86
  rescue ThreadError => e
75
87
  logger.debug _("Module thread %{id} exiting: %{message}") % {message: e.message, id: Thread.current.object_id}
@@ -1,5 +1,8 @@
1
- require 'r10k/util/subprocess'
1
+ require 'r10k/content_synchronizer'
2
2
  require 'r10k/logging'
3
+ require 'r10k/module_loader/puppetfile'
4
+ require 'r10k/util/cleaner'
5
+ require 'r10k/util/subprocess'
3
6
 
4
7
  # This class defines a common interface for environment implementations.
5
8
  #
@@ -34,6 +37,10 @@ class R10K::Environment::Base
34
37
  # @return [String] The puppetfile name (relative)
35
38
  attr_reader :puppetfile_name
36
39
 
40
+ attr_reader :managed_directories, :desired_contents
41
+
42
+ attr_reader :loader
43
+
37
44
  # Initialize the given environment.
38
45
  #
39
46
  # @param name [String] The unique name describing this environment.
@@ -57,6 +64,20 @@ class R10K::Environment::Base
57
64
  force: @overrides.dig(:modules, :force),
58
65
  puppetfile_name: @puppetfile_name})
59
66
  @puppetfile.environment = self
67
+
68
+ loader_options = { basedir: @full_path, overrides: @overrides, environment: self }
69
+ loader_options[:puppetfile] = @puppetfile_name if @puppetfile_name
70
+
71
+ @loader = R10K::ModuleLoader::Puppetfile.new(**loader_options)
72
+
73
+ if @overrides.dig(:environments, :incremental)
74
+ @loader.load_metadata
75
+ end
76
+
77
+ @base_modules = nil
78
+ @purge_exclusions = nil
79
+ @managed_directories = [ @full_path ]
80
+ @desired_contents = []
60
81
  end
61
82
 
62
83
  # Synchronize the given environment.
@@ -106,8 +127,11 @@ class R10K::Environment::Base
106
127
  # @return [Array<R10K::Module::Base>] All modules defined in the Puppetfile
107
128
  # associated with this environment.
108
129
  def modules
109
- @puppetfile.load
110
- @puppetfile.modules
130
+ if @base_modules.nil?
131
+ load_puppetfile_modules
132
+ end
133
+
134
+ @base_modules
111
135
  end
112
136
 
113
137
  # @return [Array<R10K::Module::Base>] Whether or not the given module
@@ -123,29 +147,50 @@ class R10K::Environment::Base
123
147
  end
124
148
  end
125
149
 
150
+
151
+ # Returns a Queue of the names of modules actually updated
126
152
  def deploy
127
- puppetfile.load(@overrides.dig(:environments, :default_branch_override))
153
+ if @base_modules.nil?
154
+ load_puppetfile_modules
155
+ end
128
156
 
129
- puppetfile.sync
157
+ if ! @base_modules.empty?
158
+ pool_size = @overrides.dig(:modules, :pool_size)
159
+ updated_modules = R10K::ContentSynchronizer.concurrent_sync(@base_modules, pool_size, logger)
160
+ end
130
161
 
131
162
  if (@overrides.dig(:purging, :purge_levels) || []).include?(:puppetfile)
132
163
  logger.debug("Purging unmanaged Puppetfile content for environment '#{dirname}'...")
133
- R10K::Util::Cleaner.new(puppetfile.managed_directories,
134
- puppetfile.desired_contents,
135
- puppetfile.purge_exclusions).purge!
164
+ @puppetfile_cleaner.purge!
136
165
  end
166
+
167
+ updated_modules
168
+ end
169
+
170
+ def load_puppetfile_modules
171
+ loaded_content = @loader.load
172
+ @base_modules = loaded_content[:modules]
173
+
174
+ @purge_exclusions = determine_purge_exclusions(loaded_content[:managed_directories],
175
+ loaded_content[:desired_contents])
176
+
177
+ @puppetfile_cleaner = R10K::Util::Cleaner.new(loaded_content[:managed_directories],
178
+ loaded_content[:desired_contents],
179
+ loaded_content[:purge_exclusions])
137
180
  end
138
181
 
139
182
  def whitelist(user_whitelist=[])
140
183
  user_whitelist.collect { |pattern| File.join(@full_path, pattern) }
141
184
  end
142
185
 
143
- def purge_exclusions
186
+ def determine_purge_exclusions(pf_managed_dirs = @puppetfile.managed_directories,
187
+ pf_desired_contents = @puppetfile.desired_contents)
188
+
144
189
  list = [File.join(@full_path, '.r10k-deploy.json')].to_set
145
190
 
146
- list += @puppetfile.managed_directories
191
+ list += pf_managed_dirs
147
192
 
148
- list += @puppetfile.desired_contents.flat_map do |item|
193
+ list += pf_desired_contents.flat_map do |item|
149
194
  desired_tree = []
150
195
 
151
196
  if File.directory?(item)
@@ -163,6 +208,14 @@ class R10K::Environment::Base
163
208
  list.to_a
164
209
  end
165
210
 
211
+ def purge_exclusions
212
+ if @purge_exclusions.nil?
213
+ load_puppetfile_modules
214
+ end
215
+
216
+ @purge_exclusions
217
+ end
218
+
166
219
  def generate_types!
167
220
  argv = [R10K::Settings.puppet_path, 'generate', 'types', '--environment', dirname, '--environmentpath', basedir, '--config', R10K::Settings.puppet_conf]
168
221
  subproc = R10K::Util::Subprocess.new(argv)
@@ -23,6 +23,7 @@ class R10K::Environment::WithModules < R10K::Environment::Base
23
23
  def initialize(name, basedir, dirname, options = {})
24
24
  super
25
25
 
26
+ @all_modules = nil
26
27
  @managed_content = {}
27
28
  @modules = []
28
29
  @moduledir = case options[:moduledir]
@@ -43,10 +44,12 @@ class R10K::Environment::WithModules < R10K::Environment::Base
43
44
  # - The r10k environment object
44
45
  # - A Puppetfile in the environment's content
45
46
  def modules
46
- return @modules if puppetfile.nil?
47
+ if @all_modules.nil?
48
+ puppetfile_modules = super()
49
+ @all_modules = @modules + puppetfile_modules
50
+ end
47
51
 
48
- puppetfile.load unless puppetfile.loaded?
49
- @modules + puppetfile.modules
52
+ @all_modules
50
53
  end
51
54
 
52
55
  def module_conflicts?(mod_b)
@@ -126,13 +129,6 @@ class R10K::Environment::WithModules < R10K::Environment::Base
126
129
 
127
130
  include R10K::Util::Purgeable
128
131
 
129
- # Returns an array of the full paths that can be purged.
130
- # @note This implements a required method for the Purgeable mixin
131
- # @return [Array<String>]
132
- def managed_directories
133
- [@full_path]
134
- end
135
-
136
132
  # Returns an array of the full paths of filenames that should exist. Files
137
133
  # inside managed_directories that are not listed in desired_contents will
138
134
  # be purged.
@@ -111,6 +111,6 @@ class R10K::Git::Cache
111
111
 
112
112
  # Reformat the remote name into something that can be used as a directory
113
113
  def sanitized_dirname
114
- @sanitized_dirname ||= @remote.gsub(/[^@\w\.-]/, '-')
114
+ @sanitized_dirname ||= @remote.gsub(/(\w+:\/\/)(.*)(@)/, '\1').gsub(/[^@\w\.-]/, '-')
115
115
  end
116
116
  end
@@ -1,6 +1,10 @@
1
1
  require 'r10k/git/rugged'
2
2
  require 'r10k/git/errors'
3
3
  require 'r10k/logging'
4
+ require 'json'
5
+ require 'jwt'
6
+ require 'net/http'
7
+ require 'openssl'
4
8
 
5
9
  # Generate credentials for secured remote connections.
6
10
  #
@@ -62,15 +66,29 @@ class R10K::Git::Rugged::Credentials
62
66
 
63
67
  def get_plaintext_credentials(url, username_from_url)
64
68
  per_repo_oauth_token = nil
69
+ per_repo_github_app_id = nil
70
+ per_repo_github_app_key = nil
71
+ per_repo_github_app_ttl = nil
72
+
65
73
  if per_repo_settings = R10K::Git.get_repo_settings(url)
66
74
  per_repo_oauth_token = per_repo_settings[:oauth_token]
75
+ per_repo_github_app_id = per_repo_settings[:github_app_id]
76
+ per_repo_github_app_key = per_repo_settings[:github_app_key]
77
+ per_repo_github_app_ttl = per_repo_settings[:github_app_ttl]
67
78
  end
68
79
 
80
+ app_id = per_repo_github_app_id || R10K::Git.settings[:github_app_id]
81
+ app_key = per_repo_github_app_key || R10K::Git.settings[:github_app_key]
82
+ app_ttl = per_repo_github_app_ttl || R10K::Git.settings[:github_app_ttl]
83
+
69
84
  if token_path = per_repo_oauth_token || R10K::Git.settings[:oauth_token]
70
85
  @oauth_token ||= extract_token(token_path, url)
71
86
 
72
87
  user = 'x-oauth-token'
73
88
  password = @oauth_token
89
+ elsif app_id && app_key && app_ttl
90
+ user = 'x-access-token'
91
+ password = github_app_token(app_id, app_key, app_ttl)
74
92
  else
75
93
  user = get_git_username(url, username_from_url)
76
94
  password = URI.parse(url).password || ''
@@ -125,4 +143,63 @@ class R10K::Git::Rugged::Credentials
125
143
 
126
144
  user
127
145
  end
146
+
147
+ def github_app_token(app_id, private_key, ttl)
148
+ raise R10K::Git::GitError, _('Github App id contains invalid characters.') unless app_id =~ /^\d+$/
149
+ raise R10K::Git::GitError, _('Github App token ttl contains invalid characters.') unless ttl =~ /^\d+$/
150
+ raise R10K::Git::GitError, _('Github App key is missing or unreadable') unless File.readable?(private_key)
151
+
152
+ begin
153
+ ssl_key = OpenSSL::PKey::RSA.new(File.read(private_key).strip)
154
+ unless ssl_key.private?
155
+ raise R10K::Git::GitError, _('Github App key is not a valid SSL private key')
156
+ end
157
+ rescue OpenSSL::PKey::RSAError
158
+ raise R10K::Git::GitError, _('Github App key is not a valid SSL key')
159
+ end
160
+
161
+ logger.debug2 _("Using Github App id %{app_id} with SSL key from %{key_path}") % { key_path: private_key, app_id: app_id }
162
+
163
+ jwt_issue_time = Time.now.to_i - 60
164
+ jwt_exp_time = (jwt_issue_time + 60) + ttl.to_i
165
+ payload = { iat: jwt_issue_time, exp: jwt_exp_time, iss: app_id }
166
+ jwt = JWT.encode(payload, ssl_key, "RS256")
167
+
168
+ get = URI.parse("https://api.github.com/app/installations")
169
+ get_request = Net::HTTP::Get.new(get)
170
+ get_request["Authorization"] = "Bearer #{jwt}"
171
+ get_request["Accept"] = "application/vnd.github.v3+json"
172
+ get_req_options = { use_ssl: get.scheme == "https", }
173
+ get_response = Net::HTTP.start(get.hostname, get.port, get_req_options) do |http|
174
+ http.request(get_request)
175
+ end
176
+
177
+ unless (get_response.class < Net::HTTPSuccess)
178
+ logger.debug2 _("Unexpected response code: #{get_response.code}\nResponse body: #{get_response.body}")
179
+ raise R10K::Git::GitError, _("Error using private key to get Github App access token from url")
180
+ end
181
+
182
+ access_tokens_url = JSON.parse(get_response.body)[0]['access_tokens_url']
183
+
184
+ post = URI.parse(access_tokens_url)
185
+ post_request = Net::HTTP::Post.new(post)
186
+ post_request["Authorization"] = "Bearer #{jwt}"
187
+ post_request["Accept"] = "application/vnd.github.v3+json"
188
+ post_req_options = { use_ssl: post.scheme == "https", }
189
+ post_response = Net::HTTP.start(post.hostname, post.port, post_req_options) do |http|
190
+ http.request(post_request)
191
+ end
192
+
193
+ unless (post_response.class < Net::HTTPSuccess)
194
+ logger.debug2 _("Unexpected response code: #{post_response.code}\nResponse body: #{post_response.body}")
195
+ raise R10K::Git::GitError, _("Error using private key to generate access token from #{access_token_url}")
196
+ end
197
+
198
+ token = JSON.parse(post_response.body)['token']
199
+
200
+ raise R10K::Git::GitError, _("Github App token contains invalid characters.") unless valid_token?(token)
201
+
202
+ logger.debug2 _("Github App token generated, expires at: %{expire}") % {expire: JSON.parse(post_response.body)['expires_at']}
203
+ token
204
+ end
128
205
  end
@@ -35,6 +35,7 @@ class R10K::Git::StatefulRepository
35
35
  @cache.resolve(ref)
36
36
  end
37
37
 
38
+ # Returns true if the sync actually updated the repo, false otherwise
38
39
  def sync(ref, force=true)
39
40
  @cache.sync if sync_cache?(ref)
40
41
 
@@ -46,6 +47,7 @@ class R10K::Git::StatefulRepository
46
47
 
47
48
  workdir_status = status(ref)
48
49
 
50
+ updated = true
49
51
  case workdir_status
50
52
  when :absent
51
53
  logger.debug(_("Cloning %{repo_path} and checking out %{ref}") % {repo_path: @repo.path, ref: ref })
@@ -64,15 +66,20 @@ class R10K::Git::StatefulRepository
64
66
  @repo.checkout(sha, {:force => force})
65
67
  else
66
68
  logger.warn(_("Skipping %{repo_path} due to local modifications") % {repo_path: @repo.path})
69
+ updated = false
67
70
  end
68
71
  else
69
72
  logger.debug(_("%{repo_path} is already at Git ref %{ref}") % {repo_path: @repo.path, ref: ref })
73
+ updated = false
70
74
  end
75
+ updated
71
76
  end
72
77
 
73
78
  def status(ref)
74
79
  if !@repo.exist?
75
80
  :absent
81
+ elsif !@cache.exist?
82
+ :mismatched
76
83
  elsif !@repo.git_dir.exist?
77
84
  :mismatched
78
85
  elsif !@repo.git_dir.directory?
@@ -93,6 +100,7 @@ class R10K::Git::StatefulRepository
93
100
  # @api private
94
101
  def sync_cache?(ref)
95
102
  return true if !@cache.exist?
103
+ return true if ref == 'HEAD'
96
104
  return true if !([:commit, :tag].include? @cache.ref_type(ref))
97
105
  return false
98
106
  end
data/lib/r10k/git.rb CHANGED
@@ -135,6 +135,9 @@ module R10K
135
135
 
136
136
  def_setting_attr :private_key
137
137
  def_setting_attr :oauth_token
138
+ def_setting_attr :github_app_id
139
+ def_setting_attr :github_app_key
140
+ def_setting_attr :github_app_ttl
138
141
  def_setting_attr :proxy
139
142
  def_setting_attr :username
140
143
  def_setting_attr :repositories, {}
@@ -56,6 +56,9 @@ module R10K
56
56
  with_setting(:proxy) { |value| R10K::Git.settings[:proxy] = value }
57
57
  with_setting(:repositories) { |value| R10K::Git.settings[:repositories] = value }
58
58
  with_setting(:oauth_token) { |value| R10K::Git.settings[:oauth_token] = value }
59
+ with_setting(:github_app_id) { |value| R10K::Git.settings[:github_app_id] = value }
60
+ with_setting(:github_app_key) { |value| R10K::Git.settings[:github_app_key] = value }
61
+ with_setting(:github_app_ttl) { |value| R10K::Git.settings[:github_app_ttl] = value }
59
62
  end
60
63
  end
61
64
 
@@ -63,6 +66,7 @@ module R10K
63
66
  def call
64
67
  with_setting(:baseurl) { |value| PuppetForge.host = value }
65
68
  with_setting(:proxy) { |value| PuppetForge::Connection.proxy = value }
69
+ with_setting(:authorization_token) { |value| PuppetForge::Connection.authorization = value }
66
70
  end
67
71
  end
68
72
  end
@@ -1,9 +1,12 @@
1
1
  require 'r10k/module'
2
+ require 'r10k/logging'
2
3
  require 'puppet_forge'
3
4
 
4
5
  # This class defines a common interface for module implementations.
5
6
  class R10K::Module::Base
6
7
 
8
+ include R10K::Logging
9
+
7
10
  # @!attribute [r] title
8
11
  # @return [String] The forward slash separated owner and name of the module
9
12
  attr_reader :title
@@ -35,6 +38,10 @@ class R10K::Module::Base
35
38
  # @return [String] Where the module was sourced from. E.g., "Puppetfile"
36
39
  attr_accessor :origin
37
40
 
41
+ # @!attribute [rw] spec_deletable
42
+ # @return [Boolean] set this to true if the spec dir can be safely removed, ie in the moduledir
43
+ attr_accessor :spec_deletable
44
+
38
45
  # There's been some churn over `author` vs `owner` and `full_name` over
39
46
  # `title`, so in the short run it's easier to support both and deprecate one
40
47
  # later.
@@ -43,7 +50,7 @@ class R10K::Module::Base
43
50
 
44
51
  # @param title [String]
45
52
  # @param dirname [String]
46
- # @param args [Array]
53
+ # @param args [Hash]
47
54
  def initialize(title, dirname, args, environment=nil)
48
55
  @title = PuppetForge::V3.normalize_name(title)
49
56
  @dirname = dirname
@@ -52,6 +59,9 @@ class R10K::Module::Base
52
59
  @path = Pathname.new(File.join(@dirname, @name))
53
60
  @environment = environment
54
61
  @overrides = args.delete(:overrides) || {}
62
+ @spec_deletable = true
63
+ @exclude_spec = args.delete(:exclude_spec)
64
+ @exclude_spec = @overrides[:modules].delete(:exclude_spec) if @overrides.dig(:modules, :exclude_spec)
55
65
  @origin = 'external' # Expect Puppetfile or R10k::Environment to set this to a specific value
56
66
 
57
67
  @requested_modules = @overrides.dig(:modules, :requested_modules) || []
@@ -64,8 +74,39 @@ class R10K::Module::Base
64
74
  path.to_s
65
75
  end
66
76
 
77
+ # Delete the spec dir if @exclude_spec has been set to true and @spec_deletable is also true
78
+ def maybe_delete_spec_dir
79
+ if @exclude_spec
80
+ if @spec_deletable
81
+ delete_spec_dir
82
+ else
83
+ logger.info _("Spec dir for #{@title} will not be deleted because it is not in the moduledir")
84
+ end
85
+ end
86
+ end
87
+
88
+ # Actually remove the spec dir
89
+ def delete_spec_dir
90
+ spec_path = @path + 'spec'
91
+ if spec_path.symlink?
92
+ spec_path = spec_path.realpath
93
+ end
94
+ if spec_path.directory?
95
+ logger.debug2 _("Deleting spec data at #{spec_path}")
96
+ # Use the secure flag for the #rm_rf method to avoid security issues
97
+ # involving TOCTTOU(time of check to time of use); more details here:
98
+ # https://ruby-doc.org/stdlib-2.7.0/libdoc/fileutils/rdoc/FileUtils.html#method-c-rm_rf
99
+ # Additionally, #rm_rf also has problems in windows with with symlink targets
100
+ # also being deleted; this should be revisted if Windows becomes higher priority.
101
+ FileUtils.rm_rf(spec_path, secure: true)
102
+ else
103
+ logger.debug2 _("No spec dir detected at #{spec_path}, skipping deletion")
104
+ end
105
+ end
106
+
67
107
  # Synchronize this module with the indicated state.
68
108
  # @param [Hash] opts Deprecated
109
+ # @return [Boolean] true if the module was updated, false otherwise
69
110
  def sync(opts={})
70
111
  raise NotImplementedError
71
112
  end