Passed
Push — master ( 5bdb67...7f2dc2 )
by Paul
01:36
created

FileFetcher   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 61
ccs 34
cts 34
cp 1
rs 10
c 0
b 0
f 0
wmc 15

8 Methods

Rating   Name   Duplication   Size   Complexity  
A write_file() 0 5 1
A fetch() 0 5 2
A remote_file_path() 0 4 2
A local_file() 0 3 2
A remote_file() 0 9 2
A tmpfile() 0 4 2
A tmpfile_path() 0 3 1
A fetch_file() 0 5 1
1 1
require "open-uri"
2 1
require "socket"
3 1
require "tmpdir"
4 1
require "pathname"
5 1
require_relative "exceptions"
6 1
require_relative "file_system"
7
8 1
module Resume
9 1
  module CLI
10 1
    module FileFetcher
11 1
      REMOTE_REPO =
12
        "https://raw.githubusercontent.com/paulfioravanti/resume/master".freeze
13 1
      private_constant :REMOTE_REPO
14
15 1
      module_function
16
17 1
      def fetch(path, filename: "")
18 54
        pathname = Pathname.new(path)
19 54
        filename = pathname.basename.to_path if filename.empty?
20 54
        fetch_file(pathname, filename)
21
      end
22
23 1
      def fetch_file(pathname, filename)
24
        local_file(pathname) ||
25 54
          tmpfile(filename) ||
26
          remote_file(pathname, filename)
27
      end
28 1
      private_class_method :fetch_file
29
30 1
      def local_file(pathname)
31 54
        File.open(pathname) if pathname.file?
32
      end
33 1
      private_class_method :local_file
34
35 1
      def tmpfile(filename)
36 34
        tmpfile = tmpfile_path(filename)
37 34
        File.open(tmpfile) if tmpfile.file?
38
      end
39 1
      private_class_method :tmpfile
40
41 1
      def remote_file(pathname, filename)
42 7
        tmpfile = tmpfile_path(filename)
43 7
        File.open(tmpfile, "wb") do |file|
44 7
          write_file(file, pathname)
45
        end
46 4
        tmpfile
47
      rescue SocketError, OpenURI::HTTPError, Errno::ECONNREFUSED
48 3
        raise NetworkConnectionError
49
      end
50 1
      private_class_method :remote_file
51
52 1
      def tmpfile_path(filename)
53 41
        FileSystem.tmpfile_path(filename)
54
      end
55 1
      private_class_method :tmpfile_path
56
57 1
      def write_file(file, pathname)
58 7
        Kernel.open(remote_file_path(pathname)) do |uri|
59 1
          file.write(uri.read)
60
        end
61
      end
62 1
      private_class_method :write_file
63
64 1
      def remote_file_path(pathname)
65 7
        path = pathname.to_path
66 7
        uri?(pathname) ? path : File.join(REMOTE_REPO, path)
67
      end
68 1
      private_class_method :remote_file_path
69
70 1
      def uri?(pathname)
71 7
        uri = URI.parse(pathname.to_path)
72 5
        %w(http https).include?(uri.scheme)
73
      rescue URI::BadURIError, URI::InvalidURIError
74 2
        false
75
      end
76 1
      private_class_method :uri?
77
    end
78
  end
79
end
80