Skip to content

Commit

Permalink
Add file::with_tmpfile() function
Browse files Browse the repository at this point in the history
!feature

* **Add `file::with_tmpfile()` function**
  Create a temporary file and execute the block with the filename created as an
  argument. The file is deleted after the block execution. This will only
  operate on the machine you run Bolt on.
  • Loading branch information
jay7x committed Mar 30, 2024
1 parent 4b30c39 commit ebaf085
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
39 changes: 39 additions & 0 deletions bolt-modules/file/lib/puppet/functions/file/with_tmpfile.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# frozen_string_literal: true

require 'tempfile'

# Create a temporary file and execute the block with the filename created as an
# argument. The file is deleted after the block execution. This will only
# operate on the machine you run Bolt on.
Puppet::Functions.create_function(:'file::with_tmpfile') do
# @param basename Determines the name of the temporary file (see ruby's Tempfile.new)
# @param tmpdir Directory to place the temporary file in (ruby's Dir.tmpdir is default value)
# @param block The block to execute with a temporary filename
# @example Run a command with a temporary file
# # NOTE: This will work on the Bolt controller node only!
# $res = file::with_tmpfile('foo') |$filename| {
# run_command("do_something_with '${filename}'", 'localhost')
# upload_file($filename, $targets)
# }
dispatch :with_tmpfile do
param 'String', :basename
optional_param 'Optional[String[1]]', :tmpdir
block_param 'Callable[1, 1]', :block
return_type 'Any'
end

def with_tmpfile(basename = '', tmpdir = nil)
# Send Analytics Report
Puppet.lookup(:bolt_executor) {}&.report_function_call(self.class.name)

f = Tempfile.new(basename, tmpdir)
f.close
begin
result = yield f.path
ensure
f.unlink
end

result
end
end
12 changes: 12 additions & 0 deletions bolt-modules/file/spec/functions/file/with_tmpfile_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# frozen_string_literal: true

require 'spec_helper'

describe 'file::with_tmpfile' do
it do
is_expected.to run
.with_params('foo')
.with_lambda { |_| 'bar' }
.and_return('bar')
end
end

0 comments on commit ebaf085

Please sign in to comment.