@@ -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
@@ -49,7 +49,7 @@ def valid_url?(target_url)
4949 # @param workdir [String] working directory to download into
5050 # @param sum_type [String] type of sum we are verifying
5151 # @raise [RuntimeError] an exception is raised is sum is nil
52- def initialize ( url , sum :, workdir :, sum_type :, **options )
52+ def initialize ( url , sum :, workdir :, sum_type :, cachedir : nil , **options )
5353 unless sum
5454 fail "sum is required to validate the http source"
5555 end
@@ -63,6 +63,7 @@ def initialize(url, sum:, workdir:, sum_type:, **options)
6363 @url = url
6464 @sum = sum
6565 @workdir = workdir
66+ @cachedir = cachedir ? File . realpath ( cachedir ) : nil
6667 @sum_type = sum_type
6768
6869 if Vanagon ::Component ::Source ::Http . valid_url? ( @sum )
@@ -84,6 +85,10 @@ def initialize(url, sum:, workdir:, sum_type:, **options)
8485 # file as @file and the @extension for the file as a side effect.
8586 def fetch
8687 @file = File . basename ( URI . parse ( @url ) . path )
88+ if @cachedir && File . exist? ( File . join ( @cachedir , @file ) )
89+ VanagonLogger . info "Using cached copy of #{ @file } in #{ @cachedir } "
90+ FileUtils . cp ( File . join ( @cachedir , @file ) , workdir )
91+ end
8792 if File . exist? ( File . join ( workdir , file ) )
8893 begin
8994 return if verify
@@ -138,9 +143,13 @@ def download(target_url, target_file = nil, headers = { "Accept-Encoding" => "id
138143 location = URI . parse ( response . header [ 'location' ] )
139144 download ( uri + location , target_file )
140145 when Net ::HTTPSuccess
141- File . open ( File . join ( @workdir , target_file ) , 'w' ) do |io |
146+ dir = @cachedir || @workdir
147+ File . open ( File . join ( dir , target_file ) , 'w' ) do |io |
142148 response . read_body { |chunk | io . write ( chunk ) }
143149 end
150+ if @cachedir
151+ FileUtils . cp ( File . join ( @cachedir , target_file ) , File . join ( @workdir , target_file ) )
152+ end
144153 else
145154 fail "Error: #{ response . code . to_s } . Unable to get source from #{ target_url } "
146155 end
0 commit comments