hoper 0.1.1 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 21c130462071b466211216bdb60b5770d929a0e5cb6f5b0d939e3186d3aaeb42
4
- data.tar.gz: 574da3e79b985a54fc21768571b7a1d84cadcbcf9c0aacf418a2cc3169b47143
3
+ metadata.gz: 8e6f3743b6dc72bb43f8f8581dabfe05d41fab094d0fd548196d22515368859a
4
+ data.tar.gz: 1bf041f7cbf8f5e14c928d3c85b59d748488469db8fa602a475d40bea054ab56
5
5
  SHA512:
6
- metadata.gz: 43a926307cf5840be2b3e7af833e2ca0024269a8d7252b56081777ad9c50275b8c4854cbb05ebb74e8b200425d407cd36ad94fdeddae32efcc141fc147f9be5a
7
- data.tar.gz: e62eb19ad1e0bd2c76a5f6ecd52f4859d9bb665ff4fa2420f7582b46f76daa221a8fa7019e5f506cedfaaace00916f0b31b6b210d740c738f5304dedce9eb981
6
+ metadata.gz: d6f063d86bc46f111bad3cbcf8fc8c1389d5c307ab43c1a06643d7f0e9953ab0635bf34e9eae2630755711251ea8f26c61d29f886a2807816e7c33de456272b3
7
+ data.tar.gz: ddbeaa08d3dc1fbf8f69915a5a54e250a9cd18472dc4fc3bd3746b43bc5c7f370d223ca2cd037db5069b87fc7d50066fa73b92b8d62caf67b1e26ccf4c7d2386
data/CHANGELOG.md ADDED
@@ -0,0 +1,34 @@
1
+ # Changelog
2
+
3
+ ## 1.0.1
4
+
5
+ ### Fixed
6
+ - Clear guidance for the `certificate verify failed (unable to get certificate CRL)` error,
7
+ caused by an outdated `openssl` Ruby gem running against OpenSSL 3.6+ (common on macOS
8
+ with Homebrew). Hoper now suggests `gem update openssl` instead of `--insecure`.
9
+
10
+ ## 1.0.0
11
+
12
+ Complete modernization.
13
+
14
+ ### Breaking
15
+ - Requires Ruby >= 3.1.
16
+ - Dropped the `curb` (libcurl) dependency: Hoper now uses only the Ruby standard library and
17
+ installs on Windows, macOS and Linux without compilers or native libraries.
18
+ - New output format (one line per hop with status code and timing).
19
+
20
+ ### Added
21
+ - Options: `--max-hops`, `--timeout`, `--method`, `--user-agent`, `--header`, `--insecure`,
22
+ `--json`, `--[no-]color`, `--version`, `--help`.
23
+ - Multiple URLs per invocation.
24
+ - Redirect loop detection, relative `Location` handling, `HEAD` → `GET` fallback.
25
+ - Exit codes (0 ok, 1 failure, 2 usage).
26
+ - `Hoper.trace` library API.
27
+ - Test suite and GitHub Actions CI on Linux, macOS and Windows.
28
+
29
+ ### Fixed
30
+ - Executable shebang (`#!/usr/bin/env ruby -wU`) failed on Linux.
31
+ - Errors were swallowed and always reported as "Bad URL".
32
+
33
+ ## 0.1.1
34
+ - Previous release based on `curb`.
data/README.md CHANGED
@@ -1,33 +1,125 @@
1
1
  # Hoper
2
2
 
