Class: URI::FILE

Inherits:
Generic show all
Defined in:
lib/buildr/core/transports.rb

Overview

File URL. Keep in mind that file URLs take the form of file://host/path, although the host is not used, so typically all you will see are three backslashes. This methods accept common variants, like file:/path but always returns a valid URL.

Constant Summary collapse

COMPONENT =
[ :host, :path ].freeze

Instance Method Summary collapse

Methods inherited from Generic

#download, #upload, #write

Constructor Details

#initialize(*args) ⇒ FILE

Returns a new instance of FILE.



486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# File 'lib/buildr/core/transports.rb', line 486

def initialize(*args)
  super
  # file:something (opaque) becomes file:///something
  if path.nil?
    set_path "/#{opaque}"
    unless opaque.nil?
      set_opaque nil
      warn "#{caller[2]}: We'll accept this URL, but just so you know, it needs three slashes, as in: #{to_s}"
    end
  end
  # Sadly, file://something really means file://something/ (something being server)
  set_path '/' if path.empty?

  # On windows, file://c:/something is not a valid URL, but people do it anyway, so if we see a drive-as-host,
  # we'll just be nice enough to fix it. (URI actually strips the colon here)
  if host =~ /^[a-zA-Z]$/
    set_path "/#{host}:#{path}"
    set_host nil
  end
end

Instance Method Details

#read(options = nil, &block) ⇒ Object

See URI::Generic#read

Raises:

  • (ArgumentError)


508
509
510
511
512
513
514
515
516
517
518
519
520
521
# File 'lib/buildr/core/transports.rb', line 508

def read(options = nil, &block)
  options ||= {}
  raise ArgumentError, 'Either you\'re attempting to read a file from another host (which we don\'t support), or you used two slashes by mistake, where you should have file:///<path>.' if host

  path = real_path
  # TODO: complain about clunky URLs
  raise NotFoundError, "Looking for #{self} and can't find it." unless File.exists?(path)
  raise NotFoundError, "Looking for the file #{self}, and it happens to be a directory." if File.directory?(path)
  File.open path, 'rb' do |input|
    with_progress_bar options[:progress], path.split('/').last, input.stat.size do |progress|
      block ? block.call(input.read) : input.read
    end
  end
end

#real_pathObject

The URL path always starts with a backslash. On most operating systems (Linux, Darwin, BSD) it points to the absolute path on the file system. But on Windows, it comes before the drive letter, creating an unusable path, so real_path fixes that. Ugly but necessary hack.



530
531
532
# File 'lib/buildr/core/transports.rb', line 530

def real_path #:nodoc:
  RUBY_PLATFORM =~ /win32/ && path =~ /^\/[a-zA-Z]:\// ? path[1..-1] : path
end

#to_sObject



523
524
525
# File 'lib/buildr/core/transports.rb', line 523

def to_s
  "file://#{host}#{path}"
end