@@ -12,7 +12,7 @@ class Http < Vanagon::Component::Source::Local
1212 include Vanagon ::Utilities
1313
1414 # Accessors :url, :file, :extension, :workdir, :cleanup are inherited from Local
15- attr_accessor :sum , :sum_type
15+ attr_accessor :sum , :sum_type , :cachedir
1616
1717 # Allowed checksum algorithms to use when validating files
1818 CHECKSUM_TYPES = %w[ md5 sha1 sha256 sha512 ] . freeze
@@ -48,8 +48,9 @@ def valid_url?(target_url)
4848 # sum from
4949 # @param workdir [String] working directory to download into
5050 # @param sum_type [String] type of sum we are verifying
51+ # @param cachedir [String] directory to cache downloaded sources
5152 # @raise [RuntimeError] an exception is raised is sum is nil
52- def initialize ( url , sum :, workdir :, sum_type :, **options )
53+ def initialize ( url , sum :, workdir :, sum_type :, cachedir : nil , **options )
5354 unless sum
5455 fail "sum is required to validate the http source"
5556 end
@@ -63,6 +64,7 @@ def initialize(url, sum:, workdir:, sum_type:, **options)
6364 @url = url
6465 @sum = sum
6566 @workdir = workdir
67+ @cachedir = cachedir ? File . realpath ( cachedir ) : nil
6668 @sum_type = sum_type
6769
6870 if Vanagon ::Component ::Source ::Http . valid_url? ( @sum )
@@ -81,9 +83,14 @@ def initialize(url, sum:, workdir:, sum_type:, **options)
8183 end
8284
8385 # Download the source from the url specified. Sets the full path to the
84- # file as @file and the @extension for the file as a side effect.
86+ # file as @file and the @extension for the file as a side effect. Use
87+ # the cached copy if it exists and is valid.
8588 def fetch
8689 @file = File . basename ( URI . parse ( @url ) . path )
90+ if @cachedir && File . exist? ( File . join ( @cachedir , @file ) )
91+ VanagonLogger . info "Using cached copy of #{ @file } in #{ @cachedir } "
92+ FileUtils . cp ( File . join ( @cachedir , @file ) , workdir )
93+ end
8794 if File . exist? ( File . join ( workdir , file ) )
8895 begin
8996 return if verify
@@ -138,9 +145,13 @@ def download(target_url, target_file = nil, headers = { "Accept-Encoding" => "id
138145 location = URI . parse ( response . header [ 'location' ] )
139146 download ( uri + location , target_file )
140147 when Net ::HTTPSuccess
141- File . open ( File . join ( @workdir , target_file ) , 'w' ) do |io |
148+ dir = @cachedir || @workdir
149+ File . open ( File . join ( dir , target_file ) , 'w' ) do |io |
142150 response . read_body { |chunk | io . write ( chunk ) }
143151 end
152+ if @cachedir
153+ FileUtils . cp ( File . join ( @cachedir , target_file ) , File . join ( @workdir , target_file ) )
154+ end
144155 else
145156 fail "Error: #{ response . code . to_s } . Unable to get source from #{ target_url } "
146157 end
0 commit comments