3
3
  [![Gem Version](https://badge.fury.io/rb/hoper.svg)](https://badge.fury.io/rb/hoper)
4
+ [![CI](https://github.com/gabamnml/hoper/actions/workflows/ci.yml/badge.svg)](https://github.com/gabamnml/hoper/actions/workflows/ci.yml)
4
5
 
5
- It shows all the hops that makes a url you specify to reach its endpoint.
6
- For example if you want to see the entire trip by email URL or like a URL shorten. Hoper returns you all URLs redirections.
6
+ Hoper shows every hop (redirect) a URL goes through until it reaches its final destination —
7
+ useful for URL shorteners, tracking links in emails, SSO flows, or debugging redirect rules.
7
8
 
8
- ![hoper demo](http://i.imgur.com/EYDvYm2.gif)
9
+ ```
10
+ $ hoper http://github.com
11
+ Tracing http://github.com
12
+ 1. → 301 Moved Permanently http://github.com/ 81ms
13
+ 2. ✔ 200 OK https://github.com/ 50ms
14
+ 1 redirect → https://github.com/
15
+ ```
16
+
17
+ ## Features
18
+
19
+ - **Works on Linux, macOS and Windows** — pure Ruby, no native extensions or libcurl required.
20
+ - Status code, reason and response time for every hop.
21
+ - Redirect loop detection and a configurable hop limit.
22
+ - Uses `HEAD` by default (no body downloads) with automatic fallback to `GET` for servers that reject it.
23
+ - JSON output for scripts and pipelines; meaningful exit codes.
24
+ - Honours `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` and [`NO_COLOR`](https://no-color.org).
9
25
 
10
26
  ## Installation
11
27
 
12
- $ gem install hoper
28
+ Requires Ruby 3.1 or newer.
13
29
 
14
- ## Usage
30
+ ```bash
31
+ gem install hoper
32
+ ```
15
33
 
16
- Type in your command line:
34
+ On Windows, install Ruby with [RubyInstaller](https://rubyinstaller.org/) and then run the same command.
17
35
 
18
- $ hoper [url]
36
+ ## Usage
37
+
38
+ ```
39
+ hoper [options] URL [URL...]
40
+
41
+ -m, --max-hops N Maximum redirects to follow (default: 20)
42
+ -t, --timeout SECONDS Timeout per request (default: 10)
43
+ -X, --method METHOD HTTP method: HEAD or GET (default: HEAD)
44
+ -A, --user-agent UA User-Agent header to send
45
+ -H, --header 'NAME: VALUE' Extra request header (repeatable)
46
+ -k, --insecure Do not verify TLS certificates
47
+ -j, --json Output results as JSON
48
+ --[no-]color Force/disable colored output
49
+ -v, --version Print version and exit
50
+ -h, --help Show this help
51
+ ```
52
+
53
+ If the scheme is omitted, `https://` is assumed (`hoper example.com`).
54
+
55
+ ### JSON output
56
+
57
+ ```bash
58
+ hoper --json http://github.com
59
+ ```
60
+
61
+ ```json
62
+ {
63
+ "start_url": "http://github.com/",
64
+ "final_url": "https://github.com/",
65
+ "final_status": 200,
66
+ "redirects": 1,
67
+ "hops": [
68
+ { "url": "http://github.com/", "status": 301, "reason": "Moved Permanently", "location": "https://github.com/", "duration_ms": 81 },
69
+ { "url": "https://github.com/", "status": 200, "reason": "OK", "duration_ms": 50 }
70
+ ]
71
+ }
72
+ ```
73
+
74
+ With several URLs the output is an array.
75
+
76
+ ### Exit codes
77
+
78
+ | Code | Meaning |
79
+ |------|---------|
80
+ | 0 | Every URL resolved to a non-error (< 400) final response |
81
+ | 1 | At least one URL failed (network error, loop, too many hops, 4xx/5xx) |
82
+ | 2 | Invalid usage / options |
83
+
84
+ ### As a library
85
+
86
+ ```ruby
87
+ require "hoper"
88
+
89
+ result = Hoper.trace("https://bit.ly/example", max_hops: 10)
90
+ result.hops.each { |hop| puts "#{hop.status} #{hop.url}" }
91
+ result.final_url # => "https://example.com/"
92
+ result.success? # => true
93
+ ```
19
94
 
20
95
  ## Development
21
96
 
22
- After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
97
+ ```bash
98
+ bundle install
99
+ bundle exec rake test
100
+ ```
101
+
102
+ CI runs the test suite on Ubuntu, macOS and Windows (Ruby 4.0), plus the oldest supported Ruby (3.1) on Ubuntu. Tests use a local
103
+ in-process HTTP server, so they don't need network access.
23
104
 
24
- To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
105
+ ### Releasing
106
+
107
+ Releases are automated with GitHub Actions and RubyGems Trusted Publishing:
108
+
109
+ 1. Bump `lib/hoper/version.rb` and add a section to `CHANGELOG.md`; merge to `master`.
110
+ 2. Tag and push:
111
+
112
+ ```bash
113
+ git tag v1.2.3 && git push origin v1.2.3
114
+ ```
115
+
116
+ The `Release` workflow checks the tag matches the version, runs the tests, publishes the gem
117
+ to RubyGems.org and creates a GitHub Release with the CHANGELOG notes.
25
118
 
26
119
  ## Contributing
27
120
 
28
121
  Bug reports and pull requests are welcome on GitHub at https://github.com/gabamnml/hoper. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
29
122
 
30
-
31
123
  ## License
32
124
 
33
125
  The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
data/exe/hoper CHANGED
@@ -1,59 +1,9 @@
1
- #!/usr/bin/env ruby -wU
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
2
3
 
3
- require 'hoper'
4
- require "curl"
5
- require 'uri'
4
+ lib = File.expand_path("../lib", __dir__)
5
+ $LOAD_PATH.unshift(lib) if File.directory?(lib) && !$LOAD_PATH.include?(lib)
6
6
 
7
- url = ARGV[0]
7
+ require "hoper/cli"
8
8
 
9
- if url.nil? || url.empty?
10
- print "\n"
11
- puts "Hoper #{Hoper::VERSION}"
12
- print "\n"
13
- puts "Usage: hoper [url] "
14
- print "\n"
15
- puts "EXAMPLE: \n hoper http://mail.google.com "
16
-
17
- else
18
- print "\n"
19
- puts "Starting Hoper #{Hoper::VERSION} at #{Time.now.strftime("%d-%m-%Y %H:%M")}"
20
-
21
-
22
- begin
23
- @jumps = 0
24
- c = Curl::Easy.new(url) do|curl|
25
- curl.follow_location = true
26
- curl.on_missing {|easy|
27
- print "\n"
28
- puts "The URL does not respond well. Probably return 400 error :("
29
-
30
- }
31
- curl.on_failure {|easy|
32
- print "\n"
33
- puts "The URL does not respond well. Probably return 500 error :("
34
-
35
- }
36
- curl.on_success {|easy|
37
- print "\n"
38
- puts "Total of #{@jumps.to_s} Hops in this session"
39
-
40
- }
41
- curl.on_complete {|easy|
42
- fancy_headers = easy.header_str.split(/[\r\n]+/).map(&:strip)
43
- fancy_headers.each do |fancy_header|
44
- if fancy_header.include?("Location")
45
- @jumps = @jumps.next
46
- print "\n"
47
- puts fancy_header.gsub! 'Location', 'Hop'
48
- end
49
- end
50
- }
51
-
52
- end
53
-
54
- c.perform
55
- rescue
56
- print "\n"
57
- puts "Bad URL, please fix your typo and try again :)"
58
- end
59
- end
9
+ exit Hoper::CLI.start(ARGV)
data/lib/hoper/cli.rb ADDED
@@ -0,0 +1,164 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "optparse"
5
+ require_relative "../hoper"
6
+
7
+ module Hoper
8
+ # Command line interface: `hoper [options] URL...`
9
+ class CLI
10
+ EXIT_OK = 0
11
+ EXIT_FAILURE = 1
12
+ EXIT_USAGE = 2
13
+
14
+ COLORS = { red: 31, green: 32, yellow: 33, blue: 34, cyan: 36, gray: 90, bold: 1 }.freeze
15
+
16
+ def self.start(argv = ARGV, out: $stdout, err: $stderr)
17
+ new(out: out, err: err).run(argv)
18
+ end
19
+
20
+ def initialize(out: $stdout, err: $stderr)
21
+ @out = out
22
+ @err = err
23
+ @options = {
24
+ format: :text,
25
+ color: color_supported?(out),
26
+ tracer: {}
27
+ }
28
+ end
29
+
30
+ def run(argv)
31
+ catch(:done) { execute(argv) }
32
+ end
33
+
34
+ private
35
+
36
+ def execute(argv)
37
+ urls = parser.parse(argv.dup)
38
+ if urls.empty?
39
+ @err.puts parser.help
40
+ return EXIT_USAGE
41
+ end
42
+
43
+ tracer = Tracer.new(**@options[:tracer])
44
+ results = urls.map { |url| @options[:format] == :json ? tracer.trace(url) : trace_text(tracer, url) }
45
+ print_json(results) if @options[:format] == :json
46
+ results.all?(&:success?) ? EXIT_OK : EXIT_FAILURE
47
+ rescue OptionParser::ParseError, ArgumentError => e
48
+ @err.puts "hoper: #{e.message}"
49
+ @err.puts "Try 'hoper --help' for more information."
50
+ EXIT_USAGE
51
+ rescue Interrupt
52
+ @err.puts
53
+ 130
54
+ end
55
+
56
+ def parser
57
+ @parser ||= OptionParser.new do |o|
58
+ o.banner = "Usage: hoper [options] URL [URL...]"
59
+ o.separator ""
60
+ o.separator "Show every redirect (hop) a URL goes through until its final destination."
61
+ o.separator ""
62
+ o.separator "Options:"
63
+ o.on("-m", "--max-hops N", Integer, "Maximum redirects to follow (default: #{Tracer::DEFAULT_MAX_HOPS})") do |n|
64
+ @options[:tracer][:max_hops] = n
65
+ end
66
+ o.on("-t", "--timeout SECONDS", Float, "Timeout per request (default: #{Tracer::DEFAULT_TIMEOUT})") do |t|
67
+ @options[:tracer][:timeout] = t
68
+ end
69
+ o.on("-X", "--method METHOD", Tracer::SUPPORTED_METHODS, "HTTP method: HEAD or GET (default: HEAD)") do |m|
70
+ @options[:tracer][:method] = m
71
+ end
72
+ o.on("-A", "--user-agent UA", "User-Agent header to send") { |ua| @options[:tracer][:user_agent] = ua }
73
+ o.on("-H", "--header 'NAME: VALUE'", "Extra request header (repeatable)") do |h|
74
+ name, value = h.split(":", 2).map(&:strip)
75
+ raise OptionParser::InvalidArgument, h if name.to_s.empty? || value.nil?
76
+
77
+ (@options[:tracer][:headers] ||= {})[name] = value
78
+ end
79
+ o.on("-k", "--insecure", "Do not verify TLS certificates") { @options[:tracer][:verify_ssl] = false }
80
+ o.on("-j", "--json", "Output results as JSON") { @options[:format] = :json }
81
+ o.on("--[no-]color", "Force/disable colored output") { |c| @options[:color] = c }
82
+ o.on("-v", "--version", "Print version and exit") do
83
+ @out.puts "hoper #{VERSION}"
84
+ throw :done, EXIT_OK
85
+ end
86
+ o.on("-h", "--help", "Show this help") do
87
+ @out.puts o.help
88
+ throw :done, EXIT_OK
89
+ end
90
+ o.separator ""
91
+ o.separator "Examples:"
92
+ o.separator " hoper https://bit.ly/3abcd"
93
+ o.separator " hoper -X GET --json example.com"
94
+ o.separator ""
95
+ o.separator "Proxies are read from HTTP_PROXY / HTTPS_PROXY / NO_PROXY."
96
+ end
97
+ end
98
+
99
+ def trace_text(tracer, url)
100
+ @out.puts paint("Tracing #{url}", :bold)
101
+ index = 0
102
+ result = tracer.trace(url) do |hop|
103
+ index += 1
104
+ @out.puts format_hop(index, hop)
105
+ end
106
+ @out.puts summary(result)
107
+ @out.puts
108
+ result
109
+ end
110
+
111
+ def format_hop(index, hop)
112
+ status = paint("#{hop.status} #{hop.reason}".strip, status_color(hop.status))
113
+ time = paint("#{hop.duration_ms}ms", :gray)
114
+ marker = hop.redirect? ? paint(symbol(:arrow), :cyan) : paint(symbol(:check), status_color(hop.status))
115
+ " #{index.to_s.rjust(2)}. #{marker} #{status} #{hop.url} #{time}"
116
+ end
117
+
118
+ def summary(result)
119
+ if result.error
120
+ " #{paint("#{symbol(:cross)} #{result.error}", :red)}"
121
+ else
122
+ hops = result.redirect_count
123
+ word = hops == 1 ? "redirect" : "redirects"
124
+ " #{paint("#{hops} #{word}", :bold)} #{symbol(:arrow)} #{paint(result.final_url, status_color(result.final_status))}"
125
+ end
126
+ end
127
+
128
+ # Legacy Windows consoles (non UTF-8 code pages) can't show these glyphs.
129
+ def symbol(name)
130
+ unicode = { arrow: "→", check: "✔", cross: "✖" }
131
+ ascii = { arrow: "->", check: "OK", cross: "x" }
132
+ encoding = @out.respond_to?(:external_encoding) && @out.external_encoding || Encoding.default_external
133
+ (encoding == Encoding::UTF_8 ? unicode : ascii).fetch(name)
134
+ end
135
+
136
+ def print_json(results)
137
+ data = results.map(&:to_h)
138
+ @out.puts JSON.pretty_generate(data.size == 1 ? data.first : data)
139
+ end
140
+
141
+ def status_color(status)
142
+ case status
143
+ when 200..299 then :green
144
+ when 300..399 then :yellow
145
+ else :red
146
+ end
147
+ end
148
+
149
+ def paint(text, color)
150
+ return text unless @options[:color]
151
+
152
+ "\e[#{COLORS.fetch(color)}m#{text}\e[0m"
153
+ end
154
+
155
+ # Respects https://no-color.org and only colors real terminals.
156
+ # Windows 10+ terminals understand ANSI escape codes.
157
+ def color_supported?(io)
158
+ return false if ENV.key?("NO_COLOR")
159
+ return true if ENV.key?("FORCE_COLOR")
160
+
161
+ io.respond_to?(:tty?) && io.tty? && ENV["TERM"] != "dumb"
162
+ end
163
+ end
164
+ end
data/lib/hoper/hop.rb ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Hoper
4
+ # A single request/response in the redirect chain.
5
+ Hop = Struct.new(:url, :status, :reason, :location, :duration_ms, keyword_init: true) do
6
+ def redirect?
7
+ !location.nil? && status.between?(300, 399)
8
+ end
9
+
10
+ def to_h
11
+ super.compact
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Hoper
4
+ # Outcome of tracing a URL: the list of hops plus an optional error.
5
+ Result = Struct.new(:start_url, :hops, :error, keyword_init: true) do
6
+ def final_url
7
+ hops.last&.url
8
+ end
9
+
10
+ def final_status
11
+ hops.last&.status
12
+ end
13
+
14
+ # Number of redirects followed (the final response is not a hop).
15
+ def redirect_count
16
+ hops.count(&:redirect?)
17
+ end
18
+
19
+ def success?
20
+ error.nil? && !final_status.nil? && final_status < 400
21
+ end
22
+
23
+ def to_h
24
+ {
25
+ start_url: start_url,
26
+ final_url: final_url,
27
+ final_status: final_status,
28
+ redirects: redirect_count,
29
+ hops: hops.map(&:to_h),
30
+ error: error
31
+ }.compact
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,175 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "openssl"
5
+ require "uri"
6
+
7
+ module Hoper
8
+ # Follows HTTP redirects one by one using only the Ruby standard library,
9
+ # so it works the same on Linux, macOS and Windows without native
10
+ # extensions. Proxies from HTTP_PROXY / HTTPS_PROXY / NO_PROXY are honoured.
11
+ class Tracer
12
+ DEFAULT_MAX_HOPS = 20
13
+ DEFAULT_TIMEOUT = 10
14
+ DEFAULT_USER_AGENT = "hoper/#{VERSION} (+https://github.com/gabamnml/hoper)".freeze
15
+ SUPPORTED_METHODS = %w[HEAD GET].freeze
16
+ # Servers that reject HEAD usually answer with one of these.
17
+ HEAD_FALLBACK_STATUSES = [400, 403, 404, 405, 501].freeze
18
+
19
+ attr_reader :max_hops, :timeout, :http_method, :user_agent, :verify_ssl, :headers
20
+
21
+ def initialize(max_hops: DEFAULT_MAX_HOPS, timeout: DEFAULT_TIMEOUT, method: "HEAD",
22
+ user_agent: DEFAULT_USER_AGENT, verify_ssl: true, headers: {})
23
+ @max_hops = Integer(max_hops)
24
+ @timeout = Float(timeout)
25
+ @http_method = method.to_s.upcase
26
+ @user_agent = user_agent
27
+ @verify_ssl = verify_ssl
28
+ @headers = headers
29
+
30
+ raise ArgumentError, "max_hops must be >= 1" if @max_hops < 1
31
+ raise ArgumentError, "timeout must be > 0" unless @timeout.positive?
32
+ return if SUPPORTED_METHODS.include?(@http_method)
33
+
34
+ raise ArgumentError, "method must be one of #{SUPPORTED_METHODS.join(', ')}"
35
+ end
36
+
37
+ # Traces +url+ and yields each Hop as soon as it is known (if a block is
38
+ # given). Always returns a Result; network failures are reported in
39
+ # Result#error instead of being raised.
40
+ def trace(url)
41
+ uri = self.class.normalize(url)
42
+ result = Result.new(start_url: uri.to_s, hops: [])
43
+ seen = {}
44
+
45
+ loop do
46
+ if seen[uri.to_s]
47
+ result.error = "Redirect loop detected at #{uri}"
48
+ break
49
+ end
50
+ seen[uri.to_s] = true
51
+
52
+ hop = request(uri)
53
+ result.hops << hop
54
+ yield hop if block_given?
55
+
56
+ break unless hop.redirect?
57
+
58
+ if result.redirect_count >= max_hops
59
+ result.error = "Too many redirects (limit is #{max_hops})"
60
+ break
61
+ end
62
+
63
+ uri = resolve_location(uri, hop.location)
64
+ end
65
+
66
+ result
67
+ rescue InvalidURLError => e
68
+ Result.new(start_url: url.to_s, hops: [], error: e.message)
69
+ rescue StandardError => e
70
+ result ||= Result.new(start_url: url.to_s, hops: [])
71
+ result.error = describe_error(e, uri)
72
+ result
73
+ end
74
+
75
+ # Turns user input into an absolute http(s) URI. A missing scheme
76
+ # defaults to https.
77
+ def self.normalize(url)
78
+ input = url.to_s.strip
79
+ raise InvalidURLError, "URL is empty" if input.empty?
80
+
81
+ input = "https://#{input}" unless input.match?(%r{\A[a-z][a-z0-9+.-]*://}i)
82
+ uri = URI.parse(input)
83
+ unless uri.is_a?(URI::HTTP) && uri.host && !uri.host.empty?
84
+ raise InvalidURLError, "Not a valid http(s) URL: #{url}"
85
+ end
86
+
87
+ uri.path = "/" if uri.path.nil? || uri.path.empty?
88
+ uri
89
+ rescue URI::InvalidURIError
90
+ raise InvalidURLError, "Not a valid http(s) URL: #{url}"
91
+ end
92
+
93
+ # Known bug: the system OpenSSL 3.6+ combined with an outdated `openssl`
94
+ # Ruby gem fails every verification with "unable to get certificate CRL"
95
+ # even for valid certificates. Updating the gem fixes it.
96
+ def self.tls_hint(message)
97
+ if message.include?("unable to get certificate CRL")
98
+ "\n Your Ruby 'openssl' gem (#{OpenSSL::VERSION}) is incompatible with " \
99
+ "#{OpenSSL::OPENSSL_LIBRARY_VERSION}. Fix it with: gem update openssl"
100
+ else
101
+ " (use --insecure to skip verification)"
102
+ end
103
+ end
104
+
105
+ private
106
+
107
+ def request(uri)
108
+ started = monotonic_ms
109
+ response = perform(uri, http_method)
110
+ if http_method == "HEAD" && HEAD_FALLBACK_STATUSES.include?(response.code.to_i)
111
+ started = monotonic_ms
112
+ response = perform(uri, "GET")
113
+ end
114
+
115
+ Hop.new(
116
+ url: uri.to_s,
117
+ status: response.code.to_i,
118
+ reason: response.message.to_s.strip,
119
+ location: response["location"],
120
+ duration_ms: (monotonic_ms - started).round
121
+ )
122
+ end
123
+
124
+ def perform(uri, verb)
125
+ http = Net::HTTP.new(uri.host, uri.port) # proxy taken from ENV
126
+ http.use_ssl = uri.scheme == "https"
127
+ http.verify_mode = verify_ssl ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
128
+ http.open_timeout = timeout
129
+ http.read_timeout = timeout
130
+ http.write_timeout = timeout
131
+ http.ssl_timeout = timeout if http.use_ssl?
132
+
133
+ klass = verb == "HEAD" ? Net::HTTP::Head : Net::HTTP::Get
134
+ req = klass.new(uri)
135
+ req["User-Agent"] = user_agent
136
+ req["Accept"] = "*/*"
137
+ headers.each { |k, v| req[k] = v }
138
+
139
+ http.start do |conn|
140
+ # Don't download bodies: we only care about status and headers.
141
+ conn.request(req) { |res| res.read_body { nil } if verb == "GET" }
142
+ end
143
+ end
144
+
145
+ def resolve_location(base, location)
146
+ target = URI.join(base.to_s, location.strip)
147
+ raise Error, "Redirect to unsupported URL: #{location}" unless target.is_a?(URI::HTTP)
148
+
149
+ target
150
+ rescue URI::Error
151
+ # Some servers send unescaped characters in Location.
152
+ URI.join(base.to_s, URI::DEFAULT_PARSER.escape(location.strip))
153
+ end
154
+
155
+ def describe_error(error, uri)
156
+ where = uri ? " (#{uri.host})" : ""
157
+ case error
158
+ when SocketError
159
+ "Could not resolve host#{where}"
160
+ when Errno::ECONNREFUSED
161
+ "Connection refused#{where}"
162
+ when Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout, Timeout::Error
163
+ "Timed out after #{timeout}s#{where}"
164
+ when OpenSSL::SSL::SSLError
165
+ "TLS error#{where}: #{error.message}#{self.class.tls_hint(error.message)}"
166
+ else
167
+ "#{error.class}: #{error.message}"
168
+ end
169
+ end
170
+
171
+ def monotonic_ms
172
+ Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond)
173
+ end
174
+ end
175
+ end
data/lib/hoper/version.rb CHANGED
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Hoper
2
- VERSION = "0.1.1"
4
+ VERSION = "1.0.1"
3
5
  end
data/lib/hoper.rb CHANGED
@@ -1,5 +1,22 @@
1
- require "hoper/version"
1
+ # frozen_string_literal: true
2
2
 
3
+ require_relative "hoper/version"
4
+ require_relative "hoper/hop"
5
+ require_relative "hoper/result"
6
+ require_relative "hoper/tracer"
7
+
8
+ # Hoper traces every redirect ("hop") a URL goes through until it reaches
9
+ # its final destination.
10
+ #
11
+ # result = Hoper.trace("https://bit.ly/example")
12
+ # result.hops.each { |hop| puts "#{hop.status} #{hop.url}" }
13
+ # result.final_url # => "https://example.com/"
3
14
  module Hoper
4
- # Your code goes here...
15
+ class Error < StandardError; end
16
+ class InvalidURLError < Error; end
17
+
18
+ # Convenience wrapper around Hoper::Tracer.
19
+ def self.trace(url, **options)
20
+ Tracer.new(**options).trace(url)
21
+ end
5
22
  end
metadata CHANGED
@@ -1,58 +1,17 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: hoper
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.1
4
+ version: 1.0.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Gabriel Aramburu
8
- autorequire:
9
8
  bindir: exe
10
9
  cert_chain: []
11
- date: 2022-12-04 00:00:00.000000000 Z
12
- dependencies:
13
- - !ruby/object:Gem::Dependency
14
- name: curb
15
- requirement: !ruby/object:Gem::Requirement
16
- requirements:
17
- - - ">="
18
- - !ruby/object:Gem::Version
19
- version: '0'
20
- type: :runtime
21
- prerelease: false
22
- version_requirements: !ruby/object:Gem::Requirement
23
- requirements:
24
- - - ">="
25
- - !ruby/object:Gem::Version
26
- version: '0'
27
- - !ruby/object:Gem::Dependency
28
- name: bundler
29
- requirement: !ruby/object:Gem::Requirement
30
- requirements:
31
- - - "~>"
32
- - !ruby/object:Gem::Version
33
- version: '1.12'
34
- type: :development
35
- prerelease: false
36
- version_requirements: !ruby/object:Gem::Requirement
37
- requirements:
38
- - - "~>"
39
- - !ruby/object:Gem::Version
40
- version: '1.12'
41
- - !ruby/object:Gem::Dependency
42
- name: rake
43
- requirement: !ruby/object:Gem::Requirement
44
- requirements:
45
- - - "~>"
46
- - !ruby/object:Gem::Version
47
- version: '10.0'
48
- type: :development
49
- prerelease: false
50
- version_requirements: !ruby/object:Gem::Requirement
51
- requirements:
52
- - - "~>"
53
- - !ruby/object:Gem::Version
54
- version: '10.0'
55
- description: Trace URL's jumps across the rel links to obtain the last URL
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: 'Hoper follows HTTP redirects step by step and shows each hop with its
13
+ status code and timing, until the final URL. Pure Ruby, no native extensions: works
14
+ on Linux, macOS and Windows.'
56
15
  email:
57
16
  - aramburu.gabriel@gmail.com
58
17
  executables:
@@ -60,23 +19,25 @@ executables:
60
19
  extensions: []
61
20
  extra_rdoc_files: []
62
21
  files:
63
- - ".gitignore"
64
- - CODE_OF_CONDUCT.md
65
- - Gemfile
22
+ - CHANGELOG.md
66
23
  - LICENSE.txt
67
24
  - README.md
68
- - Rakefile
69
- - bin/console
70
- - bin/setup
71
25
  - exe/hoper
72
- - hoper.gemspec
73
26
  - lib/hoper.rb
27
+ - lib/hoper/cli.rb
28
+ - lib/hoper/hop.rb
29
+ - lib/hoper/result.rb
30
+ - lib/hoper/tracer.rb
74
31
  - lib/hoper/version.rb
75
- homepage: http://garamburu.com
32
+ homepage: https://github.com/gabamnml/hoper
76
33
  licenses:
77
34
  - MIT
78
- metadata: {}
79
- post_install_message:
35
+ metadata:
36
+ homepage_uri: https://github.com/gabamnml/hoper
37
+ source_code_uri: https://github.com/gabamnml/hoper
38
+ changelog_uri: https://github.com/gabamnml/hoper/blob/master/CHANGELOG.md
39
+ bug_tracker_uri: https://github.com/gabamnml/hoper/issues
40
+ rubygems_mfa_required: 'true'
80
41
  rdoc_options: []
81
42
  require_paths:
82
43
  - lib
@@ -84,15 +45,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
84
45
  requirements:
85
46
  - - ">="
86
47
  - !ruby/object:Gem::Version
87
- version: '0'
48
+ version: '3.1'
88
49
  required_rubygems_version: !ruby/object:Gem::Requirement
89
50
  requirements:
90
51
  - - ">="
91
52
  - !ruby/object:Gem::Version
92
53
  version: '0'
93
54
  requirements: []
94
- rubygems_version: 3.1.2
95
- signing_key:
55
+ rubygems_version: 4.0.20
96
56
  specification_version: 4
97
- summary: Trace the URL's of a link.
57
+ summary: Trace every redirect (hop) a URL goes through.
98
58
  test_files: []
data/.gitignore DELETED
@@ -1,9 +0,0 @@
1
- /.bundle/
2
- /.yardoc
3
- /Gemfile.lock
4
- /_yardoc/
5
- /coverage/
6
- /doc/
7
- /pkg/
8
- /spec/reports/
9
- /tmp/
data/CODE_OF_CONDUCT.md DELETED
@@ -1,49 +0,0 @@
1
- # Contributor Code of Conduct
2
-
3
- As contributors and maintainers of this project, and in the interest of
4
- fostering an open and welcoming community, we pledge to respect all people who
5
- contribute through reporting issues, posting feature requests, updating
6
- documentation, submitting pull requests or patches, and other activities.
7
-
8
- We are committed to making participation in this project a harassment-free
9
- experience for everyone, regardless of level of experience, gender, gender
10
- identity and expression, sexual orientation, disability, personal appearance,
11
- body size, race, ethnicity, age, religion, or nationality.
12
-
13
- Examples of unacceptable behavior by participants include:
14
-
15
- * The use of sexualized language or imagery
16
- * Personal attacks
17
- * Trolling or insulting/derogatory comments
18
- * Public or private harassment
19
- * Publishing other's private information, such as physical or electronic
20
- addresses, without explicit permission
21
- * Other unethical or unprofessional conduct
22
-
23
- Project maintainers have the right and responsibility to remove, edit, or
24
- reject comments, commits, code, wiki edits, issues, and other contributions
25
- that are not aligned to this Code of Conduct, or to ban temporarily or
26
- permanently any contributor for other behaviors that they deem inappropriate,
27
- threatening, offensive, or harmful.
28
-
29
- By adopting this Code of Conduct, project maintainers commit themselves to
30
- fairly and consistently applying these principles to every aspect of managing
31
- this project. Project maintainers who do not follow or enforce the Code of
32
- Conduct may be permanently removed from the project team.
33
-
34
- This code of conduct applies both within project spaces and in public spaces
35
- when an individual is representing the project or its community.
36
-
37
- Instances of abusive, harassing, or otherwise unacceptable behavior may be
38
- reported by contacting a project maintainer at aramburu.gabriel@gmail.com. All
39
- complaints will be reviewed and investigated and will result in a response that
40
- is deemed necessary and appropriate to the circumstances. Maintainers are
41
- obligated to maintain confidentiality with regard to the reporter of an
42
- incident.
43
-
44
- This Code of Conduct is adapted from the [Contributor Covenant][homepage],
45
- version 1.3.0, available at
46
- [http://contributor-covenant.org/version/1/3/0/][version]
47
-
48
- [homepage]: http://contributor-covenant.org
49
- [version]: http://contributor-covenant.org/version/1/3/0/
data/Gemfile DELETED
@@ -1,4 +0,0 @@
1
- source 'https://rubygems.org'
2
-
3
- # Specify your gem's dependencies in hoper.gemspec
4
- gemspec
data/Rakefile DELETED
@@ -1,2 +0,0 @@
1
- require "bundler/gem_tasks"
2
- task :default => :spec
data/bin/console DELETED
@@ -1,14 +0,0 @@
1
- #!/usr/bin/env ruby
2
-
3
- require "bundler/setup"
4
- require "hoper"
5
-
6
- # You can add fixtures and/or initialization code here to make experimenting
7
- # with your gem easier. You can also use a different console, if you like.
8
-
9
- # (If you use this, don't forget to add pry to your Gemfile!)
10
- # require "pry"
11
- # Pry.start
12
-
13
- require "irb"
14
- IRB.start
data/bin/setup DELETED
@@ -1,8 +0,0 @@
1
- #!/usr/bin/env bash
2
- set -euo pipefail
3
- IFS=$'\n\t'
4
- set -vx
5
-
6
- bundle install
7
-
8
- # Do any other automated setup that you need to do here
data/hoper.gemspec DELETED
@@ -1,25 +0,0 @@
1
- # coding: utf-8
2
- require_relative 'lib/hoper/version'
3
-
4
- Gem::Specification.new do |spec|
5
- spec.name = "hoper"
6
- spec.version = Hoper::VERSION
7
- spec.authors = ["Gabriel Aramburu"]
8
- spec.email = ["aramburu.gabriel@gmail.com"]
9
-
10
- spec.summary = %q{Trace the URL's of a link.}
11
- spec.description = %q{Trace URL's jumps across the rel links to obtain the last URL}
12
- spec.homepage = "http://garamburu.com"
13
- spec.license = "MIT"
14
-
15
- spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
16
- spec.bindir = "exe"
17
- spec.executables = ["hoper"]
18
- # spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
19
- spec.require_paths = ["lib"]
20
-
21
- spec.add_dependency "curb"
22
-
23
- spec.add_development_dependency "bundler", "~> 1.12"
24
- spec.add_development_dependency "rake", "~> 10.0"
25
- end