Added a progress meter module/mixin since that'll be used elsewhere.

This commit is contained in:
Mitchell Hashimoto 2010-04-08 12:44:25 -07:00
parent 745aadd1a5
commit 00cf000189
3 changed files with 33 additions and 16 deletions

View File

@ -8,7 +8,7 @@ PROJECT_ROOT = File.join(libdir, '..') unless defined?(PROJECT_ROOT)
end
# The vagrant specific files which must be loaded prior to the rest
%w{vagrant/util vagrant/util/stacked_proc_runner vagrant/actions/base vagrant/downloaders/base vagrant/actions/collection
%w{vagrant/util vagrant/util/stacked_proc_runner vagrant/util/progress_meter vagrant/actions/base vagrant/downloaders/base vagrant/actions/collection
vagrant/actions/runner vagrant/config vagrant/provisioners/base vagrant/provisioners/chef}.each do |f|
require File.expand_path(f, libdir)
end

View File

@ -3,8 +3,7 @@ module Vagrant
# Downloads a file from an HTTP URL to a temporary file. This
# downloader reports its progress to stdout while downloading.
class HTTP < Base
# ANSI escape code to clear lines from cursor to end of line
CL_RESET = "\r\e[0K"
include Util::ProgressMeter
def self.match?(uri)
# URI.parse barfs on '<drive letter>:\\files \on\ windows'
@ -12,7 +11,7 @@ module Vagrant
extracted = URI.extract(uri).first
extracted && extracted.include?(uri)
end
def download!(source_url, destination_file)
Net::HTTP.get_response(URI.parse(source_url)) do |response|
total = response.content_length
@ -27,7 +26,7 @@ module Vagrant
# Progress reporting is limited to every 25 segments just so
# we're not constantly updating
if segment_count % 25 == 0
report_progress(progress, total)
update_progress(progress, total)
segment_count = 0
end
@ -38,17 +37,6 @@ module Vagrant
complete_progress
end
def report_progress(progress, total)
percent = (progress.to_f / total.to_f) * 100
print "#{CL_RESET}Download Progress: #{percent.to_i}% (#{progress} / #{total})"
$stdout.flush
end
def complete_progress
# Just clear the line back out
print "#{CL_RESET}"
end
end
end
end

View File

@ -0,0 +1,29 @@
module Vagrant
module Util
# A mixin which allows any class to be able to show a "progress meter"
# to standard out. The progress meter shows the progress of an operation
# with console-animated text in stdout.
module ProgressMeter
# ANSI escape code to clear lines from cursor to end of line
CL_RESET = "\r\e[0K"
# Updates the progress meter with the given progress amount and total.
# This method will do the math to figure out a percentage and show it
# within stdout.
#
# @param [Float] progress Progress
# @param [Float] total Total
def update_progress(progress, total)
percent = (progress.to_f / total.to_f) * 100
print "#{CL_RESET}Progress: #{percent.to_i}% (#{progress} / #{total})"
$stdout.flush
end
# Completes the progress meter by resetting it off of the screen.
def complete_progress
# Just clear the line back out
print "#{CL_RESET}"
end
end
end
end