From 3a27c2957712788120122209f19787e031bf55e3 Mon Sep 17 00:00:00 2001 From: Seth Vargo Date: Sat, 28 May 2016 23:00:24 -0400 Subject: [PATCH] Add a new util for generating tempfiles --- lib/vagrant/util.rb | 1 + lib/vagrant/util/tempfile.rb | 58 ++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 lib/vagrant/util/tempfile.rb diff --git a/lib/vagrant/util.rb b/lib/vagrant/util.rb index 896b5d7e0..f3017dea4 100644 --- a/lib/vagrant/util.rb +++ b/lib/vagrant/util.rb @@ -9,6 +9,7 @@ module Vagrant autoload :SafeExec, 'vagrant/util/safe_exec' autoload :StackedProcRunner, 'vagrant/util/stacked_proc_runner' autoload :TemplateRenderer, 'vagrant/util/template_renderer' + autoload :Tempfile, 'vagrant/util/tempfile' autoload :Subprocess, 'vagrant/util/subprocess' end end diff --git a/lib/vagrant/util/tempfile.rb b/lib/vagrant/util/tempfile.rb new file mode 100644 index 000000000..66006b788 --- /dev/null +++ b/lib/vagrant/util/tempfile.rb @@ -0,0 +1,58 @@ +require "tempfile" + +module Vagrant + module Util + class Tempfile + # Utility function for creating a temporary file that will persist for + # the duration of the block and then be removed after the block finishes. + # + # @example + # + # Tempfile.create("arch-configure-networks") do |f| + # f.write("network-1") + # f.fsync + # f.close + # do_something_with_file(f.path) + # end + # + # @example + # + # Tempfile.create(["runner", "ps1"]) do |f| + # # f will have a suffix of ".ps1" + # # ... + # end + # + # @param [String, Array] name the prefix of the tempfile to create + # @param [Hash] options a list of options + # @param [Proc] block the block to yield the file object to + # + # @yield [File] + def self.create(name, options = {}) + raise "No block given!" if !block_given? + + options = { + binmode: true + }.merge(options) + + # The user can specify an array where the first parameter is the prefix + # and the last parameter is the file suffix. We want to prefix the + # "prefix" with `vagrant-`, and this does that + if name.is_a?(Array) + basename = ["vagrant-#{name[0]}", name[1]] + else + basename = "vagrant-#{name}" + end + + Dir::Tmpname.create(basename) do |path| + begin + f = File.open(path, "w+") + f.binmode if options[:binmode] + yield f + ensure + File.unlink(f.path) if File.file?(f.path) + end + end + end + end + end +end