repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/lib/em/deferrable/pool.rb
_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/lib/em/deferrable/pool.rb
warn "EM::Deferrable::Pool is deprecated, please use EM::Pool" EM::Deferrable::Pool = EM::Pool
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-archives-2.1.1/lib/jekyll-archives.rb
_vendor/ruby/2.6.0/gems/jekyll-archives-2.1.1/lib/jekyll-archives.rb
require 'jekyll' module Jekyll module Archives # Internal requires autoload :Archive, 'jekyll-archives/archive' autoload :VERSION, 'jekyll-archives/version' if (Jekyll.const_defined? :Hooks) Jekyll::Hooks.register :site, :after_reset do |site| # We need to disable incremental regen for Archives to generate with the # correct content site.regenerator.instance_variable_set(:@disabled, true) end end class Archives < Jekyll::Generator safe true DEFAULTS = { 'layout' => 'archive', 'enabled' => [], 'permalinks' => { 'year' => '/:year/', 'month' => '/:year/:month/', 'day' => '/:year/:month/:day/', 'tag' => '/tag/:name/', 'category' => '/category/:name/' } } def initialize(config = nil) if config['jekyll-archives'].nil? @config = DEFAULTS else @config = Utils.deep_merge_hashes(DEFAULTS, config['jekyll-archives']) end end def generate(site) @site = site @posts = site.posts @archives = [] @site.config['jekyll-archives'] = @config read @site.pages.concat(@archives) @site.config["archives"] = @archives end # Read archive data from posts def read read_tags read_categories read_dates end def read_tags if enabled? "tags" tags.each do |title, posts| @archives << Archive.new(@site, title, "tag", posts) end end end def read_categories if enabled? "categories" categories.each do |title, posts| @archives << Archive.new(@site, title, "category", posts) end end end def read_dates years.each do |year, posts| @archives << Archive.new(@site, { :year => year }, "year", posts) if enabled? "year" months(posts).each do |month, posts| @archives << Archive.new(@site, { :year => year, :month => month }, "month", posts) if enabled? "month" days(posts).each do |day, posts| @archives << Archive.new(@site, { :year => year, :month => month, :day => day }, "day", posts) if enabled? "day" end end end end # Checks if archive type is enabled in config def enabled?(archive) @config["enabled"] == true || @config["enabled"] == "all" || if @config["enabled"].is_a? Array @config["enabled"].include? archive end end def tags @site.post_attr_hash('tags') end def categories @site.post_attr_hash('categories') end # Custom `post_attr_hash` method for years def years hash = Hash.new { |h, key| h[key] = [] } # In Jekyll 3, Collection#each should be called on the #docs array directly. if Jekyll::VERSION >= '3.0.0' @posts.docs.each { |p| hash[p.date.strftime("%Y")] << p } else @posts.each { |p| hash[p.date.strftime("%Y")] << p } end hash.values.each { |posts| posts.sort!.reverse! } hash end def months(year_posts) hash = Hash.new { |h, key| h[key] = [] } year_posts.each { |p| hash[p.date.strftime("%m")] << p } hash.values.each { |posts| posts.sort!.reverse! } hash end def days(month_posts) hash = Hash.new { |h, key| h[key] = [] } month_posts.each { |p| hash[p.date.strftime("%d")] << p } hash.values.each { |posts| posts.sort!.reverse! } hash end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-archives-2.1.1/lib/jekyll-archives/archive.rb
_vendor/ruby/2.6.0/gems/jekyll-archives-2.1.1/lib/jekyll-archives/archive.rb
module Jekyll module Archives class Archive < Jekyll::Page attr_accessor :posts, :type, :slug # Attributes for Liquid templates ATTRIBUTES_FOR_LIQUID = %w( posts type title date name path url ).freeze # Initialize a new Archive page # # site - The Site object. # title - The name of the tag/category or a Hash of the year/month/day in case of date. # e.g. { :year => 2014, :month => 08 } or "my-category" or "my-tag". # type - The type of archive. Can be one of "year", "month", "day", "category", or "tag" # posts - The array of posts that belong in this archive. def initialize(site, title, type, posts) @site = site @posts = posts @type = type @title = title @config = site.config['jekyll-archives'] # Generate slug if tag or category (taken from jekyll/jekyll/features/support/env.rb) if title.to_s.length @slug = Utils.slugify(title.to_s) end # Use ".html" for file extension and url for path @ext = File.extname(relative_path) @path = relative_path @name = File.basename(relative_path, @ext) @data = { "layout" => layout } @content = "" end # The template of the permalink. # # Returns the template String. def template @config['permalinks'][type] end # The layout to use for rendering # # Returns the layout as a String def layout if @config['layouts'] && @config['layouts'][type] @config['layouts'][type] else @config['layout'] end end # Returns a hash of URL placeholder names (as symbols) mapping to the # desired placeholder replacements. For details see "url.rb". def url_placeholders if @title.is_a? Hash @title.merge({ :type => @type }) else { :name => @slug, :type => @type } end end # The generated relative url of this page. e.g. /about.html. # # Returns the String url. def url @url ||= URL.new({ :template => template, :placeholders => url_placeholders, :permalink => nil }).to_s rescue ArgumentError raise ArgumentError.new "Template \"#{template}\" provided is invalid." end # Produce a title object suitable for Liquid based on type of archive. # # Returns a String (for tag and category archives) and nil for # date-based archives. def title if @title.is_a? String @title end end # Produce a date object if a date-based archive # # Returns a Date. def date if @title.is_a? Hash args = @title.values.map { |s| s.to_i } Date.new(*args) end end # Obtain the write path relative to the destination directory # # Returns the destination relative path String. def relative_path path = URL.unescape_path(url).gsub(/^\//, '') path = File.join(path, "index.html") if url =~ /\/$/ path end # Returns the object as a debug String. def inspect "#<Jekyll:Archive @type=#{@type.to_s} @title=#{@title} @data=#{@data.inspect}>" end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/addressable-2.5.2/spec/spec_helper.rb
_vendor/ruby/2.6.0/gems/addressable-2.5.2/spec/spec_helper.rb
require 'bundler/setup' require 'rspec/its' begin require 'coveralls' Coveralls.wear! do add_filter "spec/" add_filter "vendor/" end rescue LoadError warn "warning: coveralls gem not found; skipping Coveralls" require 'simplecov' SimpleCov.start do add_filter "spec/" add_filter "vendor/" end end RSpec.configure do |config| config.warnings = true end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/addressable-2.5.2/spec/addressable/security_spec.rb
_vendor/ruby/2.6.0/gems/addressable-2.5.2/spec/addressable/security_spec.rb
# coding: utf-8 # Copyright (C) Bob Aman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "spec_helper" require "addressable/uri" describe Addressable::URI, "when created with a URI known to cause crashes " + "in certain browsers" do it "should parse correctly" do uri = Addressable::URI.parse('%%30%30') expect(uri.path).to eq('%%30%30') expect(uri.normalize.path).to eq('%2500') end it "should parse correctly as a full URI" do uri = Addressable::URI.parse('http://www.example.com/%%30%30') expect(uri.path).to eq('/%%30%30') expect(uri.normalize.path).to eq('/%2500') end end describe Addressable::URI, "when created with a URI known to cause crashes " + "in certain browsers" do it "should parse correctly" do uri = Addressable::URI.parse('لُصّبُلُلصّبُررً ॣ ॣh ॣ ॣ 冗') expect(uri.path).to eq('لُصّبُلُلصّبُررً ॣ ॣh ॣ ॣ 冗') expect(uri.normalize.path).to eq( '%D9%84%D9%8F%D8%B5%D9%91%D8%A8%D9%8F%D9%84%D9%8F%D9%84%D8%B5%D9%91' + '%D8%A8%D9%8F%D8%B1%D8%B1%D9%8B%20%E0%A5%A3%20%E0%A5%A3h%20%E0%A5' + '%A3%20%E0%A5%A3%20%E5%86%97' ) end it "should parse correctly as a full URI" do uri = Addressable::URI.parse('http://www.example.com/لُصّبُلُلصّبُررً ॣ ॣh ॣ ॣ 冗') expect(uri.path).to eq('/لُصّبُلُلصّبُررً ॣ ॣh ॣ ॣ 冗') expect(uri.normalize.path).to eq( '/%D9%84%D9%8F%D8%B5%D9%91%D8%A8%D9%8F%D9%84%D9%8F%D9%84%D8%B5%D9%91' + '%D8%A8%D9%8F%D8%B1%D8%B1%D9%8B%20%E0%A5%A3%20%E0%A5%A3h%20%E0%A5' + '%A3%20%E0%A5%A3%20%E5%86%97' ) end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/addressable-2.5.2/spec/addressable/rack_mount_compat_spec.rb
_vendor/ruby/2.6.0/gems/addressable-2.5.2/spec/addressable/rack_mount_compat_spec.rb
# coding: utf-8 # Copyright (C) Bob Aman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "spec_helper" require "addressable/uri" require "addressable/template" require "rack/mount" describe Rack::Mount do let(:app_one) do proc { |env| [200, {'Content-Type' => 'text/plain'}, 'Route 1'] } end let(:app_two) do proc { |env| [200, {'Content-Type' => 'text/plain'}, 'Route 2'] } end let(:app_three) do proc { |env| [200, {'Content-Type' => 'text/plain'}, 'Route 3'] } end let(:routes) do s = Rack::Mount::RouteSet.new do |set| set.add_route(app_one, { :request_method => 'GET', :path_info => Addressable::Template.new('/one/{id}/') }, {:id => 'unidentified'}, :one) set.add_route(app_two, { :request_method => 'GET', :path_info => Addressable::Template.new('/two/') }, {:id => 'unidentified'}, :two) set.add_route(app_three, { :request_method => 'GET', :path_info => Addressable::Template.new('/three/{id}/').to_regexp }, {:id => 'unidentified'}, :three) end s.rehash s end it "should generate from routes with Addressable::Template" do path, _ = routes.generate(:path_info, :one, {:id => '123'}) expect(path).to eq '/one/123/' end it "should generate from routes with Addressable::Template using defaults" do path, _ = routes.generate(:path_info, :one, {}) expect(path).to eq '/one/unidentified/' end it "should recognize routes with Addressable::Template" do request = Rack::Request.new( 'REQUEST_METHOD' => 'GET', 'PATH_INFO' => '/one/123/' ) route, _, params = routes.recognize(request) expect(route).not_to be_nil expect(route.app).to eq app_one expect(params).to eq({id: '123'}) end it "should generate from routes with Addressable::Template" do path, _ = routes.generate(:path_info, :two, {:id => '654'}) expect(path).to eq '/two/' end it "should generate from routes with Addressable::Template using defaults" do path, _ = routes.generate(:path_info, :two, {}) expect(path).to eq '/two/' end it "should recognize routes with Addressable::Template" do request = Rack::Request.new( 'REQUEST_METHOD' => 'GET', 'PATH_INFO' => '/two/' ) route, _, params = routes.recognize(request) expect(route).not_to be_nil expect(route.app).to eq app_two expect(params).to eq({id: 'unidentified'}) end it "should recognize routes with derived Regexp" do request = Rack::Request.new( 'REQUEST_METHOD' => 'GET', 'PATH_INFO' => '/three/789/' ) route, _, params = routes.recognize(request) expect(route).not_to be_nil expect(route.app).to eq app_three expect(params).to eq({id: '789'}) end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/addressable-2.5.2/spec/addressable/template_spec.rb
_vendor/ruby/2.6.0/gems/addressable-2.5.2/spec/addressable/template_spec.rb
# coding: utf-8 # Copyright (C) Bob Aman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "spec_helper" require "bigdecimal" require "addressable/template" shared_examples_for 'expands' do |tests| tests.each do |template, expansion| exp = expansion.is_a?(Array) ? expansion.first : expansion it "#{template} to #{exp}" do tmpl = Addressable::Template.new(template).expand(subject) if expansion.is_a?(Array) expect(expansion.any?{|i| i == tmpl.to_str}).to be true else expect(tmpl.to_str).to eq(expansion) end end end end describe "eql?" do let(:template) { Addressable::Template.new('https://www.example.com/{foo}') } it 'is equal when the pattern matches' do other_template = Addressable::Template.new('https://www.example.com/{foo}') expect(template).to be_eql(other_template) expect(other_template).to be_eql(template) end it 'is not equal when the pattern differs' do other_template = Addressable::Template.new('https://www.example.com/{bar}') expect(template).to_not be_eql(other_template) expect(other_template).to_not be_eql(template) end it 'is not equal to non-templates' do uri = 'https://www.example.com/foo/bar' addressable_template = Addressable::Template.new uri addressable_uri = Addressable::URI.parse uri expect(addressable_template).to_not be_eql(addressable_uri) expect(addressable_uri).to_not be_eql(addressable_template) end end describe "==" do let(:template) { Addressable::Template.new('https://www.example.com/{foo}') } it 'is equal when the pattern matches' do other_template = Addressable::Template.new('https://www.example.com/{foo}') expect(template).to eq other_template expect(other_template).to eq template end it 'is not equal when the pattern differs' do other_template = Addressable::Template.new('https://www.example.com/{bar}') expect(template).not_to eq other_template expect(other_template).not_to eq template end it 'is not equal to non-templates' do uri = 'https://www.example.com/foo/bar' addressable_template = Addressable::Template.new uri addressable_uri = Addressable::URI.parse uri expect(addressable_template).not_to eq addressable_uri expect(addressable_uri).not_to eq addressable_template end end describe "Type conversion" do subject { { :var => true, :hello => 1234, :nothing => nil, :sym => :symbolic, :decimal => BigDecimal.new('1') } } it_behaves_like 'expands', { '{var}' => 'true', '{hello}' => '1234', '{nothing}' => '', '{sym}' => 'symbolic', '{decimal}' => RUBY_VERSION < '2.4.0' ? '0.1E1' : '0.1e1' } end describe "Level 1:" do subject { {:var => "value", :hello => "Hello World!"} } it_behaves_like 'expands', { '{var}' => 'value', '{hello}' => 'Hello%20World%21' } end describe "Level 2" do subject { { :var => "value", :hello => "Hello World!", :path => "/foo/bar" } } context "Operator +:" do it_behaves_like 'expands', { '{+var}' => 'value', '{+hello}' => 'Hello%20World!', '{+path}/here' => '/foo/bar/here', 'here?ref={+path}' => 'here?ref=/foo/bar' } end context "Operator #:" do it_behaves_like 'expands', { 'X{#var}' => 'X#value', 'X{#hello}' => 'X#Hello%20World!' } end end describe "Level 3" do subject { { :var => "value", :hello => "Hello World!", :empty => "", :path => "/foo/bar", :x => "1024", :y => "768" } } context "Operator nil (multiple vars):" do it_behaves_like 'expands', { 'map?{x,y}' => 'map?1024,768', '{x,hello,y}' => '1024,Hello%20World%21,768' } end context "Operator + (multiple vars):" do it_behaves_like 'expands', { '{+x,hello,y}' => '1024,Hello%20World!,768', '{+path,x}/here' => '/foo/bar,1024/here' } end context "Operator # (multiple vars):" do it_behaves_like 'expands', { '{#x,hello,y}' => '#1024,Hello%20World!,768', '{#path,x}/here' => '#/foo/bar,1024/here' } end context "Operator ." do it_behaves_like 'expands', { 'X{.var}' => 'X.value', 'X{.x,y}' => 'X.1024.768' } end context "Operator /" do it_behaves_like 'expands', { '{/var}' => '/value', '{/var,x}/here' => '/value/1024/here' } end context "Operator ;" do it_behaves_like 'expands', { '{;x,y}' => ';x=1024;y=768', '{;x,y,empty}' => ';x=1024;y=768;empty' } end context "Operator ?" do it_behaves_like 'expands', { '{?x,y}' => '?x=1024&y=768', '{?x,y,empty}' => '?x=1024&y=768&empty=' } end context "Operator &" do it_behaves_like 'expands', { '?fixed=yes{&x}' => '?fixed=yes&x=1024', '{&x,y,empty}' => '&x=1024&y=768&empty=' } end end describe "Level 4" do subject { { :var => "value", :hello => "Hello World!", :path => "/foo/bar", :semi => ";", :list => %w(red green blue), :keys => {"semi" => ';', "dot" => '.', "comma" => ','} } } context "Expansion with value modifiers" do it_behaves_like 'expands', { '{var:3}' => 'val', '{var:30}' => 'value', '{list}' => 'red,green,blue', '{list*}' => 'red,green,blue', '{keys}' => [ 'semi,%3B,dot,.,comma,%2C', 'dot,.,semi,%3B,comma,%2C', 'comma,%2C,semi,%3B,dot,.', 'semi,%3B,comma,%2C,dot,.', 'dot,.,comma,%2C,semi,%3B', 'comma,%2C,dot,.,semi,%3B' ], '{keys*}' => [ 'semi=%3B,dot=.,comma=%2C', 'dot=.,semi=%3B,comma=%2C', 'comma=%2C,semi=%3B,dot=.', 'semi=%3B,comma=%2C,dot=.', 'dot=.,comma=%2C,semi=%3B', 'comma=%2C,dot=.,semi=%3B' ] } end context "Operator + with value modifiers" do it_behaves_like 'expands', { '{+path:6}/here' => '/foo/b/here', '{+list}' => 'red,green,blue', '{+list*}' => 'red,green,blue', '{+keys}' => [ 'semi,;,dot,.,comma,,', 'dot,.,semi,;,comma,,', 'comma,,,semi,;,dot,.', 'semi,;,comma,,,dot,.', 'dot,.,comma,,,semi,;', 'comma,,,dot,.,semi,;' ], '{+keys*}' => [ 'semi=;,dot=.,comma=,', 'dot=.,semi=;,comma=,', 'comma=,,semi=;,dot=.', 'semi=;,comma=,,dot=.', 'dot=.,comma=,,semi=;', 'comma=,,dot=.,semi=;' ] } end context "Operator # with value modifiers" do it_behaves_like 'expands', { '{#path:6}/here' => '#/foo/b/here', '{#list}' => '#red,green,blue', '{#list*}' => '#red,green,blue', '{#keys}' => [ '#semi,;,dot,.,comma,,', '#dot,.,semi,;,comma,,', '#comma,,,semi,;,dot,.', '#semi,;,comma,,,dot,.', '#dot,.,comma,,,semi,;', '#comma,,,dot,.,semi,;' ], '{#keys*}' => [ '#semi=;,dot=.,comma=,', '#dot=.,semi=;,comma=,', '#comma=,,semi=;,dot=.', '#semi=;,comma=,,dot=.', '#dot=.,comma=,,semi=;', '#comma=,,dot=.,semi=;' ] } end context "Operator . with value modifiers" do it_behaves_like 'expands', { 'X{.var:3}' => 'X.val', 'X{.list}' => 'X.red,green,blue', 'X{.list*}' => 'X.red.green.blue', 'X{.keys}' => [ 'X.semi,%3B,dot,.,comma,%2C', 'X.dot,.,semi,%3B,comma,%2C', 'X.comma,%2C,semi,%3B,dot,.', 'X.semi,%3B,comma,%2C,dot,.', 'X.dot,.,comma,%2C,semi,%3B', 'X.comma,%2C,dot,.,semi,%3B' ], 'X{.keys*}' => [ 'X.semi=%3B.dot=..comma=%2C', 'X.dot=..semi=%3B.comma=%2C', 'X.comma=%2C.semi=%3B.dot=.', 'X.semi=%3B.comma=%2C.dot=.', 'X.dot=..comma=%2C.semi=%3B', 'X.comma=%2C.dot=..semi=%3B' ] } end context "Operator / with value modifiers" do it_behaves_like 'expands', { '{/var:1,var}' => '/v/value', '{/list}' => '/red,green,blue', '{/list*}' => '/red/green/blue', '{/list*,path:4}' => '/red/green/blue/%2Ffoo', '{/keys}' => [ '/semi,%3B,dot,.,comma,%2C', '/dot,.,semi,%3B,comma,%2C', '/comma,%2C,semi,%3B,dot,.', '/semi,%3B,comma,%2C,dot,.', '/dot,.,comma,%2C,semi,%3B', '/comma,%2C,dot,.,semi,%3B' ], '{/keys*}' => [ '/semi=%3B/dot=./comma=%2C', '/dot=./semi=%3B/comma=%2C', '/comma=%2C/semi=%3B/dot=.', '/semi=%3B/comma=%2C/dot=.', '/dot=./comma=%2C/semi=%3B', '/comma=%2C/dot=./semi=%3B' ] } end context "Operator ; with value modifiers" do it_behaves_like 'expands', { '{;hello:5}' => ';hello=Hello', '{;list}' => ';list=red,green,blue', '{;list*}' => ';list=red;list=green;list=blue', '{;keys}' => [ ';keys=semi,%3B,dot,.,comma,%2C', ';keys=dot,.,semi,%3B,comma,%2C', ';keys=comma,%2C,semi,%3B,dot,.', ';keys=semi,%3B,comma,%2C,dot,.', ';keys=dot,.,comma,%2C,semi,%3B', ';keys=comma,%2C,dot,.,semi,%3B' ], '{;keys*}' => [ ';semi=%3B;dot=.;comma=%2C', ';dot=.;semi=%3B;comma=%2C', ';comma=%2C;semi=%3B;dot=.', ';semi=%3B;comma=%2C;dot=.', ';dot=.;comma=%2C;semi=%3B', ';comma=%2C;dot=.;semi=%3B' ] } end context "Operator ? with value modifiers" do it_behaves_like 'expands', { '{?var:3}' => '?var=val', '{?list}' => '?list=red,green,blue', '{?list*}' => '?list=red&list=green&list=blue', '{?keys}' => [ '?keys=semi,%3B,dot,.,comma,%2C', '?keys=dot,.,semi,%3B,comma,%2C', '?keys=comma,%2C,semi,%3B,dot,.', '?keys=semi,%3B,comma,%2C,dot,.', '?keys=dot,.,comma,%2C,semi,%3B', '?keys=comma,%2C,dot,.,semi,%3B' ], '{?keys*}' => [ '?semi=%3B&dot=.&comma=%2C', '?dot=.&semi=%3B&comma=%2C', '?comma=%2C&semi=%3B&dot=.', '?semi=%3B&comma=%2C&dot=.', '?dot=.&comma=%2C&semi=%3B', '?comma=%2C&dot=.&semi=%3B' ] } end context "Operator & with value modifiers" do it_behaves_like 'expands', { '{&var:3}' => '&var=val', '{&list}' => '&list=red,green,blue', '{&list*}' => '&list=red&list=green&list=blue', '{&keys}' => [ '&keys=semi,%3B,dot,.,comma,%2C', '&keys=dot,.,semi,%3B,comma,%2C', '&keys=comma,%2C,semi,%3B,dot,.', '&keys=semi,%3B,comma,%2C,dot,.', '&keys=dot,.,comma,%2C,semi,%3B', '&keys=comma,%2C,dot,.,semi,%3B' ], '{&keys*}' => [ '&semi=%3B&dot=.&comma=%2C', '&dot=.&semi=%3B&comma=%2C', '&comma=%2C&semi=%3B&dot=.', '&semi=%3B&comma=%2C&dot=.', '&dot=.&comma=%2C&semi=%3B', '&comma=%2C&dot=.&semi=%3B' ] } end end describe "Modifiers" do subject { { :var => "value", :semi => ";", :year => %w(1965 2000 2012), :dom => %w(example com) } } context "length" do it_behaves_like 'expands', { '{var:3}' => 'val', '{var:30}' => 'value', '{var}' => 'value', '{semi}' => '%3B', '{semi:2}' => '%3B' } end context "explode" do it_behaves_like 'expands', { 'find{?year*}' => 'find?year=1965&year=2000&year=2012', 'www{.dom*}' => 'www.example.com', } end end describe "Expansion" do subject { { :count => ["one", "two", "three"], :dom => ["example", "com"], :dub => "me/too", :hello => "Hello World!", :half => "50%", :var => "value", :who => "fred", :base => "http://example.com/home/", :path => "/foo/bar", :list => ["red", "green", "blue"], :keys => {"semi" => ";","dot" => ".","comma" => ","}, :v => "6", :x => "1024", :y => "768", :empty => "", :empty_keys => {}, :undef => nil } } context "concatenation" do it_behaves_like 'expands', { '{count}' => 'one,two,three', '{count*}' => 'one,two,three', '{/count}' => '/one,two,three', '{/count*}' => '/one/two/three', '{;count}' => ';count=one,two,three', '{;count*}' => ';count=one;count=two;count=three', '{?count}' => '?count=one,two,three', '{?count*}' => '?count=one&count=two&count=three', '{&count*}' => '&count=one&count=two&count=three' } end context "simple expansion" do it_behaves_like 'expands', { '{var}' => 'value', '{hello}' => 'Hello%20World%21', '{half}' => '50%25', 'O{empty}X' => 'OX', 'O{undef}X' => 'OX', '{x,y}' => '1024,768', '{x,hello,y}' => '1024,Hello%20World%21,768', '?{x,empty}' => '?1024,', '?{x,undef}' => '?1024', '?{undef,y}' => '?768', '{var:3}' => 'val', '{var:30}' => 'value', '{list}' => 'red,green,blue', '{list*}' => 'red,green,blue', '{keys}' => [ 'semi,%3B,dot,.,comma,%2C', 'dot,.,semi,%3B,comma,%2C', 'comma,%2C,semi,%3B,dot,.', 'semi,%3B,comma,%2C,dot,.', 'dot,.,comma,%2C,semi,%3B', 'comma,%2C,dot,.,semi,%3B' ], '{keys*}' => [ 'semi=%3B,dot=.,comma=%2C', 'dot=.,semi=%3B,comma=%2C', 'comma=%2C,semi=%3B,dot=.', 'semi=%3B,comma=%2C,dot=.', 'dot=.,comma=%2C,semi=%3B', 'comma=%2C,dot=.,semi=%3B' ] } end context "reserved expansion (+)" do it_behaves_like 'expands', { '{+var}' => 'value', '{+hello}' => 'Hello%20World!', '{+half}' => '50%25', '{base}index' => 'http%3A%2F%2Fexample.com%2Fhome%2Findex', '{+base}index' => 'http://example.com/home/index', 'O{+empty}X' => 'OX', 'O{+undef}X' => 'OX', '{+path}/here' => '/foo/bar/here', 'here?ref={+path}' => 'here?ref=/foo/bar', 'up{+path}{var}/here' => 'up/foo/barvalue/here', '{+x,hello,y}' => '1024,Hello%20World!,768', '{+path,x}/here' => '/foo/bar,1024/here', '{+path:6}/here' => '/foo/b/here', '{+list}' => 'red,green,blue', '{+list*}' => 'red,green,blue', '{+keys}' => [ 'semi,;,dot,.,comma,,', 'dot,.,semi,;,comma,,', 'comma,,,semi,;,dot,.', 'semi,;,comma,,,dot,.', 'dot,.,comma,,,semi,;', 'comma,,,dot,.,semi,;' ], '{+keys*}' => [ 'semi=;,dot=.,comma=,', 'dot=.,semi=;,comma=,', 'comma=,,semi=;,dot=.', 'semi=;,comma=,,dot=.', 'dot=.,comma=,,semi=;', 'comma=,,dot=.,semi=;' ] } end context "fragment expansion (#)" do it_behaves_like 'expands', { '{#var}' => '#value', '{#hello}' => '#Hello%20World!', '{#half}' => '#50%25', 'foo{#empty}' => 'foo#', 'foo{#undef}' => 'foo', '{#x,hello,y}' => '#1024,Hello%20World!,768', '{#path,x}/here' => '#/foo/bar,1024/here', '{#path:6}/here' => '#/foo/b/here', '{#list}' => '#red,green,blue', '{#list*}' => '#red,green,blue', '{#keys}' => [ '#semi,;,dot,.,comma,,', '#dot,.,semi,;,comma,,', '#comma,,,semi,;,dot,.', '#semi,;,comma,,,dot,.', '#dot,.,comma,,,semi,;', '#comma,,,dot,.,semi,;' ], '{#keys*}' => [ '#semi=;,dot=.,comma=,', '#dot=.,semi=;,comma=,', '#comma=,,semi=;,dot=.', '#semi=;,comma=,,dot=.', '#dot=.,comma=,,semi=;', '#comma=,,dot=.,semi=;' ] } end context "label expansion (.)" do it_behaves_like 'expands', { '{.who}' => '.fred', '{.who,who}' => '.fred.fred', '{.half,who}' => '.50%25.fred', 'www{.dom*}' => 'www.example.com', 'X{.var}' => 'X.value', 'X{.empty}' => 'X.', 'X{.undef}' => 'X', 'X{.var:3}' => 'X.val', 'X{.list}' => 'X.red,green,blue', 'X{.list*}' => 'X.red.green.blue', 'X{.keys}' => [ 'X.semi,%3B,dot,.,comma,%2C', 'X.dot,.,semi,%3B,comma,%2C', 'X.comma,%2C,semi,%3B,dot,.', 'X.semi,%3B,comma,%2C,dot,.', 'X.dot,.,comma,%2C,semi,%3B', 'X.comma,%2C,dot,.,semi,%3B' ], 'X{.keys*}' => [ 'X.semi=%3B.dot=..comma=%2C', 'X.dot=..semi=%3B.comma=%2C', 'X.comma=%2C.semi=%3B.dot=.', 'X.semi=%3B.comma=%2C.dot=.', 'X.dot=..comma=%2C.semi=%3B', 'X.comma=%2C.dot=..semi=%3B' ], 'X{.empty_keys}' => 'X', 'X{.empty_keys*}' => 'X' } end context "path expansion (/)" do it_behaves_like 'expands', { '{/who}' => '/fred', '{/who,who}' => '/fred/fred', '{/half,who}' => '/50%25/fred', '{/who,dub}' => '/fred/me%2Ftoo', '{/var}' => '/value', '{/var,empty}' => '/value/', '{/var,undef}' => '/value', '{/var,x}/here' => '/value/1024/here', '{/var:1,var}' => '/v/value', '{/list}' => '/red,green,blue', '{/list*}' => '/red/green/blue', '{/list*,path:4}' => '/red/green/blue/%2Ffoo', '{/keys}' => [ '/semi,%3B,dot,.,comma,%2C', '/dot,.,semi,%3B,comma,%2C', '/comma,%2C,semi,%3B,dot,.', '/semi,%3B,comma,%2C,dot,.', '/dot,.,comma,%2C,semi,%3B', '/comma,%2C,dot,.,semi,%3B' ], '{/keys*}' => [ '/semi=%3B/dot=./comma=%2C', '/dot=./semi=%3B/comma=%2C', '/comma=%2C/semi=%3B/dot=.', '/semi=%3B/comma=%2C/dot=.', '/dot=./comma=%2C/semi=%3B', '/comma=%2C/dot=./semi=%3B' ] } end context "path-style expansion (;)" do it_behaves_like 'expands', { '{;who}' => ';who=fred', '{;half}' => ';half=50%25', '{;empty}' => ';empty', '{;v,empty,who}' => ';v=6;empty;who=fred', '{;v,bar,who}' => ';v=6;who=fred', '{;x,y}' => ';x=1024;y=768', '{;x,y,empty}' => ';x=1024;y=768;empty', '{;x,y,undef}' => ';x=1024;y=768', '{;hello:5}' => ';hello=Hello', '{;list}' => ';list=red,green,blue', '{;list*}' => ';list=red;list=green;list=blue', '{;keys}' => [ ';keys=semi,%3B,dot,.,comma,%2C', ';keys=dot,.,semi,%3B,comma,%2C', ';keys=comma,%2C,semi,%3B,dot,.', ';keys=semi,%3B,comma,%2C,dot,.', ';keys=dot,.,comma,%2C,semi,%3B', ';keys=comma,%2C,dot,.,semi,%3B' ], '{;keys*}' => [ ';semi=%3B;dot=.;comma=%2C', ';dot=.;semi=%3B;comma=%2C', ';comma=%2C;semi=%3B;dot=.', ';semi=%3B;comma=%2C;dot=.', ';dot=.;comma=%2C;semi=%3B', ';comma=%2C;dot=.;semi=%3B' ] } end context "form query expansion (?)" do it_behaves_like 'expands', { '{?who}' => '?who=fred', '{?half}' => '?half=50%25', '{?x,y}' => '?x=1024&y=768', '{?x,y,empty}' => '?x=1024&y=768&empty=', '{?x,y,undef}' => '?x=1024&y=768', '{?var:3}' => '?var=val', '{?list}' => '?list=red,green,blue', '{?list*}' => '?list=red&list=green&list=blue', '{?keys}' => [ '?keys=semi,%3B,dot,.,comma,%2C', '?keys=dot,.,semi,%3B,comma,%2C', '?keys=comma,%2C,semi,%3B,dot,.', '?keys=semi,%3B,comma,%2C,dot,.', '?keys=dot,.,comma,%2C,semi,%3B', '?keys=comma,%2C,dot,.,semi,%3B' ], '{?keys*}' => [ '?semi=%3B&dot=.&comma=%2C', '?dot=.&semi=%3B&comma=%2C', '?comma=%2C&semi=%3B&dot=.', '?semi=%3B&comma=%2C&dot=.', '?dot=.&comma=%2C&semi=%3B', '?comma=%2C&dot=.&semi=%3B' ] } end context "form query expansion (&)" do it_behaves_like 'expands', { '{&who}' => '&who=fred', '{&half}' => '&half=50%25', '?fixed=yes{&x}' => '?fixed=yes&x=1024', '{&x,y,empty}' => '&x=1024&y=768&empty=', '{&x,y,undef}' => '&x=1024&y=768', '{&var:3}' => '&var=val', '{&list}' => '&list=red,green,blue', '{&list*}' => '&list=red&list=green&list=blue', '{&keys}' => [ '&keys=semi,%3B,dot,.,comma,%2C', '&keys=dot,.,semi,%3B,comma,%2C', '&keys=comma,%2C,semi,%3B,dot,.', '&keys=semi,%3B,comma,%2C,dot,.', '&keys=dot,.,comma,%2C,semi,%3B', '&keys=comma,%2C,dot,.,semi,%3B' ], '{&keys*}' => [ '&semi=%3B&dot=.&comma=%2C', '&dot=.&semi=%3B&comma=%2C', '&comma=%2C&semi=%3B&dot=.', '&semi=%3B&comma=%2C&dot=.', '&dot=.&comma=%2C&semi=%3B', '&comma=%2C&dot=.&semi=%3B' ] } end context "non-string key in match data" do subject {Addressable::Template.new("http://example.com/{one}")} it "raises TypeError" do expect { subject.expand(Object.new => "1") }.to raise_error TypeError end end end class ExampleTwoProcessor def self.restore(name, value) return value.gsub(/-/, " ") if name == "query" return value end def self.match(name) return ".*?" if name == "first" return ".*" end def self.validate(name, value) return !!(value =~ /^[\w ]+$/) if name == "query" return true end def self.transform(name, value) return value.gsub(/ /, "+") if name == "query" return value end end class DumbProcessor def self.match(name) return ".*?" if name == "first" end end describe Addressable::Template do describe 'initialize' do context 'with a non-string' do it 'raises a TypeError' do expect { Addressable::Template.new(nil) }.to raise_error(TypeError) end end end describe 'freeze' do subject { Addressable::Template.new("http://example.com/{first}/{+second}/") } it 'freezes the template' do expect(subject.freeze).to be_frozen end end describe "Matching" do let(:uri){ Addressable::URI.parse( "http://example.com/search/an-example-search-query/" ) } let(:uri2){ Addressable::URI.parse("http://example.com/a/b/c/") } let(:uri3){ Addressable::URI.parse("http://example.com/;a=1;b=2;c=3;first=foo") } let(:uri4){ Addressable::URI.parse("http://example.com/?a=1&b=2&c=3&first=foo") } let(:uri5){ "http://example.com/foo" } context "first uri with ExampleTwoProcessor" do subject { Addressable::Template.new( "http://example.com/search/{query}/" ).match(uri, ExampleTwoProcessor) } its(:variables){ should == ["query"] } its(:captures){ should == ["an example search query"] } end context "second uri with ExampleTwoProcessor" do subject { Addressable::Template.new( "http://example.com/{first}/{+second}/" ).match(uri2, ExampleTwoProcessor) } its(:variables){ should == ["first", "second"] } its(:captures){ should == ["a", "b/c"] } end context "second uri with DumbProcessor" do subject { Addressable::Template.new( "http://example.com/{first}/{+second}/" ).match(uri2, DumbProcessor) } its(:variables){ should == ["first", "second"] } its(:captures){ should == ["a", "b/c"] } end context "second uri" do subject { Addressable::Template.new( "http://example.com/{first}{/second*}/" ).match(uri2) } its(:variables){ should == ["first", "second"] } its(:captures){ should == ["a", ["b","c"]] } end context "third uri" do subject { Addressable::Template.new( "http://example.com/{;hash*,first}" ).match(uri3) } its(:variables){ should == ["hash", "first"] } its(:captures){ should == [ {"a" => "1", "b" => "2", "c" => "3", "first" => "foo"}, nil] } end # Note that this expansion is impossible to revert deterministically - the # * operator means first could have been a key of hash or a separate key. # Semantically, a separate key is more likely, but both are possible. context "fourth uri" do subject { Addressable::Template.new( "http://example.com/{?hash*,first}" ).match(uri4) } its(:variables){ should == ["hash", "first"] } its(:captures){ should == [ {"a" => "1", "b" => "2", "c" => "3", "first"=> "foo"}, nil] } end context "fifth uri" do subject { Addressable::Template.new( "http://example.com/{path}{?hash*,first}" ).match(uri5) } its(:variables){ should == ["path", "hash", "first"] } its(:captures){ should == ["foo", nil, nil] } end end describe 'match' do subject { Addressable::Template.new('http://example.com/first/second/') } context 'when the URI is the same as the template' do it 'returns the match data itself with an empty mapping' do uri = Addressable::URI.parse('http://example.com/first/second/') match_data = subject.match(uri) expect(match_data).to be_an Addressable::Template::MatchData expect(match_data.uri).to eq(uri) expect(match_data.template).to eq(subject) expect(match_data.mapping).to be_empty expect(match_data.inspect).to be_an String end end end describe "extract" do let(:template) { Addressable::Template.new( "http://{host}{/segments*}/{?one,two,bogus}{#fragment}" ) } let(:uri){ "http://example.com/a/b/c/?one=1&two=2#foo" } let(:uri2){ "http://example.com/a/b/c/#foo" } it "should be able to extract with queries" do expect(template.extract(uri)).to eq({ "host" => "example.com", "segments" => %w(a b c), "one" => "1", "bogus" => nil, "two" => "2", "fragment" => "foo" }) end it "should be able to extract without queries" do expect(template.extract(uri2)).to eq({ "host" => "example.com", "segments" => %w(a b c), "one" => nil, "bogus" => nil, "two" => nil, "fragment" => "foo" }) end context "issue #137" do subject { Addressable::Template.new('/path{?page,per_page}') } it "can match empty" do data = subject.extract("/path") expect(data["page"]).to eq(nil) expect(data["per_page"]).to eq(nil) expect(data.keys.sort).to eq(['page', 'per_page']) end it "can match first var" do data = subject.extract("/path?page=1") expect(data["page"]).to eq("1") expect(data["per_page"]).to eq(nil) expect(data.keys.sort).to eq(['page', 'per_page']) end it "can match second var" do data = subject.extract("/path?per_page=1") expect(data["page"]).to eq(nil) expect(data["per_page"]).to eq("1") expect(data.keys.sort).to eq(['page', 'per_page']) end it "can match both vars" do data = subject.extract("/path?page=2&per_page=1") expect(data["page"]).to eq("2") expect(data["per_page"]).to eq("1") expect(data.keys.sort).to eq(['page', 'per_page']) end end end describe "Partial expand with symbols" do context "partial_expand with two simple values" do subject { Addressable::Template.new("http://example.com/{one}/{two}/") } it "builds a new pattern" do expect(subject.partial_expand(:one => "1").pattern).to eq( "http://example.com/1/{two}/" ) end end context "partial_expand query with missing param in middle" do subject { Addressable::Template.new("http://example.com/{?one,two,three}/") } it "builds a new pattern" do expect(subject.partial_expand(:one => "1", :three => "3").pattern).to eq( "http://example.com/?one=1{&two}&three=3/" ) end end context "partial_expand form style query with missing param at beginning" do subject { Addressable::Template.new("http://example.com/{?one,two}/") } it "builds a new pattern" do expect(subject.partial_expand(:two => "2").pattern).to eq( "http://example.com/?two=2{&one}/" ) end end context "partial_expand with query string" do subject { Addressable::Template.new("http://example.com/{?two,one}/") } it "builds a new pattern" do expect(subject.partial_expand(:one => "1").pattern).to eq( "http://example.com/?one=1{&two}/" ) end end context "partial_expand with path operator" do subject { Addressable::Template.new("http://example.com{/one,two}/") } it "builds a new pattern" do expect(subject.partial_expand(:one => "1").pattern).to eq( "http://example.com/1{/two}/" ) end end context "partial expand with unicode values" do subject do Addressable::Template.new("http://example.com/{resource}/{query}/") end it "normalizes unicode by default" do template = subject.partial_expand("query" => "Cafe\u0301") expect(template.pattern).to eq( "http://example.com/{resource}/Caf%C3%A9/" ) end it "does not normalize unicode when byte semantics requested" do template = subject.partial_expand({"query" => "Cafe\u0301"}, nil, false) expect(template.pattern).to eq( "http://example.com/{resource}/Cafe%CC%81/" ) end end end describe "Partial expand with strings" do context "partial_expand with two simple values" do subject { Addressable::Template.new("http://example.com/{one}/{two}/") } it "builds a new pattern" do expect(subject.partial_expand("one" => "1").pattern).to eq( "http://example.com/1/{two}/" ) end end context "partial_expand query with missing param in middle" do subject { Addressable::Template.new("http://example.com/{?one,two,three}/") } it "builds a new pattern" do expect(subject.partial_expand("one" => "1", "three" => "3").pattern).to eq( "http://example.com/?one=1{&two}&three=3/" ) end end context "partial_expand with query string" do subject { Addressable::Template.new("http://example.com/{?two,one}/") } it "builds a new pattern" do expect(subject.partial_expand("one" => "1").pattern).to eq( "http://example.com/?one=1{&two}/" ) end end context "partial_expand with path operator" do subject { Addressable::Template.new("http://example.com{/one,two}/") } it "builds a new pattern" do expect(subject.partial_expand("one" => "1").pattern).to eq( "http://example.com/1{/two}/" ) end end end describe "Expand" do context "expand with unicode values" do subject do Addressable::Template.new("http://example.com/search/{query}/") end it "normalizes unicode by default" do uri = subject.expand("query" => "Cafe\u0301").to_str expect(uri).to eq("http://example.com/search/Caf%C3%A9/") end it "does not normalize unicode when byte semantics requested" do uri = subject.expand({ "query" => "Cafe\u0301" }, nil, false).to_str expect(uri).to eq("http://example.com/search/Cafe%CC%81/") end end context "expand with a processor" do subject { Addressable::Template.new("http://example.com/search/{query}/") } it "processes spaces" do expect(subject.expand({"query" => "an example search query"}, ExampleTwoProcessor).to_str).to eq( "http://example.com/search/an+example+search+query/" ) end it "validates" do expect{ subject.expand({"query" => "Bogus!"}, ExampleTwoProcessor).to_str }.to raise_error(Addressable::Template::InvalidTemplateValueError) end end context "partial_expand query with missing param in middle" do subject { Addressable::Template.new("http://example.com/{?one,two,three}/") } it "builds a new pattern" do
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
true
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/addressable-2.5.2/spec/addressable/net_http_compat_spec.rb
_vendor/ruby/2.6.0/gems/addressable-2.5.2/spec/addressable/net_http_compat_spec.rb
# coding: utf-8 # Copyright (C) Bob Aman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "spec_helper" require "addressable/uri" require "net/http" describe Net::HTTP do it "should be compatible with Addressable" do response_body = Net::HTTP.get(Addressable::URI.parse('http://www.google.com/')) expect(response_body).not_to be_nil end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/addressable-2.5.2/spec/addressable/idna_spec.rb
_vendor/ruby/2.6.0/gems/addressable-2.5.2/spec/addressable/idna_spec.rb
# coding: utf-8 # Copyright (C) Bob Aman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "spec_helper" # Have to use RubyGems to load the idn gem. require "rubygems" require "addressable/idna" shared_examples_for "converting from unicode to ASCII" do it "should convert 'www.google.com' correctly" do expect(Addressable::IDNA.to_ascii("www.google.com")).to eq("www.google.com") end LONG = 'AcinusFallumTrompetumNullunCreditumVisumEstAtCuadLongumEtCefallum.com' it "should convert '#{LONG}' correctly" do expect(Addressable::IDNA.to_ascii(LONG)).to eq(LONG) end it "should convert 'www.詹姆斯.com' correctly" do expect(Addressable::IDNA.to_ascii( "www.詹姆斯.com" )).to eq("www.xn--8ws00zhy3a.com") end it "should convert 'www.Iñtërnâtiônàlizætiøn.com' correctly" do "www.Iñtërnâtiônàlizætiøn.com" expect(Addressable::IDNA.to_ascii( "www.I\xC3\xB1t\xC3\xABrn\xC3\xA2ti\xC3\xB4" + "n\xC3\xA0liz\xC3\xA6ti\xC3\xB8n.com" )).to eq("www.xn--itrntinliztin-vdb0a5exd8ewcye.com") end it "should convert 'www.Iñtërnâtiônàlizætiøn.com' correctly" do expect(Addressable::IDNA.to_ascii( "www.In\xCC\x83te\xCC\x88rna\xCC\x82tio\xCC\x82n" + "a\xCC\x80liz\xC3\xA6ti\xC3\xB8n.com" )).to eq("www.xn--itrntinliztin-vdb0a5exd8ewcye.com") end it "should convert " + "'www.ほんとうにながいわけのわからないどめいんめいのらべるまだながくしないとたりない.w3.mag.keio.ac.jp' " + "correctly" do expect(Addressable::IDNA.to_ascii( "www.\343\201\273\343\202\223\343\201\250\343\201\206\343\201\253\343" + "\201\252\343\201\214\343\201\204\343\202\217\343\201\221\343\201\256" + "\343\202\217\343\201\213\343\202\211\343\201\252\343\201\204\343\201" + "\251\343\202\201\343\201\204\343\202\223\343\202\201\343\201\204\343" + "\201\256\343\202\211\343\201\271\343\202\213\343\201\276\343\201\240" + "\343\201\252\343\201\214\343\201\217\343\201\227\343\201\252\343\201" + "\204\343\201\250\343\201\237\343\202\212\343\201\252\343\201\204." + "w3.mag.keio.ac.jp" )).to eq( "www.xn--n8jaaaaai5bhf7as8fsfk3jnknefdde3" + "fg11amb5gzdb4wi9bya3kc6lra.w3.mag.keio.ac.jp" ) end it "should convert " + "'www.ほんとうにながいわけのわからないどめいんめいのらべるまだながくしないとたりない.w3.mag.keio.ac.jp' " + "correctly" do expect(Addressable::IDNA.to_ascii( "www.\343\201\273\343\202\223\343\201\250\343\201\206\343\201\253\343" + "\201\252\343\201\213\343\202\231\343\201\204\343\202\217\343\201\221" + "\343\201\256\343\202\217\343\201\213\343\202\211\343\201\252\343\201" + "\204\343\201\250\343\202\231\343\202\201\343\201\204\343\202\223\343" + "\202\201\343\201\204\343\201\256\343\202\211\343\201\270\343\202\231" + "\343\202\213\343\201\276\343\201\237\343\202\231\343\201\252\343\201" + "\213\343\202\231\343\201\217\343\201\227\343\201\252\343\201\204\343" + "\201\250\343\201\237\343\202\212\343\201\252\343\201\204." + "w3.mag.keio.ac.jp" )).to eq( "www.xn--n8jaaaaai5bhf7as8fsfk3jnknefdde3" + "fg11amb5gzdb4wi9bya3kc6lra.w3.mag.keio.ac.jp" ) end it "should convert '点心和烤鸭.w3.mag.keio.ac.jp' correctly" do expect(Addressable::IDNA.to_ascii( "点心和烤鸭.w3.mag.keio.ac.jp" )).to eq("xn--0trv4xfvn8el34t.w3.mag.keio.ac.jp") end it "should convert '가각갂갃간갅갆갇갈갉힢힣.com' correctly" do expect(Addressable::IDNA.to_ascii( "가각갂갃간갅갆갇갈갉힢힣.com" )).to eq("xn--o39acdefghijk5883jma.com") end it "should convert " + "'\347\242\274\346\250\231\346\272\226\350" + "\220\254\345\234\213\347\242\274.com' correctly" do expect(Addressable::IDNA.to_ascii( "\347\242\274\346\250\231\346\272\226\350" + "\220\254\345\234\213\347\242\274.com" )).to eq("xn--9cs565brid46mda086o.com") end it "should convert 'リ宠퐱〹.com' correctly" do expect(Addressable::IDNA.to_ascii( "\357\276\230\345\256\240\355\220\261\343\200\271.com" )).to eq("xn--eek174hoxfpr4k.com") end it "should convert 'リ宠퐱卄.com' correctly" do expect(Addressable::IDNA.to_ascii( "\343\203\252\345\256\240\355\220\261\345\215\204.com" )).to eq("xn--eek174hoxfpr4k.com") end it "should convert 'ᆵ' correctly" do expect(Addressable::IDNA.to_ascii( "\341\206\265" )).to eq("xn--4ud") end it "should convert 'ᆵ' correctly" do expect(Addressable::IDNA.to_ascii( "\357\276\257" )).to eq("xn--4ud") end it "should convert '🌹🌹🌹.ws' correctly" do expect(Addressable::IDNA.to_ascii( "\360\237\214\271\360\237\214\271\360\237\214\271.ws" )).to eq("xn--2h8haa.ws") end it "should handle two adjacent '.'s correctly" do expect(Addressable::IDNA.to_ascii( "example..host" )).to eq("example..host") end end shared_examples_for "converting from ASCII to unicode" do LONG = 'AcinusFallumTrompetumNullunCreditumVisumEstAtCuadLongumEtCefallum.com' it "should convert '#{LONG}' correctly" do expect(Addressable::IDNA.to_unicode(LONG)).to eq(LONG) end it "should return the identity conversion when punycode decode fails" do expect(Addressable::IDNA.to_unicode("xn--zckp1cyg1.sblo.jp")).to eq( "xn--zckp1cyg1.sblo.jp") end it "should return the identity conversion when the ACE prefix has no suffix" do expect(Addressable::IDNA.to_unicode("xn--...-")).to eq("xn--...-") end it "should convert 'www.google.com' correctly" do expect(Addressable::IDNA.to_unicode("www.google.com")).to eq( "www.google.com") end it "should convert 'www.詹姆斯.com' correctly" do expect(Addressable::IDNA.to_unicode( "www.xn--8ws00zhy3a.com" )).to eq("www.詹姆斯.com") end it "should convert '詹姆斯.com' correctly" do expect(Addressable::IDNA.to_unicode( "xn--8ws00zhy3a.com" )).to eq("詹姆斯.com") end it "should convert 'www.iñtërnâtiônàlizætiøn.com' correctly" do expect(Addressable::IDNA.to_unicode( "www.xn--itrntinliztin-vdb0a5exd8ewcye.com" )).to eq("www.iñtërnâtiônàlizætiøn.com") end it "should convert 'iñtërnâtiônàlizætiøn.com' correctly" do expect(Addressable::IDNA.to_unicode( "xn--itrntinliztin-vdb0a5exd8ewcye.com" )).to eq("iñtërnâtiônàlizætiøn.com") end it "should convert " + "'www.ほんとうにながいわけのわからないどめいんめいのらべるまだながくしないとたりない.w3.mag.keio.ac.jp' " + "correctly" do expect(Addressable::IDNA.to_unicode( "www.xn--n8jaaaaai5bhf7as8fsfk3jnknefdde3" + "fg11amb5gzdb4wi9bya3kc6lra.w3.mag.keio.ac.jp" )).to eq( "www.ほんとうにながいわけのわからないどめいんめいのらべるまだながくしないとたりない.w3.mag.keio.ac.jp" ) end it "should convert '点心和烤鸭.w3.mag.keio.ac.jp' correctly" do expect(Addressable::IDNA.to_unicode( "xn--0trv4xfvn8el34t.w3.mag.keio.ac.jp" )).to eq("点心和烤鸭.w3.mag.keio.ac.jp") end it "should convert '가각갂갃간갅갆갇갈갉힢힣.com' correctly" do expect(Addressable::IDNA.to_unicode( "xn--o39acdefghijk5883jma.com" )).to eq("가각갂갃간갅갆갇갈갉힢힣.com") end it "should convert " + "'\347\242\274\346\250\231\346\272\226\350" + "\220\254\345\234\213\347\242\274.com' correctly" do expect(Addressable::IDNA.to_unicode( "xn--9cs565brid46mda086o.com" )).to eq( "\347\242\274\346\250\231\346\272\226\350" + "\220\254\345\234\213\347\242\274.com" ) end it "should convert 'リ宠퐱卄.com' correctly" do expect(Addressable::IDNA.to_unicode( "xn--eek174hoxfpr4k.com" )).to eq("\343\203\252\345\256\240\355\220\261\345\215\204.com") end it "should convert 'ᆵ' correctly" do expect(Addressable::IDNA.to_unicode( "xn--4ud" )).to eq("\341\206\265") end it "should convert '🌹🌹🌹.ws' correctly" do expect(Addressable::IDNA.to_unicode( "xn--2h8haa.ws" )).to eq("\360\237\214\271\360\237\214\271\360\237\214\271.ws") end it "should handle two adjacent '.'s correctly" do expect(Addressable::IDNA.to_unicode( "example..host" )).to eq("example..host") end it "should normalize 'string' correctly" do expect(Addressable::IDNA.unicode_normalize_kc(:'string')).to eq("string") expect(Addressable::IDNA.unicode_normalize_kc("string")).to eq("string") end end describe Addressable::IDNA, "when using the pure-Ruby implementation" do before do Addressable.send(:remove_const, :IDNA) load "addressable/idna/pure.rb" end it_should_behave_like "converting from unicode to ASCII" it_should_behave_like "converting from ASCII to unicode" begin require "fiber" it "should not blow up inside fibers" do f = Fiber.new do Addressable.send(:remove_const, :IDNA) load "addressable/idna/pure.rb" end f.resume end rescue LoadError # Fibers aren't supported in this version of Ruby, skip this test. warn('Fibers unsupported.') end end begin require "idn" describe Addressable::IDNA, "when using the native-code implementation" do before do Addressable.send(:remove_const, :IDNA) load "addressable/idna/native.rb" end it_should_behave_like "converting from unicode to ASCII" it_should_behave_like "converting from ASCII to unicode" end rescue LoadError # Cannot test the native implementation without libidn support. warn('Could not load native IDN implementation.') end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/addressable-2.5.2/spec/addressable/uri_spec.rb
_vendor/ruby/2.6.0/gems/addressable-2.5.2/spec/addressable/uri_spec.rb
# coding: utf-8 # Copyright (C) Bob Aman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "spec_helper" require "addressable/uri" require "uri" require "ipaddr" if !"".respond_to?("force_encoding") class String def force_encoding(encoding) @encoding = encoding end def encoding @encoding ||= Encoding::ASCII_8BIT end end class Encoding def initialize(name) @name = name end def to_s return @name end UTF_8 = Encoding.new("UTF-8") ASCII_8BIT = Encoding.new("US-ASCII") end end module Fake module URI class HTTP def initialize(uri) @uri = uri end def to_s return @uri.to_s end alias :to_str :to_s end end end describe Addressable::URI, "when created with a non-numeric port number" do it "should raise an error" do expect(lambda do Addressable::URI.new(:port => "bogus") end).to raise_error(Addressable::URI::InvalidURIError) end end describe Addressable::URI, "when created with a invalid encoded port number" do it "should raise an error" do expect(lambda do Addressable::URI.new(:port => "%eb") end).to raise_error(Addressable::URI::InvalidURIError) end end describe Addressable::URI, "when created with a non-string scheme" do it "should raise an error" do expect(lambda do Addressable::URI.new(:scheme => :bogus) end).to raise_error(TypeError) end end describe Addressable::URI, "when created with a non-string user" do it "should raise an error" do expect(lambda do Addressable::URI.new(:user => :bogus) end).to raise_error(TypeError) end end describe Addressable::URI, "when created with a non-string password" do it "should raise an error" do expect(lambda do Addressable::URI.new(:password => :bogus) end).to raise_error(TypeError) end end describe Addressable::URI, "when created with a non-string userinfo" do it "should raise an error" do expect(lambda do Addressable::URI.new(:userinfo => :bogus) end).to raise_error(TypeError) end end describe Addressable::URI, "when created with a non-string host" do it "should raise an error" do expect(lambda do Addressable::URI.new(:host => :bogus) end).to raise_error(TypeError) end end describe Addressable::URI, "when created with a non-string authority" do it "should raise an error" do expect(lambda do Addressable::URI.new(:authority => :bogus) end).to raise_error(TypeError) end end describe Addressable::URI, "when created with a non-string path" do it "should raise an error" do expect(lambda do Addressable::URI.new(:path => :bogus) end).to raise_error(TypeError) end end describe Addressable::URI, "when created with a non-string query" do it "should raise an error" do expect(lambda do Addressable::URI.new(:query => :bogus) end).to raise_error(TypeError) end end describe Addressable::URI, "when created with a non-string fragment" do it "should raise an error" do expect(lambda do Addressable::URI.new(:fragment => :bogus) end).to raise_error(TypeError) end end describe Addressable::URI, "when created with a scheme but no hierarchical " + "segment" do it "should raise an error" do expect(lambda do Addressable::URI.parse("http:") end).to raise_error(Addressable::URI::InvalidURIError) end end describe Addressable::URI, "quote handling" do describe 'in host name' do it "should raise an error for single quote" do expect(lambda do Addressable::URI.parse("http://local\"host/") end).to raise_error(Addressable::URI::InvalidURIError) end end end describe Addressable::URI, "newline normalization" do it "should not accept newlines in scheme" do expect(lambda do Addressable::URI.parse("ht%0atp://localhost/") end).to raise_error(Addressable::URI::InvalidURIError) end it "should not unescape newline in path" do uri = Addressable::URI.parse("http://localhost/%0a").normalize expect(uri.to_s).to eq("http://localhost/%0A") end it "should not unescape newline in hostname" do uri = Addressable::URI.parse("http://local%0ahost/").normalize expect(uri.to_s).to eq("http://local%0Ahost/") end it "should not unescape newline in username" do uri = Addressable::URI.parse("http://foo%0abar@localhost/").normalize expect(uri.to_s).to eq("http://foo%0Abar@localhost/") end it "should not unescape newline in username" do uri = Addressable::URI.parse("http://example:foo%0abar@example/").normalize expect(uri.to_s).to eq("http://example:foo%0Abar@example/") end it "should not accept newline in hostname" do uri = Addressable::URI.parse("http://localhost/") expect(lambda do uri.host = "local\nhost" end).to raise_error(Addressable::URI::InvalidURIError) end end describe Addressable::URI, "when created with ambiguous path" do it "should raise an error" do expect(lambda do Addressable::URI.parse("::http") end).to raise_error(Addressable::URI::InvalidURIError) end end describe Addressable::URI, "when created with an invalid host" do it "should raise an error" do expect(lambda do Addressable::URI.new(:host => "<invalid>") end).to raise_error(Addressable::URI::InvalidURIError) end end describe Addressable::URI, "when created with a host consisting of " + "sub-delims characters" do it "should not raise an error" do expect(lambda do Addressable::URI.new( :host => Addressable::URI::CharacterClasses::SUB_DELIMS.gsub(/\\/, '') ) end).not_to raise_error end end describe Addressable::URI, "when created with a host consisting of " + "unreserved characters" do it "should not raise an error" do expect(lambda do Addressable::URI.new( :host => Addressable::URI::CharacterClasses::UNRESERVED.gsub(/\\/, '') ) end).not_to raise_error end end describe Addressable::URI, "when created from nil components" do before do @uri = Addressable::URI.new end it "should have a nil site value" do expect(@uri.site).to eq(nil) end it "should have an empty path" do expect(@uri.path).to eq("") end it "should be an empty uri" do expect(@uri.to_s).to eq("") end it "should have a nil default port" do expect(@uri.default_port).to eq(nil) end it "should be empty" do expect(@uri).to be_empty end it "should raise an error if the scheme is set to whitespace" do expect(lambda do @uri.scheme = "\t \n" end).to raise_error(Addressable::URI::InvalidURIError) end it "should raise an error if the scheme is set to all digits" do expect(lambda do @uri.scheme = "123" end).to raise_error(Addressable::URI::InvalidURIError) end it "should raise an error if the scheme begins with a digit" do expect(lambda do @uri.scheme = "1scheme" end).to raise_error(Addressable::URI::InvalidURIError) end it "should raise an error if the scheme begins with a plus" do expect(lambda do @uri.scheme = "+scheme" end).to raise_error(Addressable::URI::InvalidURIError) end it "should raise an error if the scheme begins with a dot" do expect(lambda do @uri.scheme = ".scheme" end).to raise_error(Addressable::URI::InvalidURIError) end it "should raise an error if the scheme begins with a dash" do expect(lambda do @uri.scheme = "-scheme" end).to raise_error(Addressable::URI::InvalidURIError) end it "should raise an error if the scheme contains an illegal character" do expect(lambda do @uri.scheme = "scheme!" end).to raise_error(Addressable::URI::InvalidURIError) end it "should raise an error if the scheme contains whitespace" do expect(lambda do @uri.scheme = "sch eme" end).to raise_error(Addressable::URI::InvalidURIError) end it "should raise an error if the scheme contains a newline" do expect(lambda do @uri.scheme = "sch\neme" end).to raise_error(Addressable::URI::InvalidURIError) end it "should raise an error if set into an invalid state" do expect(lambda do @uri.user = "user" end).to raise_error(Addressable::URI::InvalidURIError) end it "should raise an error if set into an invalid state" do expect(lambda do @uri.password = "pass" end).to raise_error(Addressable::URI::InvalidURIError) end it "should raise an error if set into an invalid state" do expect(lambda do @uri.scheme = "http" @uri.fragment = "fragment" end).to raise_error(Addressable::URI::InvalidURIError) end it "should raise an error if set into an invalid state" do expect(lambda do @uri.fragment = "fragment" @uri.scheme = "http" end).to raise_error(Addressable::URI::InvalidURIError) end end describe Addressable::URI, "when initialized from individual components" do before do @uri = Addressable::URI.new( :scheme => "http", :user => "user", :password => "password", :host => "example.com", :port => 8080, :path => "/path", :query => "query=value", :fragment => "fragment" ) end it "returns 'http' for #scheme" do expect(@uri.scheme).to eq("http") end it "returns 'http' for #normalized_scheme" do expect(@uri.normalized_scheme).to eq("http") end it "returns 'user' for #user" do expect(@uri.user).to eq("user") end it "returns 'user' for #normalized_user" do expect(@uri.normalized_user).to eq("user") end it "returns 'password' for #password" do expect(@uri.password).to eq("password") end it "returns 'password' for #normalized_password" do expect(@uri.normalized_password).to eq("password") end it "returns 'user:password' for #userinfo" do expect(@uri.userinfo).to eq("user:password") end it "returns 'user:password' for #normalized_userinfo" do expect(@uri.normalized_userinfo).to eq("user:password") end it "returns 'example.com' for #host" do expect(@uri.host).to eq("example.com") end it "returns 'example.com' for #normalized_host" do expect(@uri.normalized_host).to eq("example.com") end it "returns 'com' for #tld" do expect(@uri.tld).to eq("com") end it "returns 'user:password@example.com:8080' for #authority" do expect(@uri.authority).to eq("user:password@example.com:8080") end it "returns 'user:password@example.com:8080' for #normalized_authority" do expect(@uri.normalized_authority).to eq("user:password@example.com:8080") end it "returns 8080 for #port" do expect(@uri.port).to eq(8080) end it "returns 8080 for #normalized_port" do expect(@uri.normalized_port).to eq(8080) end it "returns 80 for #default_port" do expect(@uri.default_port).to eq(80) end it "returns 'http://user:password@example.com:8080' for #site" do expect(@uri.site).to eq("http://user:password@example.com:8080") end it "returns 'http://user:password@example.com:8080' for #normalized_site" do expect(@uri.normalized_site).to eq("http://user:password@example.com:8080") end it "returns '/path' for #path" do expect(@uri.path).to eq("/path") end it "returns '/path' for #normalized_path" do expect(@uri.normalized_path).to eq("/path") end it "returns 'query=value' for #query" do expect(@uri.query).to eq("query=value") end it "returns 'query=value' for #normalized_query" do expect(@uri.normalized_query).to eq("query=value") end it "returns 'fragment' for #fragment" do expect(@uri.fragment).to eq("fragment") end it "returns 'fragment' for #normalized_fragment" do expect(@uri.normalized_fragment).to eq("fragment") end it "returns #hash" do expect(@uri.hash).not_to be nil end it "returns #to_s" do expect(@uri.to_s).to eq( "http://user:password@example.com:8080/path?query=value#fragment" ) end it "should not be empty" do expect(@uri).not_to be_empty end it "should not be frozen" do expect(@uri).not_to be_frozen end it "should allow destructive operations" do expect { @uri.normalize! }.not_to raise_error end end describe Addressable::URI, "when initialized from " + "frozen individual components" do before do @uri = Addressable::URI.new( :scheme => "http".freeze, :user => "user".freeze, :password => "password".freeze, :host => "example.com".freeze, :port => "8080".freeze, :path => "/path".freeze, :query => "query=value".freeze, :fragment => "fragment".freeze ) end it "returns 'http' for #scheme" do expect(@uri.scheme).to eq("http") end it "returns 'http' for #normalized_scheme" do expect(@uri.normalized_scheme).to eq("http") end it "returns 'user' for #user" do expect(@uri.user).to eq("user") end it "returns 'user' for #normalized_user" do expect(@uri.normalized_user).to eq("user") end it "returns 'password' for #password" do expect(@uri.password).to eq("password") end it "returns 'password' for #normalized_password" do expect(@uri.normalized_password).to eq("password") end it "returns 'user:password' for #userinfo" do expect(@uri.userinfo).to eq("user:password") end it "returns 'user:password' for #normalized_userinfo" do expect(@uri.normalized_userinfo).to eq("user:password") end it "returns 'example.com' for #host" do expect(@uri.host).to eq("example.com") end it "returns 'example.com' for #normalized_host" do expect(@uri.normalized_host).to eq("example.com") end it "returns 'user:password@example.com:8080' for #authority" do expect(@uri.authority).to eq("user:password@example.com:8080") end it "returns 'user:password@example.com:8080' for #normalized_authority" do expect(@uri.normalized_authority).to eq("user:password@example.com:8080") end it "returns 8080 for #port" do expect(@uri.port).to eq(8080) end it "returns 8080 for #normalized_port" do expect(@uri.normalized_port).to eq(8080) end it "returns 80 for #default_port" do expect(@uri.default_port).to eq(80) end it "returns 'http://user:password@example.com:8080' for #site" do expect(@uri.site).to eq("http://user:password@example.com:8080") end it "returns 'http://user:password@example.com:8080' for #normalized_site" do expect(@uri.normalized_site).to eq("http://user:password@example.com:8080") end it "returns '/path' for #path" do expect(@uri.path).to eq("/path") end it "returns '/path' for #normalized_path" do expect(@uri.normalized_path).to eq("/path") end it "returns 'query=value' for #query" do expect(@uri.query).to eq("query=value") end it "returns 'query=value' for #normalized_query" do expect(@uri.normalized_query).to eq("query=value") end it "returns 'fragment' for #fragment" do expect(@uri.fragment).to eq("fragment") end it "returns 'fragment' for #normalized_fragment" do expect(@uri.normalized_fragment).to eq("fragment") end it "returns #hash" do expect(@uri.hash).not_to be nil end it "returns #to_s" do expect(@uri.to_s).to eq( "http://user:password@example.com:8080/path?query=value#fragment" ) end it "should not be empty" do expect(@uri).not_to be_empty end it "should not be frozen" do expect(@uri).not_to be_frozen end it "should allow destructive operations" do expect { @uri.normalize! }.not_to raise_error end end describe Addressable::URI, "when parsed from a frozen string" do before do @uri = Addressable::URI.parse( "http://user:password@example.com:8080/path?query=value#fragment".freeze ) end it "returns 'http' for #scheme" do expect(@uri.scheme).to eq("http") end it "returns 'http' for #normalized_scheme" do expect(@uri.normalized_scheme).to eq("http") end it "returns 'user' for #user" do expect(@uri.user).to eq("user") end it "returns 'user' for #normalized_user" do expect(@uri.normalized_user).to eq("user") end it "returns 'password' for #password" do expect(@uri.password).to eq("password") end it "returns 'password' for #normalized_password" do expect(@uri.normalized_password).to eq("password") end it "returns 'user:password' for #userinfo" do expect(@uri.userinfo).to eq("user:password") end it "returns 'user:password' for #normalized_userinfo" do expect(@uri.normalized_userinfo).to eq("user:password") end it "returns 'example.com' for #host" do expect(@uri.host).to eq("example.com") end it "returns 'example.com' for #normalized_host" do expect(@uri.normalized_host).to eq("example.com") end it "returns 'user:password@example.com:8080' for #authority" do expect(@uri.authority).to eq("user:password@example.com:8080") end it "returns 'user:password@example.com:8080' for #normalized_authority" do expect(@uri.normalized_authority).to eq("user:password@example.com:8080") end it "returns 8080 for #port" do expect(@uri.port).to eq(8080) end it "returns 8080 for #normalized_port" do expect(@uri.normalized_port).to eq(8080) end it "returns 80 for #default_port" do expect(@uri.default_port).to eq(80) end it "returns 'http://user:password@example.com:8080' for #site" do expect(@uri.site).to eq("http://user:password@example.com:8080") end it "returns 'http://user:password@example.com:8080' for #normalized_site" do expect(@uri.normalized_site).to eq("http://user:password@example.com:8080") end it "returns '/path' for #path" do expect(@uri.path).to eq("/path") end it "returns '/path' for #normalized_path" do expect(@uri.normalized_path).to eq("/path") end it "returns 'query=value' for #query" do expect(@uri.query).to eq("query=value") end it "returns 'query=value' for #normalized_query" do expect(@uri.normalized_query).to eq("query=value") end it "returns 'fragment' for #fragment" do expect(@uri.fragment).to eq("fragment") end it "returns 'fragment' for #normalized_fragment" do expect(@uri.normalized_fragment).to eq("fragment") end it "returns #hash" do expect(@uri.hash).not_to be nil end it "returns #to_s" do expect(@uri.to_s).to eq( "http://user:password@example.com:8080/path?query=value#fragment" ) end it "should not be empty" do expect(@uri).not_to be_empty end it "should not be frozen" do expect(@uri).not_to be_frozen end it "should allow destructive operations" do expect { @uri.normalize! }.not_to raise_error end end describe Addressable::URI, "when frozen" do before do @uri = Addressable::URI.new.freeze end it "returns nil for #scheme" do expect(@uri.scheme).to eq(nil) end it "returns nil for #normalized_scheme" do expect(@uri.normalized_scheme).to eq(nil) end it "returns nil for #user" do expect(@uri.user).to eq(nil) end it "returns nil for #normalized_user" do expect(@uri.normalized_user).to eq(nil) end it "returns nil for #password" do expect(@uri.password).to eq(nil) end it "returns nil for #normalized_password" do expect(@uri.normalized_password).to eq(nil) end it "returns nil for #userinfo" do expect(@uri.userinfo).to eq(nil) end it "returns nil for #normalized_userinfo" do expect(@uri.normalized_userinfo).to eq(nil) end it "returns nil for #host" do expect(@uri.host).to eq(nil) end it "returns nil for #normalized_host" do expect(@uri.normalized_host).to eq(nil) end it "returns nil for #authority" do expect(@uri.authority).to eq(nil) end it "returns nil for #normalized_authority" do expect(@uri.normalized_authority).to eq(nil) end it "returns nil for #port" do expect(@uri.port).to eq(nil) end it "returns nil for #normalized_port" do expect(@uri.normalized_port).to eq(nil) end it "returns nil for #default_port" do expect(@uri.default_port).to eq(nil) end it "returns nil for #site" do expect(@uri.site).to eq(nil) end it "returns nil for #normalized_site" do expect(@uri.normalized_site).to eq(nil) end it "returns '' for #path" do expect(@uri.path).to eq('') end it "returns '' for #normalized_path" do expect(@uri.normalized_path).to eq('') end it "returns nil for #query" do expect(@uri.query).to eq(nil) end it "returns nil for #normalized_query" do expect(@uri.normalized_query).to eq(nil) end it "returns nil for #fragment" do expect(@uri.fragment).to eq(nil) end it "returns nil for #normalized_fragment" do expect(@uri.normalized_fragment).to eq(nil) end it "returns #hash" do expect(@uri.hash).not_to be nil end it "returns #to_s" do expect(@uri.to_s).to eq('') end it "should be empty" do expect(@uri).to be_empty end it "should be frozen" do expect(@uri).to be_frozen end it "should not be frozen after duping" do expect(@uri.dup).not_to be_frozen end it "should not allow destructive operations" do expect { @uri.normalize! }.to raise_error { |error| expect(error.message).to match(/can't modify frozen/) expect(error).to satisfy { |e| RuntimeError === e || TypeError === e } } end end describe Addressable::URI, "when frozen" do before do @uri = Addressable::URI.parse( "HTTP://example.com.:%38%30/%70a%74%68?a=%31#1%323" ).freeze end it "returns 'HTTP' for #scheme" do expect(@uri.scheme).to eq("HTTP") end it "returns 'http' for #normalized_scheme" do expect(@uri.normalized_scheme).to eq("http") expect(@uri.normalize.scheme).to eq("http") end it "returns nil for #user" do expect(@uri.user).to eq(nil) end it "returns nil for #normalized_user" do expect(@uri.normalized_user).to eq(nil) end it "returns nil for #password" do expect(@uri.password).to eq(nil) end it "returns nil for #normalized_password" do expect(@uri.normalized_password).to eq(nil) end it "returns nil for #userinfo" do expect(@uri.userinfo).to eq(nil) end it "returns nil for #normalized_userinfo" do expect(@uri.normalized_userinfo).to eq(nil) end it "returns 'example.com.' for #host" do expect(@uri.host).to eq("example.com.") end it "returns nil for #normalized_host" do expect(@uri.normalized_host).to eq("example.com") expect(@uri.normalize.host).to eq("example.com") end it "returns 'example.com.:80' for #authority" do expect(@uri.authority).to eq("example.com.:80") end it "returns 'example.com:80' for #normalized_authority" do expect(@uri.normalized_authority).to eq("example.com") expect(@uri.normalize.authority).to eq("example.com") end it "returns 80 for #port" do expect(@uri.port).to eq(80) end it "returns nil for #normalized_port" do expect(@uri.normalized_port).to eq(nil) expect(@uri.normalize.port).to eq(nil) end it "returns 80 for #default_port" do expect(@uri.default_port).to eq(80) end it "returns 'HTTP://example.com.:80' for #site" do expect(@uri.site).to eq("HTTP://example.com.:80") end it "returns 'http://example.com' for #normalized_site" do expect(@uri.normalized_site).to eq("http://example.com") expect(@uri.normalize.site).to eq("http://example.com") end it "returns '/%70a%74%68' for #path" do expect(@uri.path).to eq("/%70a%74%68") end it "returns '/path' for #normalized_path" do expect(@uri.normalized_path).to eq("/path") expect(@uri.normalize.path).to eq("/path") end it "returns 'a=%31' for #query" do expect(@uri.query).to eq("a=%31") end it "returns 'a=1' for #normalized_query" do expect(@uri.normalized_query).to eq("a=1") expect(@uri.normalize.query).to eq("a=1") end it "returns '/%70a%74%68?a=%31' for #request_uri" do expect(@uri.request_uri).to eq("/%70a%74%68?a=%31") end it "returns '1%323' for #fragment" do expect(@uri.fragment).to eq("1%323") end it "returns '123' for #normalized_fragment" do expect(@uri.normalized_fragment).to eq("123") expect(@uri.normalize.fragment).to eq("123") end it "returns #hash" do expect(@uri.hash).not_to be nil end it "returns #to_s" do expect(@uri.to_s).to eq('HTTP://example.com.:80/%70a%74%68?a=%31#1%323') expect(@uri.normalize.to_s).to eq('http://example.com/path?a=1#123') end it "should not be empty" do expect(@uri).not_to be_empty end it "should be frozen" do expect(@uri).to be_frozen end it "should not be frozen after duping" do expect(@uri.dup).not_to be_frozen end it "should not allow destructive operations" do expect { @uri.normalize! }.to raise_error { |error| expect(error.message).to match(/can't modify frozen/) expect(error).to satisfy { |e| RuntimeError === e || TypeError === e } } end end describe Addressable::URI, "when created from string components" do before do @uri = Addressable::URI.new( :scheme => "http", :host => "example.com" ) end it "should have a site value of 'http://example.com'" do expect(@uri.site).to eq("http://example.com") end it "should be equal to the equivalent parsed URI" do expect(@uri).to eq(Addressable::URI.parse("http://example.com")) end it "should raise an error if invalid components omitted" do expect(lambda do @uri.omit(:bogus) end).to raise_error(ArgumentError) expect(lambda do @uri.omit(:scheme, :bogus, :path) end).to raise_error(ArgumentError) end end describe Addressable::URI, "when created with a nil host but " + "non-nil authority components" do it "should raise an error" do expect(lambda do Addressable::URI.new(:user => "user", :password => "pass", :port => 80) end).to raise_error(Addressable::URI::InvalidURIError) end end describe Addressable::URI, "when created with both an authority and a user" do it "should raise an error" do expect(lambda do Addressable::URI.new( :user => "user", :authority => "user@example.com:80" ) end).to raise_error(ArgumentError) end end describe Addressable::URI, "when created with an authority and no port" do before do @uri = Addressable::URI.new(:authority => "user@example.com") end it "should not infer a port" do expect(@uri.port).to eq(nil) expect(@uri.default_port).to eq(nil) expect(@uri.inferred_port).to eq(nil) end it "should have a site value of '//user@example.com'" do expect(@uri.site).to eq("//user@example.com") end it "should have a 'null' origin" do expect(@uri.origin).to eq('null') end end describe Addressable::URI, "when created with a host with trailing dots" do before do @uri = Addressable::URI.new(:authority => "example...") end it "should have a stable normalized form" do expect(@uri.normalize.normalize.normalize.host).to eq( @uri.normalize.host ) end end describe Addressable::URI, "when created with a host with a backslash" do it "should raise an error" do expect(lambda do Addressable::URI.new(:authority => "example\\example") end).to raise_error(Addressable::URI::InvalidURIError) end end describe Addressable::URI, "when created with a host with a slash" do it "should raise an error" do expect(lambda do Addressable::URI.new(:authority => "example/example") end).to raise_error(Addressable::URI::InvalidURIError) end end describe Addressable::URI, "when created with a host with a space" do it "should raise an error" do expect(lambda do Addressable::URI.new(:authority => "example example") end).to raise_error(Addressable::URI::InvalidURIError) end end describe Addressable::URI, "when created with both a userinfo and a user" do it "should raise an error" do expect(lambda do Addressable::URI.new(:user => "user", :userinfo => "user:pass") end).to raise_error(ArgumentError) end end describe Addressable::URI, "when created with a path that hasn't been " + "prefixed with a '/' but a host specified" do before do @uri = Addressable::URI.new( :scheme => "http", :host => "example.com", :path => "path" ) end it "should prefix a '/' to the path" do expect(@uri).to eq(Addressable::URI.parse("http://example.com/path")) end it "should have a site value of 'http://example.com'" do expect(@uri.site).to eq("http://example.com") end it "should have an origin of 'http://example.com" do expect(@uri.origin).to eq('http://example.com') end end describe Addressable::URI, "when created with a path that hasn't been " + "prefixed with a '/' but no host specified" do before do @uri = Addressable::URI.new( :scheme => "http", :path => "path" ) end it "should not prefix a '/' to the path" do expect(@uri).to eq(Addressable::URI.parse("http:path")) end it "should have a site value of 'http:'" do expect(@uri.site).to eq("http:") end it "should have a 'null' origin" do expect(@uri.origin).to eq('null') end end describe Addressable::URI, "when parsed from an Addressable::URI object" do it "should not have unexpected side-effects" do original_uri = Addressable::URI.parse("http://example.com/") new_uri = Addressable::URI.parse(original_uri) new_uri.host = 'www.example.com' expect(new_uri.host).to eq('www.example.com') expect(new_uri.to_s).to eq('http://www.example.com/') expect(original_uri.host).to eq('example.com') expect(original_uri.to_s).to eq('http://example.com/') end it "should not have unexpected side-effects" do original_uri = Addressable::URI.parse("http://example.com/") new_uri = Addressable::URI.heuristic_parse(original_uri) new_uri.host = 'www.example.com' expect(new_uri.host).to eq('www.example.com') expect(new_uri.to_s).to eq('http://www.example.com/') expect(original_uri.host).to eq('example.com') expect(original_uri.to_s).to eq('http://example.com/') end it "should not have unexpected side-effects" do original_uri = Addressable::URI.parse("http://example.com/") new_uri = Addressable::URI.parse(original_uri) new_uri.origin = 'https://www.example.com:8080' expect(new_uri.host).to eq('www.example.com') expect(new_uri.to_s).to eq('https://www.example.com:8080/') expect(original_uri.host).to eq('example.com') expect(original_uri.to_s).to eq('http://example.com/') end it "should not have unexpected side-effects" do original_uri = Addressable::URI.parse("http://example.com/") new_uri = Addressable::URI.heuristic_parse(original_uri) new_uri.origin = 'https://www.example.com:8080' expect(new_uri.host).to eq('www.example.com') expect(new_uri.to_s).to eq('https://www.example.com:8080/') expect(original_uri.host).to eq('example.com') expect(original_uri.to_s).to eq('http://example.com/') end end describe Addressable::URI, "when parsed from something that looks " + "like a URI object" do it "should parse without error" do uri = Addressable::URI.parse(Fake::URI::HTTP.new("http://example.com/")) expect(lambda do Addressable::URI.parse(uri) end).not_to raise_error end end describe Addressable::URI, "when parsed from a standard library URI object" do it "should parse without error" do uri = Addressable::URI.parse(URI.parse("http://example.com/")) expect(lambda do Addressable::URI.parse(uri) end).not_to raise_error end end describe Addressable::URI, "when parsed from ''" do before do @uri = Addressable::URI.parse("") end it "should have no scheme" do expect(@uri.scheme).to eq(nil) end it "should not be considered to be ip-based" do expect(@uri).not_to be_ip_based end it "should have a path of ''" do expect(@uri.path).to eq("") end it "should have a request URI of '/'" do expect(@uri.request_uri).to eq("/") end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
true
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/addressable-2.5.2/lib/addressable.rb
_vendor/ruby/2.6.0/gems/addressable-2.5.2/lib/addressable.rb
require 'addressable/uri' require 'addressable/template'
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/addressable-2.5.2/lib/addressable/version.rb
_vendor/ruby/2.6.0/gems/addressable-2.5.2/lib/addressable/version.rb
# encoding:utf-8 #-- # Copyright (C) Bob Aman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #++ # Used to prevent the class/module from being loaded more than once if !defined?(Addressable::VERSION) module Addressable module VERSION MAJOR = 2 MINOR = 5 TINY = 2 STRING = [MAJOR, MINOR, TINY].join('.') end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/addressable-2.5.2/lib/addressable/uri.rb
_vendor/ruby/2.6.0/gems/addressable-2.5.2/lib/addressable/uri.rb
# encoding:utf-8 #-- # Copyright (C) Bob Aman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #++ require "addressable/version" require "addressable/idna" require "public_suffix" ## # Addressable is a library for processing links and URIs. module Addressable ## # This is an implementation of a URI parser based on # <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>, # <a href="http://www.ietf.org/rfc/rfc3987.txt">RFC 3987</a>. class URI ## # Raised if something other than a uri is supplied. class InvalidURIError < StandardError end ## # Container for the character classes specified in # <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>. module CharacterClasses ALPHA = "a-zA-Z" DIGIT = "0-9" GEN_DELIMS = "\\:\\/\\?\\#\\[\\]\\@" SUB_DELIMS = "\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=" RESERVED = GEN_DELIMS + SUB_DELIMS UNRESERVED = ALPHA + DIGIT + "\\-\\.\\_\\~" PCHAR = UNRESERVED + SUB_DELIMS + "\\:\\@" SCHEME = ALPHA + DIGIT + "\\-\\+\\." HOST = UNRESERVED + SUB_DELIMS + "\\[\\:\\]" AUTHORITY = PCHAR PATH = PCHAR + "\\/" QUERY = PCHAR + "\\/\\?" FRAGMENT = PCHAR + "\\/\\?" end SLASH = '/' EMPTY_STR = '' URIREGEX = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/ PORT_MAPPING = { "http" => 80, "https" => 443, "ftp" => 21, "tftp" => 69, "sftp" => 22, "ssh" => 22, "svn+ssh" => 22, "telnet" => 23, "nntp" => 119, "gopher" => 70, "wais" => 210, "ldap" => 389, "prospero" => 1525 } ## # Returns a URI object based on the parsed string. # # @param [String, Addressable::URI, #to_str] uri # The URI string to parse. # No parsing is performed if the object is already an # <code>Addressable::URI</code>. # # @return [Addressable::URI] The parsed URI. def self.parse(uri) # If we were given nil, return nil. return nil unless uri # If a URI object is passed, just return itself. return uri.dup if uri.kind_of?(self) # If a URI object of the Ruby standard library variety is passed, # convert it to a string, then parse the string. # We do the check this way because we don't want to accidentally # cause a missing constant exception to be thrown. if uri.class.name =~ /^URI\b/ uri = uri.to_s end # Otherwise, convert to a String begin uri = uri.to_str rescue TypeError, NoMethodError raise TypeError, "Can't convert #{uri.class} into String." end if not uri.is_a? String # This Regexp supplied as an example in RFC 3986, and it works great. scan = uri.scan(URIREGEX) fragments = scan[0] scheme = fragments[1] authority = fragments[3] path = fragments[4] query = fragments[6] fragment = fragments[8] user = nil password = nil host = nil port = nil if authority != nil # The Regexp above doesn't split apart the authority. userinfo = authority[/^([^\[\]]*)@/, 1] if userinfo != nil user = userinfo.strip[/^([^:]*):?/, 1] password = userinfo.strip[/:(.*)$/, 1] end host = authority.gsub( /^([^\[\]]*)@/, EMPTY_STR ).gsub( /:([^:@\[\]]*?)$/, EMPTY_STR ) port = authority[/:([^:@\[\]]*?)$/, 1] end if port == EMPTY_STR port = nil end return new( :scheme => scheme, :user => user, :password => password, :host => host, :port => port, :path => path, :query => query, :fragment => fragment ) end ## # Converts an input to a URI. The input does not have to be a valid # URI — the method will use heuristics to guess what URI was intended. # This is not standards-compliant, merely user-friendly. # # @param [String, Addressable::URI, #to_str] uri # The URI string to parse. # No parsing is performed if the object is already an # <code>Addressable::URI</code>. # @param [Hash] hints # A <code>Hash</code> of hints to the heuristic parser. # Defaults to <code>{:scheme => "http"}</code>. # # @return [Addressable::URI] The parsed URI. def self.heuristic_parse(uri, hints={}) # If we were given nil, return nil. return nil unless uri # If a URI object is passed, just return itself. return uri.dup if uri.kind_of?(self) # If a URI object of the Ruby standard library variety is passed, # convert it to a string, then parse the string. # We do the check this way because we don't want to accidentally # cause a missing constant exception to be thrown. if uri.class.name =~ /^URI\b/ uri = uri.to_s end if !uri.respond_to?(:to_str) raise TypeError, "Can't convert #{uri.class} into String." end # Otherwise, convert to a String uri = uri.to_str.dup.strip hints = { :scheme => "http" }.merge(hints) case uri when /^http:\/+/ uri.gsub!(/^http:\/+/, "http://") when /^https:\/+/ uri.gsub!(/^https:\/+/, "https://") when /^feed:\/+http:\/+/ uri.gsub!(/^feed:\/+http:\/+/, "feed:http://") when /^feed:\/+/ uri.gsub!(/^feed:\/+/, "feed://") when /^file:\/+/ uri.gsub!(/^file:\/+/, "file:///") when /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/ uri.gsub!(/^/, hints[:scheme] + "://") end match = uri.match(URIREGEX) fragments = match.captures authority = fragments[3] if authority && authority.length > 0 new_authority = authority.gsub(/\\/, '/').gsub(/ /, '%20') # NOTE: We want offset 4, not 3! offset = match.offset(4) uri[offset[0]...offset[1]] = new_authority end parsed = self.parse(uri) if parsed.scheme =~ /^[^\/?#\.]+\.[^\/?#]+$/ parsed = self.parse(hints[:scheme] + "://" + uri) end if parsed.path.include?(".") new_host = parsed.path[/^([^\/]+\.[^\/]*)/, 1] if new_host parsed.defer_validation do new_path = parsed.path.gsub( Regexp.new("^" + Regexp.escape(new_host)), EMPTY_STR) parsed.host = new_host parsed.path = new_path parsed.scheme = hints[:scheme] unless parsed.scheme end end end return parsed end ## # Converts a path to a file scheme URI. If the path supplied is # relative, it will be returned as a relative URI. If the path supplied # is actually a non-file URI, it will parse the URI as if it had been # parsed with <code>Addressable::URI.parse</code>. Handles all of the # various Microsoft-specific formats for specifying paths. # # @param [String, Addressable::URI, #to_str] path # Typically a <code>String</code> path to a file or directory, but # will return a sensible return value if an absolute URI is supplied # instead. # # @return [Addressable::URI] # The parsed file scheme URI or the original URI if some other URI # scheme was provided. # # @example # base = Addressable::URI.convert_path("/absolute/path/") # uri = Addressable::URI.convert_path("relative/path") # (base + uri).to_s # #=> "file:///absolute/path/relative/path" # # Addressable::URI.convert_path( # "c:\\windows\\My Documents 100%20\\foo.txt" # ).to_s # #=> "file:///c:/windows/My%20Documents%20100%20/foo.txt" # # Addressable::URI.convert_path("http://example.com/").to_s # #=> "http://example.com/" def self.convert_path(path) # If we were given nil, return nil. return nil unless path # If a URI object is passed, just return itself. return path if path.kind_of?(self) if !path.respond_to?(:to_str) raise TypeError, "Can't convert #{path.class} into String." end # Otherwise, convert to a String path = path.to_str.strip path.gsub!(/^file:\/?\/?/, EMPTY_STR) if path =~ /^file:\/?\/?/ path = SLASH + path if path =~ /^([a-zA-Z])[\|:]/ uri = self.parse(path) if uri.scheme == nil # Adjust windows-style uris uri.path.gsub!(/^\/?([a-zA-Z])[\|:][\\\/]/) do "/#{$1.downcase}:/" end uri.path.gsub!(/\\/, SLASH) if File.exist?(uri.path) && File.stat(uri.path).directory? uri.path.gsub!(/\/$/, EMPTY_STR) uri.path = uri.path + '/' end # If the path is absolute, set the scheme and host. if uri.path =~ /^\// uri.scheme = "file" uri.host = EMPTY_STR end uri.normalize! end return uri end ## # Joins several URIs together. # # @param [String, Addressable::URI, #to_str] *uris # The URIs to join. # # @return [Addressable::URI] The joined URI. # # @example # base = "http://example.com/" # uri = Addressable::URI.parse("relative/path") # Addressable::URI.join(base, uri) # #=> #<Addressable::URI:0xcab390 URI:http://example.com/relative/path> def self.join(*uris) uri_objects = uris.collect do |uri| if !uri.respond_to?(:to_str) raise TypeError, "Can't convert #{uri.class} into String." end uri.kind_of?(self) ? uri : self.parse(uri.to_str) end result = uri_objects.shift.dup for uri in uri_objects result.join!(uri) end return result end ## # Percent encodes a URI component. # # @param [String, #to_str] component The URI component to encode. # # @param [String, Regexp] character_class # The characters which are not percent encoded. If a <code>String</code> # is passed, the <code>String</code> must be formatted as a regular # expression character class. (Do not include the surrounding square # brackets.) For example, <code>"b-zB-Z0-9"</code> would cause # everything but the letters 'b' through 'z' and the numbers '0' through # '9' to be percent encoded. If a <code>Regexp</code> is passed, the # value <code>/[^b-zB-Z0-9]/</code> would have the same effect. A set of # useful <code>String</code> values may be found in the # <code>Addressable::URI::CharacterClasses</code> module. The default # value is the reserved plus unreserved character classes specified in # <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>. # # @param [Regexp] upcase_encoded # A string of characters that may already be percent encoded, and whose # encodings should be upcased. This allows normalization of percent # encodings for characters not included in the # <code>character_class</code>. # # @return [String] The encoded component. # # @example # Addressable::URI.encode_component("simple/example", "b-zB-Z0-9") # => "simple%2Fex%61mple" # Addressable::URI.encode_component("simple/example", /[^b-zB-Z0-9]/) # => "simple%2Fex%61mple" # Addressable::URI.encode_component( # "simple/example", Addressable::URI::CharacterClasses::UNRESERVED # ) # => "simple%2Fexample" def self.encode_component(component, character_class= CharacterClasses::RESERVED + CharacterClasses::UNRESERVED, upcase_encoded='') return nil if component.nil? begin if component.kind_of?(Symbol) || component.kind_of?(Numeric) || component.kind_of?(TrueClass) || component.kind_of?(FalseClass) component = component.to_s else component = component.to_str end rescue TypeError, NoMethodError raise TypeError, "Can't convert #{component.class} into String." end if !component.is_a? String if ![String, Regexp].include?(character_class.class) raise TypeError, "Expected String or Regexp, got #{character_class.inspect}" end if character_class.kind_of?(String) character_class = /[^#{character_class}]/ end # We can't perform regexps on invalid UTF sequences, but # here we need to, so switch to ASCII. component = component.dup component.force_encoding(Encoding::ASCII_8BIT) # Avoiding gsub! because there are edge cases with frozen strings component = component.gsub(character_class) do |sequence| (sequence.unpack('C*').map { |c| "%" + ("%02x" % c).upcase }).join end if upcase_encoded.length > 0 component = component.gsub(/%(#{upcase_encoded.chars.map do |char| char.unpack('C*').map { |c| '%02x' % c }.join end.join('|')})/i) { |s| s.upcase } end return component end class << self alias_method :encode_component, :encode_component end ## # Unencodes any percent encoded characters within a URI component. # This method may be used for unencoding either components or full URIs, # however, it is recommended to use the <code>unencode_component</code> # alias when unencoding components. # # @param [String, Addressable::URI, #to_str] uri # The URI or component to unencode. # # @param [Class] return_type # The type of object to return. # This value may only be set to <code>String</code> or # <code>Addressable::URI</code>. All other values are invalid. Defaults # to <code>String</code>. # # @param [String] leave_encoded # A string of characters to leave encoded. If a percent encoded character # in this list is encountered then it will remain percent encoded. # # @return [String, Addressable::URI] # The unencoded component or URI. # The return type is determined by the <code>return_type</code> # parameter. def self.unencode(uri, return_type=String, leave_encoded='') return nil if uri.nil? begin uri = uri.to_str rescue NoMethodError, TypeError raise TypeError, "Can't convert #{uri.class} into String." end if !uri.is_a? String if ![String, ::Addressable::URI].include?(return_type) raise TypeError, "Expected Class (String or Addressable::URI), " + "got #{return_type.inspect}" end uri = uri.dup # Seriously, only use UTF-8. I'm really not kidding! uri.force_encoding("utf-8") leave_encoded = leave_encoded.dup.force_encoding("utf-8") result = uri.gsub(/%[0-9a-f]{2}/iu) do |sequence| c = sequence[1..3].to_i(16).chr c.force_encoding("utf-8") leave_encoded.include?(c) ? sequence : c end result.force_encoding("utf-8") if return_type == String return result elsif return_type == ::Addressable::URI return ::Addressable::URI.parse(result) end end class << self alias_method :unescape, :unencode alias_method :unencode_component, :unencode alias_method :unescape_component, :unencode end ## # Normalizes the encoding of a URI component. # # @param [String, #to_str] component The URI component to encode. # # @param [String, Regexp] character_class # The characters which are not percent encoded. If a <code>String</code> # is passed, the <code>String</code> must be formatted as a regular # expression character class. (Do not include the surrounding square # brackets.) For example, <code>"b-zB-Z0-9"</code> would cause # everything but the letters 'b' through 'z' and the numbers '0' # through '9' to be percent encoded. If a <code>Regexp</code> is passed, # the value <code>/[^b-zB-Z0-9]/</code> would have the same effect. A # set of useful <code>String</code> values may be found in the # <code>Addressable::URI::CharacterClasses</code> module. The default # value is the reserved plus unreserved character classes specified in # <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>. # # @param [String] leave_encoded # When <code>character_class</code> is a <code>String</code> then # <code>leave_encoded</code> is a string of characters that should remain # percent encoded while normalizing the component; if they appear percent # encoded in the original component, then they will be upcased ("%2f" # normalized to "%2F") but otherwise left alone. # # @return [String] The normalized component. # # @example # Addressable::URI.normalize_component("simpl%65/%65xampl%65", "b-zB-Z") # => "simple%2Fex%61mple" # Addressable::URI.normalize_component( # "simpl%65/%65xampl%65", /[^b-zB-Z]/ # ) # => "simple%2Fex%61mple" # Addressable::URI.normalize_component( # "simpl%65/%65xampl%65", # Addressable::URI::CharacterClasses::UNRESERVED # ) # => "simple%2Fexample" # Addressable::URI.normalize_component( # "one%20two%2fthree%26four", # "0-9a-zA-Z &/", # "/" # ) # => "one two%2Fthree&four" def self.normalize_component(component, character_class= CharacterClasses::RESERVED + CharacterClasses::UNRESERVED, leave_encoded='') return nil if component.nil? begin component = component.to_str rescue NoMethodError, TypeError raise TypeError, "Can't convert #{component.class} into String." end if !component.is_a? String if ![String, Regexp].include?(character_class.class) raise TypeError, "Expected String or Regexp, got #{character_class.inspect}" end if character_class.kind_of?(String) leave_re = if leave_encoded.length > 0 character_class = "#{character_class}%" unless character_class.include?('%') "|%(?!#{leave_encoded.chars.map do |char| seq = char.unpack('C*').map { |c| '%02x' % c }.join [seq.upcase, seq.downcase] end.flatten.join('|')})" end character_class = /[^#{character_class}]#{leave_re}/ end # We can't perform regexps on invalid UTF sequences, but # here we need to, so switch to ASCII. component = component.dup component.force_encoding(Encoding::ASCII_8BIT) unencoded = self.unencode_component(component, String, leave_encoded) begin encoded = self.encode_component( Addressable::IDNA.unicode_normalize_kc(unencoded), character_class, leave_encoded ) rescue ArgumentError encoded = self.encode_component(unencoded) end encoded.force_encoding(Encoding::UTF_8) return encoded end ## # Percent encodes any special characters in the URI. # # @param [String, Addressable::URI, #to_str] uri # The URI to encode. # # @param [Class] return_type # The type of object to return. # This value may only be set to <code>String</code> or # <code>Addressable::URI</code>. All other values are invalid. Defaults # to <code>String</code>. # # @return [String, Addressable::URI] # The encoded URI. # The return type is determined by the <code>return_type</code> # parameter. def self.encode(uri, return_type=String) return nil if uri.nil? begin uri = uri.to_str rescue NoMethodError, TypeError raise TypeError, "Can't convert #{uri.class} into String." end if !uri.is_a? String if ![String, ::Addressable::URI].include?(return_type) raise TypeError, "Expected Class (String or Addressable::URI), " + "got #{return_type.inspect}" end uri_object = uri.kind_of?(self) ? uri : self.parse(uri) encoded_uri = Addressable::URI.new( :scheme => self.encode_component(uri_object.scheme, Addressable::URI::CharacterClasses::SCHEME), :authority => self.encode_component(uri_object.authority, Addressable::URI::CharacterClasses::AUTHORITY), :path => self.encode_component(uri_object.path, Addressable::URI::CharacterClasses::PATH), :query => self.encode_component(uri_object.query, Addressable::URI::CharacterClasses::QUERY), :fragment => self.encode_component(uri_object.fragment, Addressable::URI::CharacterClasses::FRAGMENT) ) if return_type == String return encoded_uri.to_s elsif return_type == ::Addressable::URI return encoded_uri end end class << self alias_method :escape, :encode end ## # Normalizes the encoding of a URI. Characters within a hostname are # not percent encoded to allow for internationalized domain names. # # @param [String, Addressable::URI, #to_str] uri # The URI to encode. # # @param [Class] return_type # The type of object to return. # This value may only be set to <code>String</code> or # <code>Addressable::URI</code>. All other values are invalid. Defaults # to <code>String</code>. # # @return [String, Addressable::URI] # The encoded URI. # The return type is determined by the <code>return_type</code> # parameter. def self.normalized_encode(uri, return_type=String) begin uri = uri.to_str rescue NoMethodError, TypeError raise TypeError, "Can't convert #{uri.class} into String." end if !uri.is_a? String if ![String, ::Addressable::URI].include?(return_type) raise TypeError, "Expected Class (String or Addressable::URI), " + "got #{return_type.inspect}" end uri_object = uri.kind_of?(self) ? uri : self.parse(uri) components = { :scheme => self.unencode_component(uri_object.scheme), :user => self.unencode_component(uri_object.user), :password => self.unencode_component(uri_object.password), :host => self.unencode_component(uri_object.host), :port => (uri_object.port.nil? ? nil : uri_object.port.to_s), :path => self.unencode_component(uri_object.path), :query => self.unencode_component(uri_object.query), :fragment => self.unencode_component(uri_object.fragment) } components.each do |key, value| if value != nil begin components[key] = Addressable::IDNA.unicode_normalize_kc(value.to_str) rescue ArgumentError # Likely a malformed UTF-8 character, skip unicode normalization components[key] = value.to_str end end end encoded_uri = Addressable::URI.new( :scheme => self.encode_component(components[:scheme], Addressable::URI::CharacterClasses::SCHEME), :user => self.encode_component(components[:user], Addressable::URI::CharacterClasses::UNRESERVED), :password => self.encode_component(components[:password], Addressable::URI::CharacterClasses::UNRESERVED), :host => components[:host], :port => components[:port], :path => self.encode_component(components[:path], Addressable::URI::CharacterClasses::PATH), :query => self.encode_component(components[:query], Addressable::URI::CharacterClasses::QUERY), :fragment => self.encode_component(components[:fragment], Addressable::URI::CharacterClasses::FRAGMENT) ) if return_type == String return encoded_uri.to_s elsif return_type == ::Addressable::URI return encoded_uri end end ## # Encodes a set of key/value pairs according to the rules for the # <code>application/x-www-form-urlencoded</code> MIME type. # # @param [#to_hash, #to_ary] form_values # The form values to encode. # # @param [TrueClass, FalseClass] sort # Sort the key/value pairs prior to encoding. # Defaults to <code>false</code>. # # @return [String] # The encoded value. def self.form_encode(form_values, sort=false) if form_values.respond_to?(:to_hash) form_values = form_values.to_hash.to_a elsif form_values.respond_to?(:to_ary) form_values = form_values.to_ary else raise TypeError, "Can't convert #{form_values.class} into Array." end form_values = form_values.inject([]) do |accu, (key, value)| if value.kind_of?(Array) value.each do |v| accu << [key.to_s, v.to_s] end else accu << [key.to_s, value.to_s] end accu end if sort # Useful for OAuth and optimizing caching systems form_values = form_values.sort end escaped_form_values = form_values.map do |(key, value)| # Line breaks are CRLF pairs [ self.encode_component( key.gsub(/(\r\n|\n|\r)/, "\r\n"), CharacterClasses::UNRESERVED ).gsub("%20", "+"), self.encode_component( value.gsub(/(\r\n|\n|\r)/, "\r\n"), CharacterClasses::UNRESERVED ).gsub("%20", "+") ] end return escaped_form_values.map do |(key, value)| "#{key}=#{value}" end.join("&") end ## # Decodes a <code>String</code> according to the rules for the # <code>application/x-www-form-urlencoded</code> MIME type. # # @param [String, #to_str] encoded_value # The form values to decode. # # @return [Array] # The decoded values. # This is not a <code>Hash</code> because of the possibility for # duplicate keys. def self.form_unencode(encoded_value) if !encoded_value.respond_to?(:to_str) raise TypeError, "Can't convert #{encoded_value.class} into String." end encoded_value = encoded_value.to_str split_values = encoded_value.split("&").map do |pair| pair.split("=", 2) end return split_values.map do |(key, value)| [ key ? self.unencode_component( key.gsub("+", "%20")).gsub(/(\r\n|\n|\r)/, "\n") : nil, value ? (self.unencode_component( value.gsub("+", "%20")).gsub(/(\r\n|\n|\r)/, "\n")) : nil ] end end ## # Creates a new uri object from component parts. # # @option [String, #to_str] scheme The scheme component. # @option [String, #to_str] user The user component. # @option [String, #to_str] password The password component. # @option [String, #to_str] userinfo # The userinfo component. If this is supplied, the user and password # components must be omitted. # @option [String, #to_str] host The host component. # @option [String, #to_str] port The port component. # @option [String, #to_str] authority # The authority component. If this is supplied, the user, password, # userinfo, host, and port components must be omitted. # @option [String, #to_str] path The path component. # @option [String, #to_str] query The query component. # @option [String, #to_str] fragment The fragment component. # # @return [Addressable::URI] The constructed URI object. def initialize(options={}) if options.has_key?(:authority) if (options.keys & [:userinfo, :user, :password, :host, :port]).any? raise ArgumentError, "Cannot specify both an authority and any of the components " + "within the authority." end end if options.has_key?(:userinfo) if (options.keys & [:user, :password]).any? raise ArgumentError, "Cannot specify both a userinfo and either the user or password." end end self.defer_validation do # Bunch of crazy logic required because of the composite components # like userinfo and authority. self.scheme = options[:scheme] if options[:scheme] self.user = options[:user] if options[:user] self.password = options[:password] if options[:password] self.userinfo = options[:userinfo] if options[:userinfo] self.host = options[:host] if options[:host] self.port = options[:port] if options[:port] self.authority = options[:authority] if options[:authority] self.path = options[:path] if options[:path] self.query = options[:query] if options[:query] self.query_values = options[:query_values] if options[:query_values] self.fragment = options[:fragment] if options[:fragment] end self.to_s end ## # Freeze URI, initializing instance variables. # # @return [Addressable::URI] The frozen URI object. def freeze self.normalized_scheme self.normalized_user self.normalized_password self.normalized_userinfo self.normalized_host self.normalized_port self.normalized_authority self.normalized_site self.normalized_path self.normalized_query self.normalized_fragment self.hash super end ## # The scheme component for this URI. # # @return [String] The scheme component. def scheme return defined?(@scheme) ? @scheme : nil end ## # The scheme component for this URI, normalized. # # @return [String] The scheme component, normalized. def normalized_scheme return nil unless self.scheme @normalized_scheme ||= begin if self.scheme =~ /^\s*ssh\+svn\s*$/i "svn+ssh".dup else Addressable::URI.normalize_component( self.scheme.strip.downcase, Addressable::URI::CharacterClasses::SCHEME ) end end # All normalized values should be UTF-8 @normalized_scheme.force_encoding(Encoding::UTF_8) if @normalized_scheme @normalized_scheme end ## # Sets the scheme component for this URI. # # @param [String, #to_str] new_scheme The new scheme component. def scheme=(new_scheme) if new_scheme && !new_scheme.respond_to?(:to_str) raise TypeError, "Can't convert #{new_scheme.class} into String." elsif new_scheme new_scheme = new_scheme.to_str end if new_scheme && new_scheme !~ /\A[a-z][a-z0-9\.\+\-]*\z/i raise InvalidURIError, "Invalid scheme format: #{new_scheme}" end @scheme = new_scheme @scheme = nil if @scheme.to_s.strip.empty? # Reset dependent values remove_instance_variable(:@normalized_scheme) if defined?(@normalized_scheme) remove_composite_values # Ensure we haven't created an invalid URI validate() end ## # The user component for this URI. # # @return [String] The user component. def user return defined?(@user) ? @user : nil end ## # The user component for this URI, normalized. # # @return [String] The user component, normalized. def normalized_user return nil unless self.user return @normalized_user if defined?(@normalized_user) @normalized_user ||= begin if normalized_scheme =~ /https?/ && self.user.strip.empty? && (!self.password || self.password.strip.empty?) nil else Addressable::URI.normalize_component( self.user.strip, Addressable::URI::CharacterClasses::UNRESERVED ) end end # All normalized values should be UTF-8 @normalized_user.force_encoding(Encoding::UTF_8) if @normalized_user @normalized_user end ## # Sets the user component for this URI. # # @param [String, #to_str] new_user The new user component. def user=(new_user) if new_user && !new_user.respond_to?(:to_str) raise TypeError, "Can't convert #{new_user.class} into String." end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
true
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/addressable-2.5.2/lib/addressable/template.rb
_vendor/ruby/2.6.0/gems/addressable-2.5.2/lib/addressable/template.rb
# encoding:utf-8 #-- # Copyright (C) Bob Aman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #++ require "addressable/version" require "addressable/uri" module Addressable ## # This is an implementation of a URI template based on # RFC 6570 (http://tools.ietf.org/html/rfc6570). class Template # Constants used throughout the template code. anything = Addressable::URI::CharacterClasses::RESERVED + Addressable::URI::CharacterClasses::UNRESERVED variable_char_class = Addressable::URI::CharacterClasses::ALPHA + Addressable::URI::CharacterClasses::DIGIT + '_' var_char = "(?:(?:[#{variable_char_class}]|%[a-fA-F0-9][a-fA-F0-9])+)" RESERVED = "(?:[#{anything}]|%[a-fA-F0-9][a-fA-F0-9])" UNRESERVED = "(?:[#{ Addressable::URI::CharacterClasses::UNRESERVED }]|%[a-fA-F0-9][a-fA-F0-9])" variable = "(?:#{var_char}(?:\\.?#{var_char})*)" varspec = "(?:(#{variable})(\\*|:\\d+)?)" VARNAME = /^#{variable}$/ VARSPEC = /^#{varspec}$/ VARIABLE_LIST = /^#{varspec}(?:,#{varspec})*$/ operator = "+#./;?&=,!@|" EXPRESSION = /\{([#{operator}])?(#{varspec}(?:,#{varspec})*)\}/ LEADERS = { '?' => '?', '/' => '/', '#' => '#', '.' => '.', ';' => ';', '&' => '&' } JOINERS = { '?' => '&', '.' => '.', ';' => ';', '&' => '&', '/' => '/' } ## # Raised if an invalid template value is supplied. class InvalidTemplateValueError < StandardError end ## # Raised if an invalid template operator is used in a pattern. class InvalidTemplateOperatorError < StandardError end ## # Raised if an invalid template operator is used in a pattern. class TemplateOperatorAbortedError < StandardError end ## # This class represents the data that is extracted when a Template # is matched against a URI. class MatchData ## # Creates a new MatchData object. # MatchData objects should never be instantiated directly. # # @param [Addressable::URI] uri # The URI that the template was matched against. def initialize(uri, template, mapping) @uri = uri.dup.freeze @template = template @mapping = mapping.dup.freeze end ## # @return [Addressable::URI] # The URI that the Template was matched against. attr_reader :uri ## # @return [Addressable::Template] # The Template used for the match. attr_reader :template ## # @return [Hash] # The mapping that resulted from the match. # Note that this mapping does not include keys or values for # variables that appear in the Template, but are not present # in the URI. attr_reader :mapping ## # @return [Array] # The list of variables that were present in the Template. # Note that this list will include variables which do not appear # in the mapping because they were not present in URI. def variables self.template.variables end alias_method :keys, :variables alias_method :names, :variables ## # @return [Array] # The list of values that were captured by the Template. # Note that this list will include nils for any variables which # were in the Template, but did not appear in the URI. def values @values ||= self.variables.inject([]) do |accu, key| accu << self.mapping[key] accu end end alias_method :captures, :values ## # Accesses captured values by name or by index. # # @param [String, Symbol, Fixnum] key # Capture index or name. Note that when accessing by with index # of 0, the full URI will be returned. The intention is to mimic # the ::MatchData#[] behavior. # # @param [#to_int, nil] len # If provided, an array of values will be returend with the given # parameter used as length. # # @return [Array, String, nil] # The captured value corresponding to the index or name. If the # value was not provided or the key is unknown, nil will be # returned. # # If the second parameter is provided, an array of that length will # be returned instead. def [](key, len = nil) if len to_a[key, len] elsif String === key or Symbol === key mapping[key.to_s] else to_a[key] end end ## # @return [Array] # Array with the matched URI as first element followed by the captured # values. def to_a [to_s, *values] end ## # @return [String] # The matched URI as String. def to_s uri.to_s end alias_method :string, :to_s # Returns multiple captured values at once. # # @param [String, Symbol, Fixnum] *indexes # Indices of the captures to be returned # # @return [Array] # Values corresponding to given indices. # # @see Addressable::Template::MatchData#[] def values_at(*indexes) indexes.map { |i| self[i] } end ## # Returns a <tt>String</tt> representation of the MatchData's state. # # @return [String] The MatchData's state, as a <tt>String</tt>. def inspect sprintf("#<%s:%#0x RESULT:%s>", self.class.to_s, self.object_id, self.mapping.inspect) end ## # Dummy method for code expecting a ::MatchData instance # # @return [String] An empty string. def pre_match "" end alias_method :post_match, :pre_match end ## # Creates a new <tt>Addressable::Template</tt> object. # # @param [#to_str] pattern The URI Template pattern. # # @return [Addressable::Template] The initialized Template object. def initialize(pattern) if !pattern.respond_to?(:to_str) raise TypeError, "Can't convert #{pattern.class} into String." end @pattern = pattern.to_str.dup.freeze end ## # Freeze URI, initializing instance variables. # # @return [Addressable::URI] The frozen URI object. def freeze self.variables self.variable_defaults self.named_captures super end ## # @return [String] The Template object's pattern. attr_reader :pattern ## # Returns a <tt>String</tt> representation of the Template object's state. # # @return [String] The Template object's state, as a <tt>String</tt>. def inspect sprintf("#<%s:%#0x PATTERN:%s>", self.class.to_s, self.object_id, self.pattern) end ## # Returns <code>true</code> if the Template objects are equal. This method # does NOT normalize either Template before doing the comparison. # # @param [Object] template The Template to compare. # # @return [TrueClass, FalseClass] # <code>true</code> if the Templates are equivalent, <code>false</code> # otherwise. def ==(template) return false unless template.kind_of?(Template) return self.pattern == template.pattern end ## # Addressable::Template makes no distinction between `==` and `eql?`. # # @see #== alias_method :eql?, :== ## # Extracts a mapping from the URI using a URI Template pattern. # # @param [Addressable::URI, #to_str] uri # The URI to extract from. # # @param [#restore, #match] processor # A template processor object may optionally be supplied. # # The object should respond to either the <tt>restore</tt> or # <tt>match</tt> messages or both. The <tt>restore</tt> method should # take two parameters: `[String] name` and `[String] value`. # The <tt>restore</tt> method should reverse any transformations that # have been performed on the value to ensure a valid URI. # The <tt>match</tt> method should take a single # parameter: `[String] name`. The <tt>match</tt> method should return # a <tt>String</tt> containing a regular expression capture group for # matching on that particular variable. The default value is `".*?"`. # The <tt>match</tt> method has no effect on multivariate operator # expansions. # # @return [Hash, NilClass] # The <tt>Hash</tt> mapping that was extracted from the URI, or # <tt>nil</tt> if the URI didn't match the template. # # @example # class ExampleProcessor # def self.restore(name, value) # return value.gsub(/\+/, " ") if name == "query" # return value # end # # def self.match(name) # return ".*?" if name == "first" # return ".*" # end # end # # uri = Addressable::URI.parse( # "http://example.com/search/an+example+search+query/" # ) # Addressable::Template.new( # "http://example.com/search/{query}/" # ).extract(uri, ExampleProcessor) # #=> {"query" => "an example search query"} # # uri = Addressable::URI.parse("http://example.com/a/b/c/") # Addressable::Template.new( # "http://example.com/{first}/{second}/" # ).extract(uri, ExampleProcessor) # #=> {"first" => "a", "second" => "b/c"} # # uri = Addressable::URI.parse("http://example.com/a/b/c/") # Addressable::Template.new( # "http://example.com/{first}/{-list|/|second}/" # ).extract(uri) # #=> {"first" => "a", "second" => ["b", "c"]} def extract(uri, processor=nil) match_data = self.match(uri, processor) return (match_data ? match_data.mapping : nil) end ## # Extracts match data from the URI using a URI Template pattern. # # @param [Addressable::URI, #to_str] uri # The URI to extract from. # # @param [#restore, #match] processor # A template processor object may optionally be supplied. # # The object should respond to either the <tt>restore</tt> or # <tt>match</tt> messages or both. The <tt>restore</tt> method should # take two parameters: `[String] name` and `[String] value`. # The <tt>restore</tt> method should reverse any transformations that # have been performed on the value to ensure a valid URI. # The <tt>match</tt> method should take a single # parameter: `[String] name`. The <tt>match</tt> method should return # a <tt>String</tt> containing a regular expression capture group for # matching on that particular variable. The default value is `".*?"`. # The <tt>match</tt> method has no effect on multivariate operator # expansions. # # @return [Hash, NilClass] # The <tt>Hash</tt> mapping that was extracted from the URI, or # <tt>nil</tt> if the URI didn't match the template. # # @example # class ExampleProcessor # def self.restore(name, value) # return value.gsub(/\+/, " ") if name == "query" # return value # end # # def self.match(name) # return ".*?" if name == "first" # return ".*" # end # end # # uri = Addressable::URI.parse( # "http://example.com/search/an+example+search+query/" # ) # match = Addressable::Template.new( # "http://example.com/search/{query}/" # ).match(uri, ExampleProcessor) # match.variables # #=> ["query"] # match.captures # #=> ["an example search query"] # # uri = Addressable::URI.parse("http://example.com/a/b/c/") # match = Addressable::Template.new( # "http://example.com/{first}/{+second}/" # ).match(uri, ExampleProcessor) # match.variables # #=> ["first", "second"] # match.captures # #=> ["a", "b/c"] # # uri = Addressable::URI.parse("http://example.com/a/b/c/") # match = Addressable::Template.new( # "http://example.com/{first}{/second*}/" # ).match(uri) # match.variables # #=> ["first", "second"] # match.captures # #=> ["a", ["b", "c"]] def match(uri, processor=nil) uri = Addressable::URI.parse(uri) mapping = {} # First, we need to process the pattern, and extract the values. expansions, expansion_regexp = parse_template_pattern(pattern, processor) return nil unless uri.to_str.match(expansion_regexp) unparsed_values = uri.to_str.scan(expansion_regexp).flatten if uri.to_str == pattern return Addressable::Template::MatchData.new(uri, self, mapping) elsif expansions.size > 0 index = 0 expansions.each do |expansion| _, operator, varlist = *expansion.match(EXPRESSION) varlist.split(',').each do |varspec| _, name, modifier = *varspec.match(VARSPEC) mapping[name] ||= nil case operator when nil, '+', '#', '/', '.' unparsed_value = unparsed_values[index] name = varspec[VARSPEC, 1] value = unparsed_value value = value.split(JOINERS[operator]) if value && modifier == '*' when ';', '?', '&' if modifier == '*' if unparsed_values[index] value = unparsed_values[index].split(JOINERS[operator]) value = value.inject({}) do |acc, v| key, val = v.split('=') val = "" if val.nil? acc[key] = val acc end end else if (unparsed_values[index]) name, value = unparsed_values[index].split('=') value = "" if value.nil? end end end if processor != nil && processor.respond_to?(:restore) value = processor.restore(name, value) end if processor == nil if value.is_a?(Hash) value = value.inject({}){|acc, (k, v)| acc[Addressable::URI.unencode_component(k)] = Addressable::URI.unencode_component(v) acc } elsif value.is_a?(Array) value = value.map{|v| Addressable::URI.unencode_component(v) } else value = Addressable::URI.unencode_component(value) end end if !mapping.has_key?(name) || mapping[name].nil? # Doesn't exist, set to value (even if value is nil) mapping[name] = value end index = index + 1 end end return Addressable::Template::MatchData.new(uri, self, mapping) else return nil end end ## # Expands a URI template into another URI template. # # @param [Hash] mapping The mapping that corresponds to the pattern. # @param [#validate, #transform] processor # An optional processor object may be supplied. # @param [Boolean] normalize_values # Optional flag to enable/disable unicode normalization. Default: true # # The object should respond to either the <tt>validate</tt> or # <tt>transform</tt> messages or both. Both the <tt>validate</tt> and # <tt>transform</tt> methods should take two parameters: <tt>name</tt> and # <tt>value</tt>. The <tt>validate</tt> method should return <tt>true</tt> # or <tt>false</tt>; <tt>true</tt> if the value of the variable is valid, # <tt>false</tt> otherwise. An <tt>InvalidTemplateValueError</tt> # exception will be raised if the value is invalid. The <tt>transform</tt> # method should return the transformed variable value as a <tt>String</tt>. # If a <tt>transform</tt> method is used, the value will not be percent # encoded automatically. Unicode normalization will be performed both # before and after sending the value to the transform method. # # @return [Addressable::Template] The partially expanded URI template. # # @example # Addressable::Template.new( # "http://example.com/{one}/{two}/" # ).partial_expand({"one" => "1"}).pattern # #=> "http://example.com/1/{two}/" # # Addressable::Template.new( # "http://example.com/{?one,two}/" # ).partial_expand({"one" => "1"}).pattern # #=> "http://example.com/?one=1{&two}/" # # Addressable::Template.new( # "http://example.com/{?one,two,three}/" # ).partial_expand({"one" => "1", "three" => 3}).pattern # #=> "http://example.com/?one=1{&two}&three=3" def partial_expand(mapping, processor=nil, normalize_values=true) result = self.pattern.dup mapping = normalize_keys(mapping) result.gsub!( EXPRESSION ) do |capture| transform_partial_capture(mapping, capture, processor, normalize_values) end return Addressable::Template.new(result) end ## # Expands a URI template into a full URI. # # @param [Hash] mapping The mapping that corresponds to the pattern. # @param [#validate, #transform] processor # An optional processor object may be supplied. # @param [Boolean] normalize_values # Optional flag to enable/disable unicode normalization. Default: true # # The object should respond to either the <tt>validate</tt> or # <tt>transform</tt> messages or both. Both the <tt>validate</tt> and # <tt>transform</tt> methods should take two parameters: <tt>name</tt> and # <tt>value</tt>. The <tt>validate</tt> method should return <tt>true</tt> # or <tt>false</tt>; <tt>true</tt> if the value of the variable is valid, # <tt>false</tt> otherwise. An <tt>InvalidTemplateValueError</tt> # exception will be raised if the value is invalid. The <tt>transform</tt> # method should return the transformed variable value as a <tt>String</tt>. # If a <tt>transform</tt> method is used, the value will not be percent # encoded automatically. Unicode normalization will be performed both # before and after sending the value to the transform method. # # @return [Addressable::URI] The expanded URI template. # # @example # class ExampleProcessor # def self.validate(name, value) # return !!(value =~ /^[\w ]+$/) if name == "query" # return true # end # # def self.transform(name, value) # return value.gsub(/ /, "+") if name == "query" # return value # end # end # # Addressable::Template.new( # "http://example.com/search/{query}/" # ).expand( # {"query" => "an example search query"}, # ExampleProcessor # ).to_str # #=> "http://example.com/search/an+example+search+query/" # # Addressable::Template.new( # "http://example.com/search/{query}/" # ).expand( # {"query" => "an example search query"} # ).to_str # #=> "http://example.com/search/an%20example%20search%20query/" # # Addressable::Template.new( # "http://example.com/search/{query}/" # ).expand( # {"query" => "bogus!"}, # ExampleProcessor # ).to_str # #=> Addressable::Template::InvalidTemplateValueError def expand(mapping, processor=nil, normalize_values=true) result = self.pattern.dup mapping = normalize_keys(mapping) result.gsub!( EXPRESSION ) do |capture| transform_capture(mapping, capture, processor, normalize_values) end return Addressable::URI.parse(result) end ## # Returns an Array of variables used within the template pattern. # The variables are listed in the Array in the order they appear within # the pattern. Multiple occurrences of a variable within a pattern are # not represented in this Array. # # @return [Array] The variables present in the template's pattern. def variables @variables ||= ordered_variable_defaults.map { |var, val| var }.uniq end alias_method :keys, :variables alias_method :names, :variables ## # Returns a mapping of variables to their default values specified # in the template. Variables without defaults are not returned. # # @return [Hash] Mapping of template variables to their defaults def variable_defaults @variable_defaults ||= Hash[*ordered_variable_defaults.reject { |k, v| v.nil? }.flatten] end ## # Coerces a template into a `Regexp` object. This regular expression will # behave very similarly to the actual template, and should match the same # URI values, but it cannot fully handle, for example, values that would # extract to an `Array`. # # @return [Regexp] A regular expression which should match the template. def to_regexp _, source = parse_template_pattern(pattern) Regexp.new(source) end ## # Returns the source of the coerced `Regexp`. # # @return [String] The source of the `Regexp` given by {#to_regexp}. # # @api private def source self.to_regexp.source end ## # Returns the named captures of the coerced `Regexp`. # # @return [Hash] The named captures of the `Regexp` given by {#to_regexp}. # # @api private def named_captures self.to_regexp.named_captures end ## # Generates a route result for a given set of parameters. # Should only be used by rack-mount. # # @param params [Hash] The set of parameters used to expand the template. # @param recall [Hash] Default parameters used to expand the template. # @param options [Hash] Either a `:processor` or a `:parameterize` block. # # @api private def generate(params={}, recall={}, options={}) merged = recall.merge(params) if options[:processor] processor = options[:processor] elsif options[:parameterize] # TODO: This is sending me into fits trying to shoe-horn this into # the existing API. I think I've got this backwards and processors # should be a set of 4 optional blocks named :validate, :transform, # :match, and :restore. Having to use a singleton here is a huge # code smell. processor = Object.new class <<processor attr_accessor :block def transform(name, value) block.call(name, value) end end processor.block = options[:parameterize] else processor = nil end result = self.expand(merged, processor) result.to_s if result end private def ordered_variable_defaults @ordered_variable_defaults ||= begin expansions, _ = parse_template_pattern(pattern) expansions.map do |capture| _, _, varlist = *capture.match(EXPRESSION) varlist.split(',').map do |varspec| varspec[VARSPEC, 1] end end.flatten end end ## # Loops through each capture and expands any values available in mapping # # @param [Hash] mapping # Set of keys to expand # @param [String] capture # The expression to expand # @param [#validate, #transform] processor # An optional processor object may be supplied. # @param [Boolean] normalize_values # Optional flag to enable/disable unicode normalization. Default: true # # The object should respond to either the <tt>validate</tt> or # <tt>transform</tt> messages or both. Both the <tt>validate</tt> and # <tt>transform</tt> methods should take two parameters: <tt>name</tt> and # <tt>value</tt>. The <tt>validate</tt> method should return <tt>true</tt> # or <tt>false</tt>; <tt>true</tt> if the value of the variable is valid, # <tt>false</tt> otherwise. An <tt>InvalidTemplateValueError</tt> exception # will be raised if the value is invalid. The <tt>transform</tt> method # should return the transformed variable value as a <tt>String</tt>. If a # <tt>transform</tt> method is used, the value will not be percent encoded # automatically. Unicode normalization will be performed both before and # after sending the value to the transform method. # # @return [String] The expanded expression def transform_partial_capture(mapping, capture, processor = nil, normalize_values = true) _, operator, varlist = *capture.match(EXPRESSION) vars = varlist.split(',') if '?' == operator # partial expansion of form style query variables sometimes requires a # slight reordering of the variables to produce a valid url. first_to_expand = vars.find { |varspec| _, name, _ = *varspec.match(VARSPEC) mapping.key? name } vars = [first_to_expand] + vars.reject {|varspec| varspec == first_to_expand} if first_to_expand end vars .zip(operator_sequence(operator).take(vars.length)) .reduce("".dup) do |acc, (varspec, op)| _, name, _ = *varspec.match(VARSPEC) acc << if mapping.key? name transform_capture(mapping, "{#{op}#{varspec}}", processor, normalize_values) else "{#{op}#{varspec}}" end end end ## # Creates a lazy Enumerator of the operators that should be used to expand # variables in a varlist starting with `operator`. For example, an operator # `"?"` results in the sequence `"?","&","&"...` # # @param [String] operator from which to generate a sequence # # @return [Enumerator] sequence of operators def operator_sequence(operator) rest_operator = if "?" == operator "&" else operator end head_operator = operator Enumerator.new do |y| y << head_operator.to_s while true y << rest_operator.to_s end end end ## # Transforms a mapped value so that values can be substituted into the # template. # # @param [Hash] mapping The mapping to replace captures # @param [String] capture # The expression to replace # @param [#validate, #transform] processor # An optional processor object may be supplied. # @param [Boolean] normalize_values # Optional flag to enable/disable unicode normalization. Default: true # # # The object should respond to either the <tt>validate</tt> or # <tt>transform</tt> messages or both. Both the <tt>validate</tt> and # <tt>transform</tt> methods should take two parameters: <tt>name</tt> and # <tt>value</tt>. The <tt>validate</tt> method should return <tt>true</tt> # or <tt>false</tt>; <tt>true</tt> if the value of the variable is valid, # <tt>false</tt> otherwise. An <tt>InvalidTemplateValueError</tt> exception # will be raised if the value is invalid. The <tt>transform</tt> method # should return the transformed variable value as a <tt>String</tt>. If a # <tt>transform</tt> method is used, the value will not be percent encoded # automatically. Unicode normalization will be performed both before and # after sending the value to the transform method. # # @return [String] The expanded expression def transform_capture(mapping, capture, processor=nil, normalize_values=true) _, operator, varlist = *capture.match(EXPRESSION) return_value = varlist.split(',').inject([]) do |acc, varspec| _, name, modifier = *varspec.match(VARSPEC) value = mapping[name] unless value == nil || value == {} allow_reserved = %w(+ #).include?(operator) # Common primitives where the .to_s output is well-defined if Numeric === value || Symbol === value || value == true || value == false value = value.to_s end length = modifier.gsub(':', '').to_i if modifier =~ /^:\d+/ unless (Hash === value) || value.respond_to?(:to_ary) || value.respond_to?(:to_str) raise TypeError, "Can't convert #{value.class} into String or Array." end value = normalize_value(value) if normalize_values if processor == nil || !processor.respond_to?(:transform) # Handle percent escaping if allow_reserved encode_map = Addressable::URI::CharacterClasses::RESERVED + Addressable::URI::CharacterClasses::UNRESERVED else encode_map = Addressable::URI::CharacterClasses::UNRESERVED end if value.kind_of?(Array) transformed_value = value.map do |val| if length Addressable::URI.encode_component(val[0...length], encode_map) else Addressable::URI.encode_component(val, encode_map) end end unless modifier == "*" transformed_value = transformed_value.join(',') end elsif value.kind_of?(Hash) transformed_value = value.map do |key, val| if modifier == "*" "#{ Addressable::URI.encode_component( key, encode_map) }=#{ Addressable::URI.encode_component( val, encode_map) }" else "#{ Addressable::URI.encode_component( key, encode_map) },#{ Addressable::URI.encode_component( val, encode_map) }" end end unless modifier == "*" transformed_value = transformed_value.join(',') end else if length transformed_value = Addressable::URI.encode_component( value[0...length], encode_map) else transformed_value = Addressable::URI.encode_component( value, encode_map) end end end # Process, if we've got a processor if processor != nil if processor.respond_to?(:validate) if !processor.validate(name, value) display_value = value.kind_of?(Array) ? value.inspect : value raise InvalidTemplateValueError, "#{name}=#{display_value} is an invalid template value." end end if processor.respond_to?(:transform) transformed_value = processor.transform(name, value) if normalize_values transformed_value = normalize_value(transformed_value) end end end acc << [name, transformed_value] end acc end return "" if return_value.empty? join_values(operator, return_value) end ## # Takes a set of values, and joins them together based on the # operator. # # @param [String, Nil] operator One of the operators from the set # (?,&,+,#,;,/,.), or nil if there wasn't one. # @param [Array] return_value # The set of return values (as [variable_name, value] tuples) that will # be joined together. # # @return [String] The transformed mapped value def join_values(operator, return_value) leader = LEADERS.fetch(operator, '') joiner = JOINERS.fetch(operator, ',') case operator when '&', '?' leader + return_value.map{|k,v| if v.is_a?(Array) && v.first =~ /=/ v.join(joiner) elsif v.is_a?(Array)
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
true
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/addressable-2.5.2/lib/addressable/idna.rb
_vendor/ruby/2.6.0/gems/addressable-2.5.2/lib/addressable/idna.rb
# encoding:utf-8 #-- # Copyright (C) Bob Aman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #++ begin require "addressable/idna/native" rescue LoadError # libidn or the idn gem was not available, fall back on a pure-Ruby # implementation... require "addressable/idna/pure" end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/addressable-2.5.2/lib/addressable/idna/pure.rb
_vendor/ruby/2.6.0/gems/addressable-2.5.2/lib/addressable/idna/pure.rb
# encoding:utf-8 #-- # Copyright (C) Bob Aman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #++ module Addressable module IDNA # This module is loosely based on idn_actionmailer by Mick Staugaard, # the unicode library by Yoshida Masato, and the punycode implementation # by Kazuhiro Nishiyama. Most of the code was copied verbatim, but # some reformatting was done, and some translation from C was done. # # Without their code to work from as a base, we'd all still be relying # on the presence of libidn. Which nobody ever seems to have installed. # # Original sources: # http://github.com/staugaard/idn_actionmailer # http://www.yoshidam.net/Ruby.html#unicode # http://rubyforge.org/frs/?group_id=2550 UNICODE_TABLE = File.expand_path( File.join(File.dirname(__FILE__), '../../..', 'data/unicode.data') ) ACE_PREFIX = "xn--" UTF8_REGEX = /\A(?: [\x09\x0A\x0D\x20-\x7E] # ASCII | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4nil5 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16 )*\z/mnx UTF8_REGEX_MULTIBYTE = /(?: [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4nil5 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16 )/mnx # :startdoc: # Converts from a Unicode internationalized domain name to an ASCII # domain name as described in RFC 3490. def self.to_ascii(input) input = input.to_s unless input.is_a?(String) input = input.dup if input.respond_to?(:force_encoding) input.force_encoding(Encoding::ASCII_8BIT) end if input =~ UTF8_REGEX && input =~ UTF8_REGEX_MULTIBYTE parts = unicode_downcase(input).split('.') parts.map! do |part| if part.respond_to?(:force_encoding) part.force_encoding(Encoding::ASCII_8BIT) end if part =~ UTF8_REGEX && part =~ UTF8_REGEX_MULTIBYTE ACE_PREFIX + punycode_encode(unicode_normalize_kc(part)) else part end end parts.join('.') else input end end # Converts from an ASCII domain name to a Unicode internationalized # domain name as described in RFC 3490. def self.to_unicode(input) input = input.to_s unless input.is_a?(String) parts = input.split('.') parts.map! do |part| if part =~ /^#{ACE_PREFIX}(.+)/ begin punycode_decode(part[/^#{ACE_PREFIX}(.+)/, 1]) rescue Addressable::IDNA::PunycodeBadInput # toUnicode is explicitly defined as never-fails by the spec part end else part end end output = parts.join('.') if output.respond_to?(:force_encoding) output.force_encoding(Encoding::UTF_8) end output end # Unicode normalization form KC. def self.unicode_normalize_kc(input) input = input.to_s unless input.is_a?(String) unpacked = input.unpack("U*") unpacked = unicode_compose(unicode_sort_canonical(unicode_decompose(unpacked))) return unpacked.pack("U*") end ## # Unicode aware downcase method. # # @api private # @param [String] input # The input string. # @return [String] The downcased result. def self.unicode_downcase(input) input = input.to_s unless input.is_a?(String) unpacked = input.unpack("U*") unpacked.map! { |codepoint| lookup_unicode_lowercase(codepoint) } return unpacked.pack("U*") end (class <<self; private :unicode_downcase; end) def self.unicode_compose(unpacked) unpacked_result = [] length = unpacked.length return unpacked if length == 0 starter = unpacked[0] starter_cc = lookup_unicode_combining_class(starter) starter_cc = 256 if starter_cc != 0 for i in 1...length ch = unpacked[i] cc = lookup_unicode_combining_class(ch) if (starter_cc == 0 && (composite = unicode_compose_pair(starter, ch)) != nil) starter = composite startercc = lookup_unicode_combining_class(composite) else unpacked_result << starter starter = ch startercc = cc end end unpacked_result << starter return unpacked_result end (class <<self; private :unicode_compose; end) def self.unicode_compose_pair(ch_one, ch_two) if ch_one >= HANGUL_LBASE && ch_one < HANGUL_LBASE + HANGUL_LCOUNT && ch_two >= HANGUL_VBASE && ch_two < HANGUL_VBASE + HANGUL_VCOUNT # Hangul L + V return HANGUL_SBASE + ( (ch_one - HANGUL_LBASE) * HANGUL_VCOUNT + (ch_two - HANGUL_VBASE) ) * HANGUL_TCOUNT elsif ch_one >= HANGUL_SBASE && ch_one < HANGUL_SBASE + HANGUL_SCOUNT && (ch_one - HANGUL_SBASE) % HANGUL_TCOUNT == 0 && ch_two >= HANGUL_TBASE && ch_two < HANGUL_TBASE + HANGUL_TCOUNT # Hangul LV + T return ch_one + (ch_two - HANGUL_TBASE) end p = [] ucs4_to_utf8 = lambda do |ch| if ch < 128 p << ch elsif ch < 2048 p << (ch >> 6 | 192) p << (ch & 63 | 128) elsif ch < 0x10000 p << (ch >> 12 | 224) p << (ch >> 6 & 63 | 128) p << (ch & 63 | 128) elsif ch < 0x200000 p << (ch >> 18 | 240) p << (ch >> 12 & 63 | 128) p << (ch >> 6 & 63 | 128) p << (ch & 63 | 128) elsif ch < 0x4000000 p << (ch >> 24 | 248) p << (ch >> 18 & 63 | 128) p << (ch >> 12 & 63 | 128) p << (ch >> 6 & 63 | 128) p << (ch & 63 | 128) elsif ch < 0x80000000 p << (ch >> 30 | 252) p << (ch >> 24 & 63 | 128) p << (ch >> 18 & 63 | 128) p << (ch >> 12 & 63 | 128) p << (ch >> 6 & 63 | 128) p << (ch & 63 | 128) end end ucs4_to_utf8.call(ch_one) ucs4_to_utf8.call(ch_two) return lookup_unicode_composition(p) end (class <<self; private :unicode_compose_pair; end) def self.unicode_sort_canonical(unpacked) unpacked = unpacked.dup i = 1 length = unpacked.length return unpacked if length < 2 while i < length last = unpacked[i-1] ch = unpacked[i] last_cc = lookup_unicode_combining_class(last) cc = lookup_unicode_combining_class(ch) if cc != 0 && last_cc != 0 && last_cc > cc unpacked[i] = last unpacked[i-1] = ch i -= 1 if i > 1 else i += 1 end end return unpacked end (class <<self; private :unicode_sort_canonical; end) def self.unicode_decompose(unpacked) unpacked_result = [] for cp in unpacked if cp >= HANGUL_SBASE && cp < HANGUL_SBASE + HANGUL_SCOUNT l, v, t = unicode_decompose_hangul(cp) unpacked_result << l unpacked_result << v if v unpacked_result << t if t else dc = lookup_unicode_compatibility(cp) unless dc unpacked_result << cp else unpacked_result.concat(unicode_decompose(dc.unpack("U*"))) end end end return unpacked_result end (class <<self; private :unicode_decompose; end) def self.unicode_decompose_hangul(codepoint) sindex = codepoint - HANGUL_SBASE; if sindex < 0 || sindex >= HANGUL_SCOUNT l = codepoint v = t = nil return l, v, t end l = HANGUL_LBASE + sindex / HANGUL_NCOUNT v = HANGUL_VBASE + (sindex % HANGUL_NCOUNT) / HANGUL_TCOUNT t = HANGUL_TBASE + sindex % HANGUL_TCOUNT if t == HANGUL_TBASE t = nil end return l, v, t end (class <<self; private :unicode_decompose_hangul; end) def self.lookup_unicode_combining_class(codepoint) codepoint_data = UNICODE_DATA[codepoint] (codepoint_data ? (codepoint_data[UNICODE_DATA_COMBINING_CLASS] || 0) : 0) end (class <<self; private :lookup_unicode_combining_class; end) def self.lookup_unicode_compatibility(codepoint) codepoint_data = UNICODE_DATA[codepoint] (codepoint_data ? codepoint_data[UNICODE_DATA_COMPATIBILITY] : nil) end (class <<self; private :lookup_unicode_compatibility; end) def self.lookup_unicode_lowercase(codepoint) codepoint_data = UNICODE_DATA[codepoint] (codepoint_data ? (codepoint_data[UNICODE_DATA_LOWERCASE] || codepoint) : codepoint) end (class <<self; private :lookup_unicode_lowercase; end) def self.lookup_unicode_composition(unpacked) return COMPOSITION_TABLE[unpacked] end (class <<self; private :lookup_unicode_composition; end) HANGUL_SBASE = 0xac00 HANGUL_LBASE = 0x1100 HANGUL_LCOUNT = 19 HANGUL_VBASE = 0x1161 HANGUL_VCOUNT = 21 HANGUL_TBASE = 0x11a7 HANGUL_TCOUNT = 28 HANGUL_NCOUNT = HANGUL_VCOUNT * HANGUL_TCOUNT # 588 HANGUL_SCOUNT = HANGUL_LCOUNT * HANGUL_NCOUNT # 11172 UNICODE_DATA_COMBINING_CLASS = 0 UNICODE_DATA_EXCLUSION = 1 UNICODE_DATA_CANONICAL = 2 UNICODE_DATA_COMPATIBILITY = 3 UNICODE_DATA_UPPERCASE = 4 UNICODE_DATA_LOWERCASE = 5 UNICODE_DATA_TITLECASE = 6 begin if defined?(FakeFS) fakefs_state = FakeFS.activated? FakeFS.deactivate! end # This is a sparse Unicode table. Codepoints without entries are # assumed to have the value: [0, 0, nil, nil, nil, nil, nil] UNICODE_DATA = File.open(UNICODE_TABLE, "rb") do |file| Marshal.load(file.read) end ensure if defined?(FakeFS) FakeFS.activate! if fakefs_state end end COMPOSITION_TABLE = {} for codepoint, data in UNICODE_DATA canonical = data[UNICODE_DATA_CANONICAL] exclusion = data[UNICODE_DATA_EXCLUSION] if canonical && exclusion == 0 COMPOSITION_TABLE[canonical.unpack("C*")] = codepoint end end UNICODE_MAX_LENGTH = 256 ACE_MAX_LENGTH = 256 PUNYCODE_BASE = 36 PUNYCODE_TMIN = 1 PUNYCODE_TMAX = 26 PUNYCODE_SKEW = 38 PUNYCODE_DAMP = 700 PUNYCODE_INITIAL_BIAS = 72 PUNYCODE_INITIAL_N = 0x80 PUNYCODE_DELIMITER = 0x2D PUNYCODE_MAXINT = 1 << 64 PUNYCODE_PRINT_ASCII = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + " !\"\#$%&'()*+,-./" + "0123456789:;<=>?" + "@ABCDEFGHIJKLMNO" + "PQRSTUVWXYZ[\\]^_" + "`abcdefghijklmno" + "pqrstuvwxyz{|}~\n" # Input is invalid. class PunycodeBadInput < StandardError; end # Output would exceed the space provided. class PunycodeBigOutput < StandardError; end # Input needs wider integers to process. class PunycodeOverflow < StandardError; end def self.punycode_encode(unicode) unicode = unicode.to_s unless unicode.is_a?(String) input = unicode.unpack("U*") output = [0] * (ACE_MAX_LENGTH + 1) input_length = input.size output_length = [ACE_MAX_LENGTH] # Initialize the state n = PUNYCODE_INITIAL_N delta = out = 0 max_out = output_length[0] bias = PUNYCODE_INITIAL_BIAS # Handle the basic code points: input_length.times do |j| if punycode_basic?(input[j]) if max_out - out < 2 raise PunycodeBigOutput, "Output would exceed the space provided." end output[out] = input[j] out += 1 end end h = b = out # h is the number of code points that have been handled, b is the # number of basic code points, and out is the number of characters # that have been output. if b > 0 output[out] = PUNYCODE_DELIMITER out += 1 end # Main encoding loop: while h < input_length # All non-basic code points < n have been # handled already. Find the next larger one: m = PUNYCODE_MAXINT input_length.times do |j| m = input[j] if (n...m) === input[j] end # Increase delta enough to advance the decoder's # <n,i> state to <m,0>, but guard against overflow: if m - n > (PUNYCODE_MAXINT - delta) / (h + 1) raise PunycodeOverflow, "Input needs wider integers to process." end delta += (m - n) * (h + 1) n = m input_length.times do |j| # Punycode does not need to check whether input[j] is basic: if input[j] < n delta += 1 if delta == 0 raise PunycodeOverflow, "Input needs wider integers to process." end end if input[j] == n # Represent delta as a generalized variable-length integer: q = delta; k = PUNYCODE_BASE while true if out >= max_out raise PunycodeBigOutput, "Output would exceed the space provided." end t = ( if k <= bias PUNYCODE_TMIN elsif k >= bias + PUNYCODE_TMAX PUNYCODE_TMAX else k - bias end ) break if q < t output[out] = punycode_encode_digit(t + (q - t) % (PUNYCODE_BASE - t)) out += 1 q = (q - t) / (PUNYCODE_BASE - t) k += PUNYCODE_BASE end output[out] = punycode_encode_digit(q) out += 1 bias = punycode_adapt(delta, h + 1, h == b) delta = 0 h += 1 end end delta += 1 n += 1 end output_length[0] = out outlen = out outlen.times do |j| c = output[j] unless c >= 0 && c <= 127 raise StandardError, "Invalid output char." end unless PUNYCODE_PRINT_ASCII[c] raise PunycodeBadInput, "Input is invalid." end end output[0..outlen].map { |x| x.chr }.join("").sub(/\0+\z/, "") end (class <<self; private :punycode_encode; end) def self.punycode_decode(punycode) input = [] output = [] if ACE_MAX_LENGTH * 2 < punycode.size raise PunycodeBigOutput, "Output would exceed the space provided." end punycode.each_byte do |c| unless c >= 0 && c <= 127 raise PunycodeBadInput, "Input is invalid." end input.push(c) end input_length = input.length output_length = [UNICODE_MAX_LENGTH] # Initialize the state n = PUNYCODE_INITIAL_N out = i = 0 max_out = output_length[0] bias = PUNYCODE_INITIAL_BIAS # Handle the basic code points: Let b be the number of input code # points before the last delimiter, or 0 if there is none, then # copy the first b code points to the output. b = 0 input_length.times do |j| b = j if punycode_delimiter?(input[j]) end if b > max_out raise PunycodeBigOutput, "Output would exceed the space provided." end b.times do |j| unless punycode_basic?(input[j]) raise PunycodeBadInput, "Input is invalid." end output[out] = input[j] out+=1 end # Main decoding loop: Start just after the last delimiter if any # basic code points were copied; start at the beginning otherwise. in_ = b > 0 ? b + 1 : 0 while in_ < input_length # in_ is the index of the next character to be consumed, and # out is the number of code points in the output array. # Decode a generalized variable-length integer into delta, # which gets added to i. The overflow checking is easier # if we increase i as we go, then subtract off its starting # value at the end to obtain delta. oldi = i; w = 1; k = PUNYCODE_BASE while true if in_ >= input_length raise PunycodeBadInput, "Input is invalid." end digit = punycode_decode_digit(input[in_]) in_+=1 if digit >= PUNYCODE_BASE raise PunycodeBadInput, "Input is invalid." end if digit > (PUNYCODE_MAXINT - i) / w raise PunycodeOverflow, "Input needs wider integers to process." end i += digit * w t = ( if k <= bias PUNYCODE_TMIN elsif k >= bias + PUNYCODE_TMAX PUNYCODE_TMAX else k - bias end ) break if digit < t if w > PUNYCODE_MAXINT / (PUNYCODE_BASE - t) raise PunycodeOverflow, "Input needs wider integers to process." end w *= PUNYCODE_BASE - t k += PUNYCODE_BASE end bias = punycode_adapt(i - oldi, out + 1, oldi == 0) # I was supposed to wrap around from out + 1 to 0, # incrementing n each time, so we'll fix that now: if i / (out + 1) > PUNYCODE_MAXINT - n raise PunycodeOverflow, "Input needs wider integers to process." end n += i / (out + 1) i %= out + 1 # Insert n at position i of the output: # not needed for Punycode: # raise PUNYCODE_INVALID_INPUT if decode_digit(n) <= base if out >= max_out raise PunycodeBigOutput, "Output would exceed the space provided." end #memmove(output + i + 1, output + i, (out - i) * sizeof *output) output[i + 1, out - i] = output[i, out - i] output[i] = n i += 1 out += 1 end output_length[0] = out output.pack("U*") end (class <<self; private :punycode_decode; end) def self.punycode_basic?(codepoint) codepoint < 0x80 end (class <<self; private :punycode_basic?; end) def self.punycode_delimiter?(codepoint) codepoint == PUNYCODE_DELIMITER end (class <<self; private :punycode_delimiter?; end) def self.punycode_encode_digit(d) d + 22 + 75 * ((d < 26) ? 1 : 0) end (class <<self; private :punycode_encode_digit; end) # Returns the numeric value of a basic codepoint # (for use in representing integers) in the range 0 to # base - 1, or PUNYCODE_BASE if codepoint does not represent a value. def self.punycode_decode_digit(codepoint) if codepoint - 48 < 10 codepoint - 22 elsif codepoint - 65 < 26 codepoint - 65 elsif codepoint - 97 < 26 codepoint - 97 else PUNYCODE_BASE end end (class <<self; private :punycode_decode_digit; end) # Bias adaptation method def self.punycode_adapt(delta, numpoints, firsttime) delta = firsttime ? delta / PUNYCODE_DAMP : delta >> 1 # delta >> 1 is a faster way of doing delta / 2 delta += delta / numpoints difference = PUNYCODE_BASE - PUNYCODE_TMIN k = 0 while delta > (difference * PUNYCODE_TMAX) / 2 delta /= difference k += PUNYCODE_BASE end k + (difference + 1) * delta / (delta + PUNYCODE_SKEW) end (class <<self; private :punycode_adapt; end) end # :startdoc: end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/addressable-2.5.2/lib/addressable/idna/native.rb
_vendor/ruby/2.6.0/gems/addressable-2.5.2/lib/addressable/idna/native.rb
# encoding:utf-8 #-- # Copyright (C) Bob Aman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #++ require "idn" module Addressable module IDNA def self.punycode_encode(value) IDN::Punycode.encode(value.to_s) end def self.punycode_decode(value) IDN::Punycode.decode(value.to_s) end def self.unicode_normalize_kc(value) IDN::Stringprep.nfkc_normalize(value.to_s) end def self.to_ascii(value) value.to_s.split('.', -1).map do |segment| if segment.size > 0 && segment.size < 64 IDN::Idna.toASCII(segment, IDN::Idna::ALLOW_UNASSIGNED) elsif segment.size >= 64 segment else '' end end.join('.') end def self.to_unicode(value) value.to_s.split('.', -1).map do |segment| if segment.size > 0 && segment.size < 64 IDN::Idna.toUnicode(segment, IDN::Idna::ALLOW_UNASSIGNED) elsif segment.size >= 64 segment else '' end end.join('.') end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen.rb
require 'logger' require 'listen/logger' require 'listen/listener' require 'listen/internals/thread_pool' # Show warnings about vulnerabilities, bugs and outdated Rubies, since previous # versions aren't tested or officially supported. require 'ruby_dep/warning' RubyDep::Warning.new.show_warnings # Always set up logging by default first time file is required # # NOTE: If you need to clear the logger completely, do so *after* # requiring this file. If you need to set a custom logger, # require the listen/logger file and set the logger before requiring # this file. Listen.setup_default_logger_if_unset # Won't print anything by default because of level - unless you've set # LISTEN_GEM_DEBUGGING or provided your own logger with a high enough level Listen::Logger.info "Listen loglevel set to: #{Listen.logger.level}" Listen::Logger.info "Listen version: #{Listen::VERSION}" module Listen class << self # Listens to file system modifications on a either single directory or # multiple directories. # # @param (see Listen::Listener#new) # # @yield [modified, added, removed] the changed files # @yieldparam [Array<String>] modified the list of modified files # @yieldparam [Array<String>] added the list of added files # @yieldparam [Array<String>] removed the list of removed files # # @return [Listen::Listener] the listener # def to(*args, &block) @listeners ||= [] Listener.new(*args, &block).tap do |listener| @listeners << listener end end # This is used by the `listen` binary to handle Ctrl-C # def stop Internals::ThreadPool.stop @listeners ||= [] # TODO: should use a mutex for this @listeners.each(&:stop) @listeners = nil end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/directory.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/directory.rb
require 'set' module Listen # TODO: refactor (turn it into a normal object, cache the stat, etc) class Directory def self.scan(snapshot, rel_path, options) record = snapshot.record dir = Pathname.new(record.root) previous = record.dir_entries(rel_path) record.add_dir(rel_path) # TODO: use children(with_directory: false) path = dir + rel_path current = Set.new(_children(path)) Listen::Logger.debug do format('%s: %s(%s): %s -> %s', (options[:silence] ? 'Recording' : 'Scanning'), rel_path, options.inspect, previous.inspect, current.inspect) end begin current.each do |full_path| type = ::File.lstat(full_path.to_s).directory? ? :dir : :file item_rel_path = full_path.relative_path_from(dir).to_s _change(snapshot, type, item_rel_path, options) end rescue Errno::ENOENT # The directory changed meanwhile, so rescan it current = Set.new(_children(path)) retry end # TODO: this is not tested properly previous = previous.reject { |entry, _| current.include? path + entry } _async_changes(snapshot, Pathname.new(rel_path), previous, options) rescue Errno::ENOENT, Errno::EHOSTDOWN record.unset_path(rel_path) _async_changes(snapshot, Pathname.new(rel_path), previous, options) rescue Errno::ENOTDIR # TODO: path not tested record.unset_path(rel_path) _async_changes(snapshot, path, previous, options) _change(snapshot, :file, rel_path, options) rescue Listen::Logger.warn do format('scan DIED: %s:%s', $ERROR_INFO, $ERROR_POSITION * "\n") end raise end def self._async_changes(snapshot, path, previous, options) fail "Not a Pathname: #{path.inspect}" unless path.respond_to?(:children) previous.each do |entry, data| # TODO: this is a hack with insufficient testing type = data.key?(:mtime) ? :file : :dir rel_path_s = (path + entry).to_s _change(snapshot, type, rel_path_s, options) end end def self._change(snapshot, type, path, options) return snapshot.invalidate(type, path, options) if type == :dir # Minor param cleanup for tests # TODO: use a dedicated Event class opts = options.dup opts.delete(:recursive) snapshot.invalidate(type, path, opts) end def self._children(path) return path.children unless RUBY_ENGINE == 'jruby' # JRuby inconsistency workaround, see: # https://github.com/jruby/jruby/issues/3840 exists = path.exist? directory = path.directory? return path.children unless exists && !directory raise Errno::ENOTDIR, path.to_s end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/record.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/record.rb
require 'thread' require 'listen/record/entry' require 'listen/record/symlink_detector' module Listen class Record # TODO: one Record object per watched directory? # TODO: deprecate attr_reader :root def initialize(directory) @tree = _auto_hash @root = directory.to_s end def add_dir(rel_path) return if [nil, '', '.'].include? rel_path @tree[rel_path] ||= {} end def update_file(rel_path, data) dirname, basename = Pathname(rel_path).split.map(&:to_s) _fast_update_file(dirname, basename, data) end def unset_path(rel_path) dirname, basename = Pathname(rel_path).split.map(&:to_s) _fast_unset_path(dirname, basename) end def file_data(rel_path) dirname, basename = Pathname(rel_path).split.map(&:to_s) if [nil, '', '.'].include? dirname tree[basename] ||= {} tree[basename].dup else tree[dirname] ||= {} tree[dirname][basename] ||= {} tree[dirname][basename].dup end end def dir_entries(rel_path) subtree = if [nil, '', '.'].include? rel_path.to_s tree else tree[rel_path.to_s] ||= _auto_hash tree[rel_path.to_s] end result = {} subtree.each do |key, values| # only get data for file entries result[key] = values.key?(:mtime) ? values : {} end result end def build @tree = _auto_hash # TODO: test with a file name given # TODO: test other permissions # TODO: test with mixed encoding symlink_detector = SymlinkDetector.new remaining = ::Queue.new remaining << Entry.new(root, nil, nil) _fast_build_dir(remaining, symlink_detector) until remaining.empty? end private def _auto_hash Hash.new { |h, k| h[k] = Hash.new } end attr_reader :tree def _fast_update_file(dirname, basename, data) if [nil, '', '.'].include? dirname tree[basename] = (tree[basename] || {}).merge(data) else tree[dirname] ||= {} tree[dirname][basename] = (tree[dirname][basename] || {}).merge(data) end end def _fast_unset_path(dirname, basename) # this may need to be reworked to properly remove # entries from a tree, without adding non-existing dirs to the record if [nil, '', '.'].include? dirname return unless tree.key?(basename) tree.delete(basename) else return unless tree.key?(dirname) tree[dirname].delete(basename) end end def _fast_build_dir(remaining, symlink_detector) entry = remaining.pop children = entry.children # NOTE: children() implicitly tests if dir symlink_detector.verify_unwatched!(entry) children.each { |child| remaining << child } add_dir(entry.record_dir_key) rescue Errno::ENOTDIR _fast_try_file(entry) rescue SystemCallError, SymlinkDetector::Error _fast_unset_path(entry.relative, entry.name) end def _fast_try_file(entry) _fast_update_file(entry.relative, entry.name, entry.meta) rescue SystemCallError _fast_unset_path(entry.relative, entry.name) end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/version.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/version.rb
module Listen VERSION = '3.1.5'.freeze end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/change.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/change.rb
require 'listen/file' require 'listen/directory' module Listen # TODO: rename to Snapshot class Change # TODO: test this class for coverage class Config def initialize(queue, silencer) @queue = queue @silencer = silencer end def silenced?(path, type) @silencer.silenced?(Pathname(path), type) end def queue(*args) @queue << args end end attr_reader :record def initialize(config, record) @config = config @record = record end # Invalidate some part of the snapshot/record (dir, file, subtree, etc.) def invalidate(type, rel_path, options) watched_dir = Pathname.new(record.root) change = options[:change] cookie = options[:cookie] if !cookie && config.silenced?(rel_path, type) Listen::Logger.debug { "(silenced): #{rel_path.inspect}" } return end path = watched_dir + rel_path Listen::Logger.debug do log_details = options[:silence] && 'recording' || change || 'unknown' "#{log_details}: #{type}:#{path} (#{options.inspect})" end if change options = cookie ? { cookie: cookie } : {} config.queue(type, change, watched_dir, rel_path, options) elsif type == :dir # NOTE: POSSIBLE RECURSION # TODO: fix - use a queue instead Directory.scan(self, rel_path, options) else change = File.change(record, rel_path) return if !change || options[:silence] config.queue(:file, change, watched_dir, rel_path) end rescue RuntimeError => ex msg = format( '%s#%s crashed %s:%s', self.class, __method__, exinspect, ex.backtrace * "\n") Listen::Logger.error(msg) raise end private attr_reader :config end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/logger.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/logger.rb
module Listen def self.logger @logger ||= nil end def self.logger=(logger) @logger = logger end def self.setup_default_logger_if_unset self.logger ||= ::Logger.new(STDERR).tap do |logger| debugging = ENV['LISTEN_GEM_DEBUGGING'] logger.level = case debugging.to_s when /2/ ::Logger::DEBUG when /true|yes|1/i ::Logger::INFO else ::Logger::ERROR end end end class Logger [:fatal, :error, :warn, :info, :debug].each do |meth| define_singleton_method(meth) do |*args, &block| Listen.logger.public_send(meth, *args, &block) if Listen.logger end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/options.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/options.rb
module Listen class Options def initialize(opts, defaults) @options = {} given_options = opts.dup defaults.keys.each do |key| @options[key] = given_options.delete(key) || defaults[key] end return if given_options.empty? msg = "Unknown options: #{given_options.inspect}" Listen::Logger.warn msg fail msg end def method_missing(name, *_) return @options[name] if @options.key?(name) msg = "Bad option: #{name.inspect} (valid:#{@options.keys.inspect})" fail NameError, msg end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/silencer.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/silencer.rb
module Listen class Silencer # The default list of directories that get ignored. DEFAULT_IGNORED_DIRECTORIES = %r{^(?: \.git | \.svn | \.hg | \.rbx | \.bundle | bundle | vendor/bundle | log | tmp |vendor/ruby )(/|$)}x # The default list of files that get ignored. DEFAULT_IGNORED_EXTENSIONS = %r{(?: # Kate's tmp\/swp files \..*\d+\.new | \.kate-swp # Gedit tmp files | \.goutputstream-.{6} # Intellij files | ___jb_bak___ | ___jb_old___ # Vim swap files and write test | \.sw[px] | \.swpx | ^4913 # Sed temporary files - but without actual words, like 'sedatives' | (?:^ sed (?: [a-zA-Z0-9]{0}[A-Z]{1}[a-zA-Z0-9]{5} | [a-zA-Z0-9]{1}[A-Z]{1}[a-zA-Z0-9]{4} | [a-zA-Z0-9]{2}[A-Z]{1}[a-zA-Z0-9]{3} | [a-zA-Z0-9]{3}[A-Z]{1}[a-zA-Z0-9]{2} | [a-zA-Z0-9]{4}[A-Z]{1}[a-zA-Z0-9]{1} | [a-zA-Z0-9]{5}[A-Z]{1}[a-zA-Z0-9]{0} ) ) # other files | \.DS_Store | \.tmp | ~ )$}x attr_accessor :only_patterns, :ignore_patterns def initialize configure({}) end def configure(options) @only_patterns = options[:only] ? Array(options[:only]) : nil @ignore_patterns = _init_ignores(options[:ignore], options[:ignore!]) end # Note: relative_path is temporarily expected to be a relative Pathname to # make refactoring easier (ideally, it would take a string) # TODO: switch type and path places - and verify def silenced?(relative_path, type) path = relative_path.to_s if only_patterns && type == :file return true unless only_patterns.any? { |pattern| path =~ pattern } end ignore_patterns.any? { |pattern| path =~ pattern } end private attr_reader :options def _init_ignores(ignores, overrides) patterns = [] unless overrides patterns << DEFAULT_IGNORED_DIRECTORIES patterns << DEFAULT_IGNORED_EXTENSIONS end patterns << ignores patterns << overrides patterns.compact.flatten end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/file.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/file.rb
require 'digest/md5' module Listen class File def self.change(record, rel_path) path = Pathname.new(record.root) + rel_path lstat = path.lstat data = { mtime: lstat.mtime.to_f, mode: lstat.mode } record_data = record.file_data(rel_path) if record_data.empty? record.update_file(rel_path, data) return :added end if data[:mode] != record_data[:mode] record.update_file(rel_path, data) return :modified end if data[:mtime] != record_data[:mtime] record.update_file(rel_path, data) return :modified end return if /1|true/ =~ ENV['LISTEN_GEM_DISABLE_HASHING'] return unless inaccurate_mac_time?(lstat) # Check if change happened within 1 second (maybe it's even # too much, e.g. 0.3-0.5 could be sufficient). # # With rb-fsevent, there's a (configurable) latency between # when file was changed and when the event was triggered. # # If a file is saved at ???14.998, by the time the event is # actually received by Listen, the time could already be e.g. # ???15.7. # # And since Darwin adapter uses directory scanning, the file # mtime may be the same (e.g. file was changed at ???14.001, # then at ???14.998, but the fstat time would be ???14.0 in # both cases). # # If change happend at ???14.999997, the mtime is 14.0, so for # an mtime=???14.0 we assume it could even be almost ???15.0 # # So if Time.now.to_f is ???15.999998 and stat reports mtime # at ???14.0, then event was due to that file'd change when: # # ???15.999997 - ???14.999998 < 1.0s # # So the "2" is "1 + 1" (1s to cover rb-fsevent latency + # 1s maximum difference between real mtime and that recorded # in the file system) # return if data[:mtime].to_i + 2 <= Time.now.to_f md5 = Digest::MD5.file(path).digest record.update_file(rel_path, data.merge(md5: md5)) :modified if record_data[:md5] && md5 != record_data[:md5] rescue SystemCallError record.unset_path(rel_path) :removed rescue Listen::Logger.debug "lstat failed for: #{rel_path} (#{$ERROR_INFO})" raise end def self.inaccurate_mac_time?(stat) # 'mac' means Modified/Accessed/Created # Since precision depends on mounted FS (e.g. you can have a FAT partiion # mounted on Linux), check for fields with a remainder to detect this [stat.mtime, stat.ctime, stat.atime].map(&:usec).all?(&:zero?) end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/adapter.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/adapter.rb
require 'listen/adapter/base' require 'listen/adapter/bsd' require 'listen/adapter/darwin' require 'listen/adapter/linux' require 'listen/adapter/polling' require 'listen/adapter/windows' module Listen module Adapter OPTIMIZED_ADAPTERS = [Darwin, Linux, BSD, Windows].freeze POLLING_FALLBACK_MESSAGE = 'Listen will be polling for changes.'\ 'Learn more at https://github.com/guard/listen#listen-adapters.'.freeze class << self def select(options = {}) _log :debug, 'Adapter: considering polling ...' return Polling if options[:force_polling] _log :debug, 'Adapter: considering optimized backend...' return _usable_adapter_class if _usable_adapter_class _log :debug, 'Adapter: falling back to polling...' _warn_polling_fallback(options) Polling rescue _log :warn, format('Adapter: failed: %s:%s', $ERROR_POSITION.inspect, $ERROR_POSITION * "\n") raise end private def _usable_adapter_class OPTIMIZED_ADAPTERS.detect(&:usable?) end def _warn_polling_fallback(options) msg = options.fetch(:polling_fallback_message, POLLING_FALLBACK_MESSAGE) Kernel.warn "[Listen warning]:\n #{msg}" if msg end def _log(type, message) Listen::Logger.send(type, message) end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/fsm.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/fsm.rb
# Code copied from https://github.com/celluloid/celluloid-fsm module Listen module FSM DEFAULT_STATE = :default # Default state name unless one is explicitly set # Included hook to extend class methods def self.included(klass) klass.send :extend, ClassMethods end module ClassMethods # Obtain or set the default state # Passing a state name sets the default state def default_state(new_default = nil) if new_default @default_state = new_default.to_sym else defined?(@default_state) ? @default_state : DEFAULT_STATE end end # Obtain the valid states for this FSM def states @states ||= {} end # Declare an FSM state and optionally provide a callback block to fire # Options: # * to: a state or array of states this state can transition to def state(*args, &block) if args.last.is_a? Hash # Stringify keys :/ options = args.pop.each_with_object({}) { |(k, v), h| h[k.to_s] = v } else options = {} end args.each do |name| name = name.to_sym default_state name if options['default'] states[name] = State.new(name, options['to'], &block) end end end # Be kind and call super if you must redefine initialize def initialize @state = self.class.default_state end # Obtain the current state of the FSM attr_reader :state def transition(state_name) new_state = validate_and_sanitize_new_state(state_name) return unless new_state transition_with_callbacks!(new_state) end # Immediate state transition with no checks, or callbacks. "Dangerous!" def transition!(state_name) @state = state_name end protected def validate_and_sanitize_new_state(state_name) state_name = state_name.to_sym return if current_state_name == state_name if current_state && !current_state.valid_transition?(state_name) valid = current_state.transitions.map(&:to_s).join(', ') msg = "#{self.class} can't change state from '#{@state}'"\ " to '#{state_name}', only to: #{valid}" fail ArgumentError, msg end new_state = states[state_name] unless new_state return if state_name == default_state fail ArgumentError, "invalid state for #{self.class}: #{state_name}" end new_state end def transition_with_callbacks!(state_name) transition! state_name.name state_name.call(self) end def states self.class.states end def default_state self.class.default_state end def current_state states[@state] end def current_state_name current_state && current_state.name || '' end class State attr_reader :name, :transitions def initialize(name, transitions = nil, &block) @name = name @block = block @transitions = nil @transitions = Array(transitions).map(&:to_sym) if transitions end def call(obj) obj.instance_eval(&@block) if @block end def valid_transition?(new_state) # All transitions are allowed unless expressly return true unless @transitions @transitions.include? new_state.to_sym end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/backend.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/backend.rb
require 'listen/adapter' require 'listen/adapter/base' require 'listen/adapter/config' require 'forwardable' # This class just aggregates configuration object to avoid Listener specs # from exploding with huge test setup blocks module Listen class Backend extend Forwardable def initialize(directories, queue, silencer, config) adapter_select_opts = config.adapter_select_options adapter_class = Adapter.select(adapter_select_opts) # Use default from adapter if possible @min_delay_between_events = config.min_delay_between_events @min_delay_between_events ||= adapter_class::DEFAULTS[:wait_for_delay] @min_delay_between_events ||= 0.1 adapter_opts = config.adapter_instance_options(adapter_class) aconfig = Adapter::Config.new(directories, queue, silencer, adapter_opts) @adapter = adapter_class.new(aconfig) end delegate start: :adapter delegate stop: :adapter attr_reader :min_delay_between_events private attr_reader :adapter end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/cli.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/cli.rb
require 'thor' require 'listen' require 'logger' module Listen class CLI < Thor default_task :start desc 'start', 'Starts Listen' class_option :verbose, type: :boolean, default: false, aliases: '-v', banner: 'Verbose' class_option :directory, type: :array, default: '.', aliases: '-d', banner: 'The directory to listen to' class_option :relative, type: :boolean, default: false, aliases: '-r', banner: 'Convert paths relative to current directory' def start Listen::Forwarder.new(options).start end end class Forwarder attr_reader :logger def initialize(options) @options = options @logger = ::Logger.new(STDOUT) @logger.level = ::Logger::INFO @logger.formatter = proc { |_, _, _, msg| "#{msg}\n" } end def start logger.info 'Starting listen...' directory = @options[:directory] relative = @options[:relative] callback = proc do |modified, added, removed| if @options[:verbose] logger.info "+ #{added}" unless added.empty? logger.info "- #{removed}" unless removed.empty? logger.info "> #{modified}" unless modified.empty? end end listener = Listen.to( directory, relative: relative, &callback) listener.start sleep 0.5 while listener.processing? end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/queue_optimizer.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/queue_optimizer.rb
module Listen class QueueOptimizer class Config def initialize(adapter_class, silencer) @adapter_class = adapter_class @silencer = silencer end def exist?(path) Pathname(path).exist? end def silenced?(path, type) @silencer.silenced?(path, type) end def debug(*args, &block) Listen.logger.debug(*args, &block) end end def smoosh_changes(changes) # TODO: adapter could be nil at this point (shutdown) cookies = changes.group_by do |_, _, _, _, options| (options || {})[:cookie] end _squash_changes(_reinterpret_related_changes(cookies)) end def initialize(config) @config = config end private attr_reader :config # groups changes into the expected structure expected by # clients def _squash_changes(changes) # We combine here for backward compatibility # Newer clients should receive dir and path separately changes = changes.map { |change, dir, path| [change, dir + path] } actions = changes.group_by(&:last).map do |path, action_list| [_logical_action_for(path, action_list.map(&:first)), path.to_s] end config.debug("listen: raw changes: #{actions.inspect}") { modified: [], added: [], removed: [] }.tap do |squashed| actions.each do |type, path| squashed[type] << path unless type.nil? end config.debug("listen: final changes: #{squashed.inspect}") end end def _logical_action_for(path, actions) actions << :added if actions.delete(:moved_to) actions << :removed if actions.delete(:moved_from) modified = actions.detect { |x| x == :modified } _calculate_add_remove_difference(actions, path, modified) end def _calculate_add_remove_difference(actions, path, default_if_exists) added = actions.count { |x| x == :added } removed = actions.count { |x| x == :removed } diff = added - removed # TODO: avoid checking if path exists and instead assume the events are # in order (if last is :removed, it doesn't exist, etc.) if config.exist?(path) if diff > 0 :added elsif diff.zero? && added > 0 :modified else default_if_exists end else diff < 0 ? :removed : nil end end # remove extraneous rb-inotify events, keeping them only if it's a possible # editor rename() call (e.g. Kate and Sublime) def _reinterpret_related_changes(cookies) table = { moved_to: :added, moved_from: :removed } cookies.flat_map do |_, changes| data = _detect_possible_editor_save(changes) if data to_dir, to_file = data [[:modified, to_dir, to_file]] else not_silenced = changes.reject do |type, _, _, path, _| config.silenced?(Pathname(path), type) end not_silenced.map do |_, change, dir, path, _| [table.fetch(change, change), dir, path] end end end end def _detect_possible_editor_save(changes) return unless changes.size == 2 from_type = from_change = from = nil to_type = to_change = to_dir = to = nil changes.each do |data| case data[1] when :moved_from from_type, from_change, _, from, = data when :moved_to to_type, to_change, to_dir, to, = data else return nil end end return unless from && to # Expect an ignored moved_from and non-ignored moved_to # to qualify as an "editor modify" return unless config.silenced?(Pathname(from), from_type) config.silenced?(Pathname(to), to_type) ? nil : [to_dir, to] end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/listener.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/listener.rb
require 'English' require 'listen/version' require 'listen/backend' require 'listen/silencer' require 'listen/silencer/controller' require 'listen/queue_optimizer' require 'listen/fsm' require 'listen/event/loop' require 'listen/event/queue' require 'listen/event/config' require 'listen/listener/config' module Listen class Listener # TODO: move the state machine's methods private include Listen::FSM # Initializes the directories listener. # # @param [String] directory the directories to listen to # @param [Hash] options the listen options (see Listen::Listener::Options) # # @yield [modified, added, removed] the changed files # @yieldparam [Array<String>] modified the list of modified files # @yieldparam [Array<String>] added the list of added files # @yieldparam [Array<String>] removed the list of removed files # def initialize(*dirs, &block) options = dirs.last.is_a?(Hash) ? dirs.pop : {} @config = Config.new(options) eq_config = Event::Queue::Config.new(@config.relative?) queue = Event::Queue.new(eq_config) { @processor.wakeup_on_event } silencer = Silencer.new rules = @config.silencer_rules @silencer_controller = Silencer::Controller.new(silencer, rules) @backend = Backend.new(dirs, queue, silencer, @config) optimizer_config = QueueOptimizer::Config.new(@backend, silencer) pconfig = Event::Config.new( self, queue, QueueOptimizer.new(optimizer_config), @backend.min_delay_between_events, &block) @processor = Event::Loop.new(pconfig) super() # FSM end default_state :initializing state :initializing, to: [:backend_started, :stopped] state :backend_started, to: [:frontend_ready, :stopped] do backend.start end state :frontend_ready, to: [:processing_events, :stopped] do processor.setup end state :processing_events, to: [:paused, :stopped] do processor.resume end state :paused, to: [:processing_events, :stopped] do processor.pause end state :stopped, to: [:backend_started] do backend.stop # should be before processor.teardown to halt events ASAP processor.teardown end # Starts processing events and starts adapters # or resumes invoking callbacks if paused def start transition :backend_started if state == :initializing transition :frontend_ready if state == :backend_started transition :processing_events if state == :frontend_ready transition :processing_events if state == :paused end # Stops both listening for events and processing them def stop transition :stopped end # Stops invoking callbacks (messages pile up) def pause transition :paused end # processing means callbacks are called def processing? state == :processing_events end def paused? state == :paused end def ignore(regexps) @silencer_controller.append_ignores(regexps) end def ignore!(regexps) @silencer_controller.replace_with_bang_ignores(regexps) end def only(regexps) @silencer_controller.replace_with_only(regexps) end private attr_reader :processor attr_reader :backend end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/silencer/controller.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/silencer/controller.rb
module Listen class Silencer class Controller def initialize(silencer, default_options) @silencer = silencer opts = default_options @prev_silencer_options = {} rules = [:only, :ignore, :ignore!].map do |option| [option, opts[option]] if opts.key? option end _reconfigure_silencer(Hash[rules.compact]) end def append_ignores(*regexps) prev_ignores = Array(@prev_silencer_options[:ignore]) _reconfigure_silencer(ignore: [prev_ignores + regexps]) end def replace_with_bang_ignores(regexps) _reconfigure_silencer(ignore!: regexps) end def replace_with_only(regexps) _reconfigure_silencer(only: regexps) end private def _reconfigure_silencer(extra_options) opts = extra_options.dup opts = opts.map do |key, value| [key, Array(value).flatten.compact] end opts = Hash[opts] if opts.key?(:ignore) && opts[:ignore].empty? opts.delete(:ignore) end @prev_silencer_options = opts @silencer.configure(@prev_silencer_options.dup.freeze) end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/record/entry.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/record/entry.rb
module Listen # @private api class Record # Represents a directory entry (dir or file) class Entry # file: "/home/me/watched_dir", "app/models", "foo.rb" # dir, "/home/me/watched_dir", "." def initialize(root, relative, name = nil) @root = root @relative = relative @name = name end attr_reader :root, :relative, :name def children child_relative = _join (_entries(sys_path) - %w(. ..)).map do |name| Entry.new(@root, child_relative, name) end end def meta lstat = ::File.lstat(sys_path) { mtime: lstat.mtime.to_f, mode: lstat.mode } end # record hash is e.g. # if @record["/home/me/watched_dir"]["project/app/models"]["foo.rb"] # if @record["/home/me/watched_dir"]["project/app"]["models"] # record_dir_key is "project/app/models" def record_dir_key ::File.join(*[@relative, @name].compact) end def sys_path # Use full path in case someone uses chdir ::File.join(*[@root, @relative, @name].compact) end def real_path @real_path ||= ::File.realpath(sys_path) end private def _join args = [@relative, @name].compact args.empty? ? nil : ::File.join(*args) end def _entries(dir) return Dir.entries(dir) unless RUBY_ENGINE == 'jruby' # JRuby inconsistency workaround, see: # https://github.com/jruby/jruby/issues/3840 exists = ::File.exist?(dir) directory = ::File.directory?(dir) return Dir.entries(dir) unless exists && !directory raise Errno::ENOTDIR, dir end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/record/symlink_detector.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/record/symlink_detector.rb
require 'set' module Listen # @private api class Record class SymlinkDetector WIKI = 'https://github.com/guard/listen/wiki/Duplicate-directory-errors'.freeze SYMLINK_LOOP_ERROR = <<-EOS.freeze ** ERROR: directory is already being watched! ** Directory: %s is already being watched through: %s MORE INFO: #{WIKI} EOS class Error < RuntimeError end def initialize @real_dirs = Set.new end def verify_unwatched!(entry) real_path = entry.real_path @real_dirs.add?(real_path) || _fail(entry.sys_path, real_path) end private def _fail(symlinked, real_path) STDERR.puts format(SYMLINK_LOOP_ERROR, symlinked, real_path) fail Error, 'Failed due to looped symlinks' end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/internals/thread_pool.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/internals/thread_pool.rb
module Listen # @private api module Internals module ThreadPool def self.add(&block) Thread.new { block.call }.tap do |th| (@threads ||= Queue.new) << th end end def self.stop return unless @threads ||= nil return if @threads.empty? # return to avoid using possibly stubbed Queue killed = Queue.new # You can't kill a read on a descriptor in JRuby, so let's just # ignore running threads (listen rb-inotify waiting for disk activity # before closing) pray threads die faster than they are created... limit = RUBY_ENGINE == 'jruby' ? [1] : [] killed << @threads.pop.kill until @threads.empty? until killed.empty? th = killed.pop th.join(*limit) unless th[:listen_blocking_read_thread] end end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/event/processor.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/event/processor.rb
module Listen module Event class Processor def initialize(config, reasons) @config = config @reasons = reasons _reset_no_unprocessed_events end # TODO: implement this properly instead of checking the state at arbitrary # points in time def loop_for(latency) @latency = latency loop do _wait_until_events _wait_until_events_calm_down _wait_until_no_longer_paused _process_changes end rescue Stopped Listen::Logger.debug('Processing stopped') end private class Stopped < RuntimeError end def _wait_until_events_calm_down loop do now = _timestamp # Assure there's at least latency between callbacks to allow # for accumulating changes diff = _deadline - now break if diff <= 0 # give events a bit of time to accumulate so they can be # compressed/optimized _sleep(:waiting_until_latency, diff) end end def _wait_until_no_longer_paused # TODO: may not be a good idea? _sleep(:waiting_for_unpause) while config.paused? end def _check_stopped return unless config.stopped? _flush_wakeup_reasons raise Stopped end def _sleep(_local_reason, *args) _check_stopped sleep_duration = config.sleep(*args) _check_stopped _flush_wakeup_reasons do |reason| next unless reason == :event _remember_time_of_first_unprocessed_event unless config.paused? end sleep_duration end def _remember_time_of_first_unprocessed_event @first_unprocessed_event_time ||= _timestamp end def _reset_no_unprocessed_events @first_unprocessed_event_time = nil end def _deadline @first_unprocessed_event_time + @latency end def _wait_until_events # TODO: long sleep may not be a good idea? _sleep(:waiting_for_events) while config.event_queue.empty? @first_unprocessed_event_time ||= _timestamp end def _flush_wakeup_reasons reasons = @reasons until reasons.empty? reason = reasons.pop yield reason if block_given? end end def _timestamp config.timestamp end # for easier testing without sleep loop def _process_changes _reset_no_unprocessed_events changes = [] changes << config.event_queue.pop until config.event_queue.empty? callable = config.callable? return unless callable hash = config.optimize_changes(changes) result = [hash[:modified], hash[:added], hash[:removed]] return if result.all?(&:empty?) block_start = _timestamp config.call(*result) Listen::Logger.debug "Callback took #{_timestamp - block_start} sec" end attr_reader :config end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/event/queue.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/event/queue.rb
require 'thread' require 'forwardable' module Listen module Event class Queue extend Forwardable class Config def initialize(relative) @relative = relative end def relative? @relative end end def initialize(config, &block) @event_queue = ::Queue.new @block = block @config = config end def <<(args) type, change, dir, path, options = *args fail "Invalid type: #{type.inspect}" unless [:dir, :file].include? type fail "Invalid change: #{change.inspect}" unless change.is_a?(Symbol) fail "Invalid path: #{path.inspect}" unless path.is_a?(String) dir = _safe_relative_from_cwd(dir) event_queue.public_send(:<<, [type, change, dir, path, options]) block.call(args) if block end delegate empty?: :event_queue delegate pop: :event_queue private attr_reader :event_queue attr_reader :block attr_reader :config def _safe_relative_from_cwd(dir) return dir unless config.relative? dir.relative_path_from(Pathname.pwd) rescue ArgumentError dir end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/event/loop.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/event/loop.rb
require 'thread' require 'timeout' require 'listen/event/processor' module Listen module Event class Loop class Error < RuntimeError class NotStarted < Error end end def initialize(config) @config = config @wait_thread = nil @state = :paused @reasons = ::Queue.new end def wakeup_on_event return if stopped? return unless processing? return unless wait_thread.alive? _wakeup(:event) end def paused? wait_thread && state == :paused end def processing? return false if stopped? return false if paused? state == :processing end def setup # TODO: use a Fiber instead? q = ::Queue.new @wait_thread = Internals::ThreadPool.add do _wait_for_changes(q, config) end Listen::Logger.debug('Waiting for processing to start...') Timeout.timeout(5) { q.pop } end def resume fail Error::NotStarted if stopped? return unless wait_thread _wakeup(:resume) end def pause # TODO: works? # fail NotImplementedError end def teardown return unless wait_thread if wait_thread.alive? _wakeup(:teardown) wait_thread.join end @wait_thread = nil end def stopped? !wait_thread end private attr_reader :config attr_reader :wait_thread attr_accessor :state def _wait_for_changes(ready_queue, config) processor = Event::Processor.new(config, @reasons) _wait_until_resumed(ready_queue) processor.loop_for(config.min_delay_between_events) rescue StandardError => ex _nice_error(ex) end def _sleep(*args) Kernel.sleep(*args) end def _wait_until_resumed(ready_queue) self.state = :paused ready_queue << :ready sleep self.state = :processing end def _nice_error(ex) indent = "\n -- " msg = format( 'exception while processing events: %s Backtrace:%s%s', ex, indent, ex.backtrace * indent ) Listen::Logger.error(msg) end def _wakeup(reason) @reasons << reason wait_thread.wakeup end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/event/config.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/event/config.rb
module Listen module Event class Config def initialize( listener, event_queue, queue_optimizer, wait_for_delay, &block) @listener = listener @event_queue = event_queue @queue_optimizer = queue_optimizer @min_delay_between_events = wait_for_delay @block = block end def sleep(*args) Kernel.sleep(*args) end def call(*args) @block.call(*args) if @block end def timestamp Time.now.to_f end attr_reader :event_queue def callable? @block end def optimize_changes(changes) @queue_optimizer.smoosh_changes(changes) end attr_reader :min_delay_between_events def stopped? listener.state == :stopped end def paused? listener.state == :paused end private attr_reader :listener end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/adapter/polling.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/adapter/polling.rb
module Listen module Adapter # Polling Adapter that works cross-platform and # has no dependencies. This is the adapter that # uses the most CPU processing power and has higher # file IO than the other implementations. # class Polling < Base OS_REGEXP = // # match every OS DEFAULTS = { latency: 1.0, wait_for_delay: 0.05 }.freeze private def _configure(_, &callback) @polling_callbacks ||= [] @polling_callbacks << callback end def _run loop do start = Time.now.to_f @polling_callbacks.each do |callback| callback.call(nil) nap_time = options.latency - (Time.now.to_f - start) # TODO: warn if nap_time is negative (polling too slow) sleep(nap_time) if nap_time > 0 end end end def _process_event(dir, _) _queue_change(:dir, dir, '.', recursive: true) end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/adapter/base.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/adapter/base.rb
require 'listen/options' require 'listen/record' require 'listen/change' module Listen module Adapter class Base attr_reader :options # TODO: only used by tests DEFAULTS = {}.freeze attr_reader :config def initialize(config) @started = false @config = config @configured = nil fail 'No directories to watch!' if config.directories.empty? defaults = self.class.const_get('DEFAULTS') @options = Listen::Options.new(config.adapter_options, defaults) rescue _log_exception 'adapter config failed: %s:%s called from: %s', caller raise end # TODO: it's a separate method as a temporary workaround for tests def configure if @configured _log(:warn, 'Adapter already configured!') return end @configured = true @callbacks ||= {} config.directories.each do |dir| callback = @callbacks[dir] || lambda do |event| _process_event(dir, event) end @callbacks[dir] = callback _configure(dir, &callback) end @snapshots ||= {} # TODO: separate config per directory (some day maybe) change_config = Change::Config.new(config.queue, config.silencer) config.directories.each do |dir| record = Record.new(dir) snapshot = Change.new(change_config, record) @snapshots[dir] = snapshot end end def started? @started end def start configure if started? _log(:warn, 'Adapter already started!') return end @started = true calling_stack = caller.dup Listen::Internals::ThreadPool.add do begin @snapshots.values.each do |snapshot| _timed('Record.build()') { snapshot.record.build } end _run rescue msg = 'run() in thread failed: %s:\n'\ ' %s\n\ncalled from:\n %s' _log_exception(msg, calling_stack) raise # for unit tests mostly end end end def stop _stop end def self.usable? const_get('OS_REGEXP') =~ RbConfig::CONFIG['target_os'] end private def _stop end def _timed(title) start = Time.now.to_f yield diff = Time.now.to_f - start Listen::Logger.info format('%s: %.05f seconds', title, diff) rescue Listen::Logger.warn "#{title} crashed: #{$ERROR_INFO.inspect}" raise end # TODO: allow backend adapters to pass specific invalidation objects # e.g. Darwin -> DirRescan, INotify -> MoveScan, etc. def _queue_change(type, dir, rel_path, options) @snapshots[dir].invalidate(type, rel_path, options) end def _log(*args, &block) self.class.send(:_log, *args, &block) end def _log_exception(msg, caller_stack) formatted = format( msg, $ERROR_INFO, $ERROR_POSITION * "\n", caller_stack * "\n" ) _log(:error, formatted) end class << self private def _log(*args, &block) Listen::Logger.send(*args, &block) end end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/adapter/darwin.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/adapter/darwin.rb
require 'thread' require 'listen/internals/thread_pool' module Listen module Adapter # Adapter implementation for Mac OS X `FSEvents`. # class Darwin < Base OS_REGEXP = /darwin(?<major_version>1\d+)/i # The default delay between checking for changes. DEFAULTS = { latency: 0.1 }.freeze INCOMPATIBLE_GEM_VERSION = <<-EOS.gsub(/^ {8}/, '') rb-fsevent > 0.9.4 no longer supports OS X 10.6 through 10.8. Please add the following to your Gemfile to avoid polling for changes: require 'rbconfig' if RbConfig::CONFIG['target_os'] =~ /darwin(1[0-3])/i gem 'rb-fsevent', '<= 0.9.4' end EOS def self.usable? require 'rb-fsevent' version = RbConfig::CONFIG['target_os'][OS_REGEXP, :major_version] return false unless version return true if version.to_i >= 13 # darwin13 is OS X 10.9 fsevent_version = Gem::Version.new(FSEvent::VERSION) return true if fsevent_version <= Gem::Version.new('0.9.4') Kernel.warn INCOMPATIBLE_GEM_VERSION false end private # NOTE: each directory gets a DIFFERENT callback! def _configure(dir, &callback) opts = { latency: options.latency } @workers ||= ::Queue.new @workers << FSEvent.new.tap do |worker| _log :debug, "fsevent: watching: #{dir.to_s.inspect}" worker.watch(dir.to_s, opts, &callback) end end def _run first = @workers.pop # NOTE: _run is called within a thread, so run every other # worker in it's own thread _run_workers_in_background(_to_array(@workers)) _run_worker(first) end def _process_event(dir, event) _log :debug, "fsevent: processing event: #{event.inspect}" event.each do |path| new_path = Pathname.new(path.sub(%r{\/$}, '')) _log :debug, "fsevent: #{new_path}" # TODO: does this preserve symlinks? rel_path = new_path.relative_path_from(dir).to_s _queue_change(:dir, dir, rel_path, recursive: true) end end def _run_worker(worker) _log :debug, "fsevent: running worker: #{worker.inspect}" worker.run rescue format_string = 'fsevent: running worker failed: %s:%s called from: %s' _log_exception format_string, caller end def _run_workers_in_background(workers) workers.each do |worker| # NOTE: while passing local variables to the block below is not # thread safe, using 'worker' from the enumerator above is ok Listen::Internals::ThreadPool.add { _run_worker(worker) } end end def _to_array(queue) workers = [] workers << queue.pop until queue.empty? workers end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/adapter/linux.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/adapter/linux.rb
module Listen module Adapter # @see https://github.com/nex3/rb-inotify class Linux < Base OS_REGEXP = /linux/i DEFAULTS = { events: [ :recursive, :attrib, :create, :delete, :move, :close_write ], wait_for_delay: 0.1 }.freeze private WIKI_URL = 'https://github.com/guard/listen'\ '/wiki/Increasing-the-amount-of-inotify-watchers'.freeze INOTIFY_LIMIT_MESSAGE = <<-EOS.gsub(/^\s*/, '') FATAL: Listen error: unable to monitor directories for changes. Visit #{WIKI_URL} for info on how to fix this. EOS def _configure(directory, &callback) require 'rb-inotify' @worker ||= ::INotify::Notifier.new @worker.watch(directory.to_s, *options.events, &callback) rescue Errno::ENOSPC abort(INOTIFY_LIMIT_MESSAGE) end def _run Thread.current[:listen_blocking_read_thread] = true @worker.run Thread.current[:listen_blocking_read_thread] = false end def _process_event(dir, event) # NOTE: avoid using event.absolute_name since new API # will need to have a custom recursion implemented # to properly match events to configured directories path = Pathname.new(event.watcher.path) + event.name rel_path = path.relative_path_from(dir).to_s _log(:debug) { "inotify: #{rel_path} (#{event.flags.inspect})" } if /1|true/ =~ ENV['LISTEN_GEM_SIMULATE_FSEVENT'] if (event.flags & [:moved_to, :moved_from]) || _dir_event?(event) rel_path = path.dirname.relative_path_from(dir).to_s end _queue_change(:dir, dir, rel_path, {}) return end return if _skip_event?(event) cookie_params = event.cookie.zero? ? {} : { cookie: event.cookie } # Note: don't pass options to force rescanning the directory, so we can # detect moving/deleting a whole tree if _dir_event?(event) _queue_change(:dir, dir, rel_path, cookie_params) return end params = cookie_params.merge(change: _change(event.flags)) _queue_change(:file, dir, rel_path, params) end def _skip_event?(event) # Event on root directory return true if event.name == '' # INotify reports changes to files inside directories as events # on the directories themselves too. # # @see http://linux.die.net/man/7/inotify _dir_event?(event) && (event.flags & [:close, :modify]).any? end def _change(event_flags) { modified: [:attrib, :close_write], moved_to: [:moved_to], moved_from: [:moved_from], added: [:create], removed: [:delete] }.each do |change, flags| return change unless (flags & event_flags).empty? end nil end def _dir_event?(event) event.flags.include?(:isdir) end def _stop @worker && @worker.close end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/adapter/config.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/adapter/config.rb
require 'pathname' module Listen module Adapter class Config attr_reader :directories attr_reader :silencer attr_reader :queue attr_reader :adapter_options def initialize(directories, queue, silencer, adapter_options) # Default to current directory if no directories are supplied directories = [Dir.pwd] if directories.to_a.empty? # TODO: fix (flatten, array, compact?) @directories = directories.map do |directory| Pathname.new(directory.to_s).realpath end @silencer = silencer @queue = queue @adapter_options = adapter_options end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/adapter/bsd.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/adapter/bsd.rb
# Listener implementation for BSD's `kqueue`. # @see http://www.freebsd.org/cgi/man.cgi?query=kqueue # @see https://github.com/mat813/rb-kqueue/blob/master/lib/rb-kqueue/queue.rb # module Listen module Adapter class BSD < Base OS_REGEXP = /bsd|dragonfly/i DEFAULTS = { events: [ :delete, :write, :extend, :attrib, :rename # :link, :revoke ] }.freeze BUNDLER_DECLARE_GEM = <<-EOS.gsub(/^ {6}/, '') Please add the following to your Gemfile to avoid polling for changes: require 'rbconfig' if RbConfig::CONFIG['target_os'] =~ /#{OS_REGEXP}/ gem 'rb-kqueue', '>= 0.2' end EOS def self.usable? return false unless super require 'rb-kqueue' require 'find' true rescue LoadError Kernel.warn BUNDLER_DECLARE_GEM false end private def _configure(directory, &callback) @worker ||= KQueue::Queue.new @callback = callback # use Record to make a snapshot of dir, so we # can detect new files _find(directory.to_s) { |path| _watch_file(path, @worker) } end def _run @worker.run end def _process_event(dir, event) full_path = _event_path(event) if full_path.directory? # Force dir content tracking to kick in, or we won't have # names of added files _queue_change(:dir, dir, '.', recursive: true) elsif full_path.exist? path = full_path.relative_path_from(dir) _queue_change(:file, dir, path.to_s, change: _change(event.flags)) end # If it is a directory, and it has a write flag, it means a # file has been added so find out which and deal with it. # No need to check for removed files, kqueue will forget them # when the vfs does. _watch_for_new_file(event) if full_path.directory? end def _change(event_flags) { modified: [:attrib, :extend], added: [:write], removed: [:rename, :delete] }.each do |change, flags| return change unless (flags & event_flags).empty? end nil end def _event_path(event) Pathname.new(event.watcher.path) end def _watch_for_new_file(event) queue = event.watcher.queue _find(_event_path(event).to_s) do |file_path| unless queue.watchers.detect { |_, v| v.path == file_path.to_s } _watch_file(file_path, queue) end end end def _watch_file(path, queue) queue.watch_file(path, *options.events, &@callback) rescue Errno::ENOENT => e _log :warn, "kqueue: watch file failed: #{e.message}" end # Quick rubocop workaround def _find(*paths, &block) Find.send(:find, *paths, &block) end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/adapter/windows.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/adapter/windows.rb
module Listen module Adapter # Adapter implementation for Windows `wdm`. # class Windows < Base OS_REGEXP = /mswin|mingw|cygwin/i BUNDLER_DECLARE_GEM = <<-EOS.gsub(/^ {6}/, '') Please add the following to your Gemfile to avoid polling for changes: gem 'wdm', '>= 0.1.0' if Gem.win_platform? EOS def self.usable? return false unless super require 'wdm' true rescue LoadError _log :debug, format('wdm - load failed: %s:%s', $ERROR_INFO, $ERROR_POSITION * "\n") Kernel.warn BUNDLER_DECLARE_GEM false end private def _configure(dir) require 'wdm' _log :debug, 'wdm - starting...' @worker ||= WDM::Monitor.new @worker.watch_recursively(dir.to_s, :files) do |change| yield([:file, change]) end @worker.watch_recursively(dir.to_s, :directories) do |change| yield([:dir, change]) end events = [:attributes, :last_write] @worker.watch_recursively(dir.to_s, *events) do |change| yield([:attr, change]) end end def _run @worker.run! end def _process_event(dir, event) _log :debug, "wdm - callback: #{event.inspect}" type, change = event full_path = Pathname(change.path) rel_path = full_path.relative_path_from(dir).to_s options = { change: _change(change.type) } case type when :file _queue_change(:file, dir, rel_path, options) when :attr unless full_path.directory? _queue_change(:file, dir, rel_path, options) end when :dir if change.type == :removed # TODO: check if watched dir? _queue_change(:dir, dir, Pathname(rel_path).dirname.to_s, {}) elsif change.type == :added _queue_change(:dir, dir, rel_path, {}) # do nothing - changed directory means either: # - removed subdirs (handled above) # - added subdirs (handled above) # - removed files (handled by _file_callback) # - added files (handled by _file_callback) # so what's left? end end rescue details = event.inspect _log :error, format('wdm - callback (%s): %s:%s', details, $ERROR_INFO, $ERROR_POSITION * "\n") raise end def _change(type) { modified: [:modified, :attrib], # TODO: is attrib really passed? added: [:added, :renamed_new_file], removed: [:removed, :renamed_old_file] }.each do |change, types| return change if types.include?(type) end nil end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/listener/config.rb
_vendor/ruby/2.6.0/gems/listen-3.1.5/lib/listen/listener/config.rb
module Listen class Listener class Config DEFAULTS = { # Listener options debug: false, # TODO: is this broken? wait_for_delay: nil, # NOTE: should be provided by adapter if possible relative: false, # Backend selecting options force_polling: false, polling_fallback_message: nil }.freeze def initialize(opts) @options = DEFAULTS.merge(opts) @relative = @options[:relative] @min_delay_between_events = @options[:wait_for_delay] @silencer_rules = @options # silencer will extract what it needs end def relative? @relative end attr_reader :min_delay_between_events attr_reader :silencer_rules def adapter_instance_options(klass) valid_keys = klass.const_get('DEFAULTS').keys Hash[@options.select { |key, _| valid_keys.include?(key) }] end def adapter_select_options valid_keys = %w(force_polling polling_fallback_message).map(&:to_sym) Hash[@options.select { |key, _| valid_keys.include?(key) }] end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-paginate-1.1.0/spec/pagination_spec.rb
_vendor/ruby/2.6.0/gems/jekyll-paginate-1.1.0/spec/pagination_spec.rb
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-paginate-1.1.0/spec/spec_helper.rb
_vendor/ruby/2.6.0/gems/jekyll-paginate-1.1.0/spec/spec_helper.rb
require 'jekyll' require File.expand_path("../lib/jekyll-paginate", File.dirname(__FILE__)) module TestMethods def test_dir(*subdirs) File.join(File.dirname(__FILE__), *subdirs) end def dest_dir(*subdirs) test_dir('dest', *subdirs) end def source_dir(*subdirs) test_dir('source', *subdirs) end def build_configs(overrides, base_hash = Jekyll::Configuration::DEFAULTS) Jekyll::Utils.deep_merge_hashes(base_hash, overrides) end def site_configuration(overrides = {}) build_configs({ "source" => source_dir, "destination" => dest_dir }, build_configs(overrides)) end def build_site(config = {}) site = Jekyll::Site.new(site_configuration( {"paginate" => 1}.merge(config) )) site.process site end end RSpec.configure do |config| config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # These two settings work together to allow you to limit a spec run # to individual examples or groups you care about by tagging them with # `:focus` metadata. When nothing is tagged with `:focus`, all examples # get run. config.filter_run :focus config.run_all_when_everything_filtered = true # Limits the available syntax to the non-monkey patched syntax that is recommended. # For more details, see: # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching config.disable_monkey_patching! # This setting enables warnings. It's recommended, but in some cases may # be too noisy due to issues in dependencies. # config.warnings = true # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = 'doc' end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed include TestMethods end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-paginate-1.1.0/spec/pager_spec.rb
_vendor/ruby/2.6.0/gems/jekyll-paginate-1.1.0/spec/pager_spec.rb
require 'spec_helper' RSpec.describe(Jekyll::Paginate::Pager) do it "calculate number of pages" do expect(described_class.calculate_pages([], '2')).to eql(0) expect(described_class.calculate_pages([1], '2')).to eql(1) expect(described_class.calculate_pages([1,2], '2')).to eql(1) expect(described_class.calculate_pages([1,2,3], '2')).to eql(2) expect(described_class.calculate_pages([1,2,3,4], '2')).to eql(2) expect(described_class.calculate_pages([1,2,3,4,5], '2')).to eql(3) end context "with the default paginate_path" do let(:site) { build_site } it "determines the correct pagination path for each page" do expect(described_class.paginate_path(site, 1)).to eql("/index.html") expect(described_class.paginate_path(site, 2)).to eql("/page2") end end context "with paginate_path set to a subdirectory with no index.html" do let(:site) { build_site({'paginate_path' => '/blog/page-:num'}) } it "determines the correct pagination path for each page" do expect(described_class.paginate_path(site, 1)).to eql("/index.html") expect(described_class.paginate_path(site, 2)).to eql("/blog/page-2") end end context "with paginate_path set to a subdirectory with no index.html with num pages being in subdirectories" do let(:site) { build_site({'paginate_path' => '/blog/page/:num'}) } it "determines the correct pagination path for each page" do expect(described_class.paginate_path(site, 1)).to eql("/index.html") expect(described_class.paginate_path(site, 2)).to eql("/blog/page/2") end end context "with paginate_path set to a subdirectory wherein an index.html exists" do let(:site) { build_site({'paginate_path' => '/contacts/page:num'}) } it "determines the correct pagination path for each page" do expect(described_class.paginate_path(site, 1)).to eql("/contacts/index.html") expect(described_class.paginate_path(site, 2)).to eql("/contacts/page2") end end context "with paginate_path set to a subdir wherein an index.html exists with pages in subdirs" do let(:site) { build_site({'paginate_path' => '/contacts/page/:num'}) } it "determines the correct pagination path for each page" do expect(described_class.paginate_path(site, 1)).to eql("/contacts/index.html") expect(described_class.paginate_path(site, 2)).to eql("/contacts/page/2") end end context "pagination disabled" do let(:site) { build_site('paginate' => nil) } it "report that pagination is disabled" do expect(described_class.pagination_enabled?(site)).to be_falsey end end context "pagination enabled for 2" do let(:site) { build_site('paginate' => 2) } let(:posts) { site.posts } it "report that pagination is enabled" do expect(described_class.pagination_enabled?(site)).to be_truthy end context "with 4 posts" do let(:posts) { site.posts[1..4] } it "create first pager" do pager = described_class.new(site, 1, posts) expect(pager.posts.size).to eql(2) expect(pager.total_pages).to eql(2) expect(pager.previous_page).to be_nil expect(pager.next_page).to eql(2) end it "create second pager" do pager = described_class.new(site, 2, posts) expect(pager.posts.size).to eql(2) expect(pager.total_pages).to eql(2) expect(pager.previous_page).to eql(1) expect(pager.next_page).to be_nil end it "not create third pager" do expect { described_class.new(site, 3, posts) }.to raise_error end end context "with 5 posts" do let(:posts) { site.posts[1..5] } it "create first pager" do pager = described_class.new(site, 1, posts) expect(pager.posts.size).to eql(2) expect(pager.total_pages).to eql(3) expect(pager.previous_page).to be_nil expect(pager.next_page).to eql(2) end it "create second pager" do pager = described_class.new(site, 2, posts) expect(pager.posts.size).to eql(2) expect(pager.total_pages).to eql(3) expect(pager.previous_page).to eql(1) expect(pager.next_page).to eql(3) end it "create third pager" do pager = described_class.new(site, 3, posts) expect(pager.posts.size).to eql(1) expect(pager.total_pages).to eql(3) expect(pager.previous_page).to eql(2) expect(pager.next_page).to be_nil end it "not create fourth pager" do expect { described_class.new(site, 4, posts) }.to raise_error(RuntimeError) end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-paginate-1.1.0/lib/jekyll-paginate.rb
_vendor/ruby/2.6.0/gems/jekyll-paginate-1.1.0/lib/jekyll-paginate.rb
require "jekyll-paginate/version" require "jekyll-paginate/pager" require "jekyll-paginate/pagination" module Jekyll module Paginate end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-paginate-1.1.0/lib/jekyll-paginate/version.rb
_vendor/ruby/2.6.0/gems/jekyll-paginate-1.1.0/lib/jekyll-paginate/version.rb
module Jekyll module Paginate VERSION = "1.1.0" end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-paginate-1.1.0/lib/jekyll-paginate/pagination.rb
_vendor/ruby/2.6.0/gems/jekyll-paginate-1.1.0/lib/jekyll-paginate/pagination.rb
module Jekyll module Paginate class Pagination < Generator # This generator is safe from arbitrary code execution. safe true # This generator should be passive with regard to its execution priority :lowest # Generate paginated pages if necessary. # # site - The Site. # # Returns nothing. def generate(site) if Pager.pagination_enabled?(site) if template = template_page(site) paginate(site, template) else Jekyll.logger.warn "Pagination:", "Pagination is enabled, but I couldn't find " + "an index.html page to use as the pagination template. Skipping pagination." end end end # Paginates the blog's posts. Renders the index.html file into paginated # directories, e.g.: page2/index.html, page3/index.html, etc and adds more # site-wide data. # # site - The Site. # page - The index.html Page that requires pagination. # # {"paginator" => { "page" => <Number>, # "per_page" => <Number>, # "posts" => [<Post>], # "total_posts" => <Number>, # "total_pages" => <Number>, # "previous_page" => <Number>, # "next_page" => <Number> }} def paginate(site, page) all_posts = site.site_payload['site']['posts'] all_posts = all_posts.reject { |p| p['hidden'] } pages = Pager.calculate_pages(all_posts, site.config['paginate'].to_i) (1..pages).each do |num_page| pager = Pager.new(site, num_page, all_posts, pages) if num_page > 1 newpage = Page.new(site, site.source, page.dir, page.name) newpage.pager = pager newpage.dir = Pager.paginate_path(site, num_page) site.pages << newpage else page.pager = pager end end end # Static: Fetch the URL of the template page. Used to determine the # path to the first pager in the series. # # site - the Jekyll::Site object # # Returns the url of the template page def self.first_page_url(site) if page = Pagination.new.template_page(site) page.url else nil end end # Public: Find the Jekyll::Page which will act as the pager template # # site - the Jekyll::Site object # # Returns the Jekyll::Page which will act as the pager template def template_page(site) site.pages.dup.select do |page| Pager.pagination_candidate?(site.config, page) end.sort do |one, two| two.path.size <=> one.path.size end.first end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-paginate-1.1.0/lib/jekyll-paginate/pager.rb
_vendor/ruby/2.6.0/gems/jekyll-paginate-1.1.0/lib/jekyll-paginate/pager.rb
module Jekyll module Paginate class Pager attr_reader :page, :per_page, :posts, :total_posts, :total_pages, :previous_page, :previous_page_path, :next_page, :next_page_path # Calculate the number of pages. # # all_posts - The Array of all Posts. # per_page - The Integer of entries per page. # # Returns the Integer number of pages. def self.calculate_pages(all_posts, per_page) (all_posts.size.to_f / per_page.to_i).ceil end # Determine if pagination is enabled the site. # # site - the Jekyll::Site object # # Returns true if pagination is enabled, false otherwise. def self.pagination_enabled?(site) !site.config['paginate'].nil? && site.pages.size > 0 end # Static: Determine if a page is a possible candidate to be a template page. # Page's name must be `index.html` and exist in any of the directories # between the site source and `paginate_path`. # # config - the site configuration hash # page - the Jekyll::Page about which we're inquiring # # Returns true if the def self.pagination_candidate?(config, page) page_dir = File.dirname(File.expand_path(remove_leading_slash(page.path), config['source'])) paginate_path = remove_leading_slash(config['paginate_path']) paginate_path = File.expand_path(paginate_path, config['source']) page.name == 'index.html' && in_hierarchy(config['source'], page_dir, File.dirname(paginate_path)) end # Determine if the subdirectories of the two paths are the same relative to source # # source - the site source # page_dir - the directory of the Jekyll::Page # paginate_path - the absolute paginate path (from root of FS) # # Returns whether the subdirectories are the same relative to source def self.in_hierarchy(source, page_dir, paginate_path) return false if paginate_path == File.dirname(paginate_path) return false if paginate_path == Pathname.new(source).parent page_dir == paginate_path || in_hierarchy(source, page_dir, File.dirname(paginate_path)) end # Static: Return the pagination path of the page # # site - the Jekyll::Site object # num_page - the pagination page number # # Returns the pagination path as a string def self.paginate_path(site, num_page) return nil if num_page.nil? return Pagination.first_page_url(site) if num_page <= 1 format = site.config['paginate_path'] format = format.sub(':num', num_page.to_s) ensure_leading_slash(format) end # Static: Return a String version of the input which has a leading slash. # If the input already has a forward slash in position zero, it will be # returned unchanged. # # path - a String path # # Returns the path with a leading slash def self.ensure_leading_slash(path) path[0..0] == "/" ? path : "/#{path}" end # Static: Return a String version of the input without a leading slash. # # path - a String path # # Returns the input without the leading slash def self.remove_leading_slash(path) ensure_leading_slash(path)[1..-1] end # Initialize a new Pager. # # site - the Jekyll::Site object # page - The Integer page number. # all_posts - The Array of all the site's Posts. # num_pages - The Integer number of pages or nil if you'd like the number # of pages calculated. def initialize(site, page, all_posts, num_pages = nil) @page = page @per_page = site.config['paginate'].to_i @total_pages = num_pages || Pager.calculate_pages(all_posts, @per_page) if @page > @total_pages raise RuntimeError, "page number can't be greater than total pages: #{@page} > #{@total_pages}" end init = (@page - 1) * @per_page offset = (init + @per_page - 1) >= all_posts.size ? all_posts.size : (init + @per_page - 1) @total_posts = all_posts.size @posts = all_posts[init..offset] @previous_page = @page != 1 ? @page - 1 : nil @previous_page_path = Pager.paginate_path(site, @previous_page) @next_page = @page != @total_pages ? @page + 1 : nil @next_page_path = Pager.paginate_path(site, @next_page) end # Convert this Pager's data to a Hash suitable for use by Liquid. # # Returns the Hash representation of this Pager. def to_liquid { 'page' => page, 'per_page' => per_page, 'posts' => posts, 'total_posts' => total_posts, 'total_pages' => total_pages, 'previous_page' => previous_page, 'previous_page_path' => previous_page_path, 'next_page' => next_page, 'next_page_path' => next_page_path } end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/colorator-1.1.0/lib/colorator.rb
_vendor/ruby/2.6.0/gems/colorator-1.1.0/lib/colorator.rb
$:.unshift File.dirname(__FILE__) module Colorator module_function VERSION = "1.1.0" # -------------------------------------------------------------------------- ANSI_MATCHR = /\x1b.*?[jkmsuABGKH]/ ANSI_COLORS = { :black => 30, :red => 31, :green => 32, :yellow => 33, :blue => 34, :magenta => 35, :cyan => 36, :white => 37, :bold => 1 } # -------------------------------------------------------------------------- # Allows you to check if a string currently has ansi. # -------------------------------------------------------------------------- def has_ansi?(str) str.match(ANSI_MATCHR).is_a?( MatchData ) end # -------------------------------------------------------------------------- # Jump the cursor, moving it up and then back down to it's spot, allowing # you to do fancy things like multiple output (downloads) the way that Docker # does them in an async way without breaking term. # -------------------------------------------------------------------------- def ansi_jump(str, num) "\x1b[#{num}A#{clear_line(str)}\x1b[#{ num }B" end # -------------------------------------------------------------------------- def reset_ansi(str = "") "\x1b[0m#{ str }" end # -------------------------------------------------------------------------- def clear_line(str = "") "\x1b[2K\r#{ str }" end # -------------------------------------------------------------------------- # Strip ANSI from the current string, making it just a normal string. # -------------------------------------------------------------------------- def strip_ansi(str) str.gsub( ANSI_MATCHR, "" ) end # -------------------------------------------------------------------------- # Clear the screen's current view, so the user gets a clean output. # -------------------------------------------------------------------------- def clear_screen(str = "") "\x1b[H\x1b[2J#{ str }" end # -------------------------------------------------------------------------- def colorize(str = "", color) "\x1b[#{color}m#{str}\x1b[0m" end # -------------------------------------------------------------------------- Colorator::ANSI_COLORS.each do |color, code| define_singleton_method color do |str| colorize( str, code ) end end # -------------------------------------------------------------------------- class << self alias reset_color reset_ansi alias strip_color strip_ansi alias has_color? has_ansi? end # -------------------------------------------------------------------------- CORE_METHODS = ( public_methods - Object.methods ) end require "colorator/core_ext"
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/colorator-1.1.0/lib/colorator/core_ext.rb
_vendor/ruby/2.6.0/gems/colorator-1.1.0/lib/colorator/core_ext.rb
class String Colorator::CORE_METHODS.each do |method| define_method method do |*args| Colorator.public_send(method, self, *args ) end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen.rb
require 'logger' require 'sass-listen/logger' require 'sass-listen/listener' require 'sass-listen/internals/thread_pool' # Always set up logging by default first time file is required # # NOTE: If you need to clear the logger completely, do so *after* # requiring this file. If you need to set a custom logger, # require the listen/logger file and set the logger before requiring # this file. SassListen.setup_default_logger_if_unset # Won't print anything by default because of level - unless you've set # LISTEN_GEM_DEBUGGING or provided your own logger with a high enough level SassListen::Logger.info "SassListen loglevel set to: #{SassListen.logger.level}" SassListen::Logger.info "SassListen version: #{SassListen::VERSION}" module SassListen class << self # Listens to file system modifications on a either single directory or # multiple directories. # # @param (see SassListen::Listener#new) # # @yield [modified, added, removed] the changed files # @yieldparam [Array<String>] modified the list of modified files # @yieldparam [Array<String>] added the list of added files # @yieldparam [Array<String>] removed the list of removed files # # @return [SassListen::Listener] the listener # def to(*args, &block) @listeners ||= [] Listener.new(*args, &block).tap do |listener| @listeners << listener end end # This is used by the `listen` binary to handle Ctrl-C # def stop Internals::ThreadPool.stop @listeners ||= [] # TODO: should use a mutex for this @listeners.each do |listener| # call stop to halt the main loop listener.stop end @listeners = nil end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/directory.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/directory.rb
require 'set' module SassListen # TODO: refactor (turn it into a normal object, cache the stat, etc) class Directory def self.scan(snapshot, rel_path, options) record = snapshot.record dir = Pathname.new(record.root) previous = record.dir_entries(rel_path) record.add_dir(rel_path) # TODO: use children(with_directory: false) path = dir + rel_path current = Set.new(_children(path)) SassListen::Logger.debug do format('%s: %s(%s): %s -> %s', (options[:silence] ? 'Recording' : 'Scanning'), rel_path, options.inspect, previous.inspect, current.inspect) end begin current.each do |full_path| type = ::File.lstat(full_path.to_s).directory? ? :dir : :file item_rel_path = full_path.relative_path_from(dir).to_s _change(snapshot, type, item_rel_path, options) end rescue Errno::ENOENT # The directory changed meanwhile, so rescan it current = Set.new(_children(path)) retry end # TODO: this is not tested properly previous = previous.reject { |entry, _| current.include? path + entry } _async_changes(snapshot, Pathname.new(rel_path), previous, options) rescue Errno::ENOENT, Errno::EHOSTDOWN record.unset_path(rel_path) _async_changes(snapshot, Pathname.new(rel_path), previous, options) rescue Errno::ENOTDIR # TODO: path not tested record.unset_path(rel_path) _async_changes(snapshot, path, previous, options) _change(snapshot, :file, rel_path, options) rescue SassListen::Logger.warn do format('scan DIED: %s:%s', $ERROR_INFO, $ERROR_POSITION * "\n") end raise end def self._async_changes(snapshot, path, previous, options) fail "Not a Pathname: #{path.inspect}" unless path.respond_to?(:children) previous.each do |entry, data| # TODO: this is a hack with insufficient testing type = data.key?(:mtime) ? :file : :dir rel_path_s = (path + entry).to_s _change(snapshot, type, rel_path_s, options) end end def self._change(snapshot, type, path, options) return snapshot.invalidate(type, path, options) if type == :dir # Minor param cleanup for tests # TODO: use a dedicated Event class opts = options.dup opts.delete(:recursive) snapshot.invalidate(type, path, opts) end def self._children(path) return path.children unless RUBY_ENGINE == 'jruby' # JRuby inconsistency workaround, see: # https://github.com/jruby/jruby/issues/3840 exists = path.exist? directory = path.directory? return path.children unless (exists && !directory) raise Errno::ENOTDIR, path.to_s end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/record.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/record.rb
require 'thread' require 'sass-listen/record/entry' require 'sass-listen/record/symlink_detector' module SassListen class Record # TODO: one Record object per watched directory? # TODO: deprecate attr_reader :root def initialize(directory) @tree = _auto_hash @root = directory.to_s end def add_dir(rel_path) return if [nil, '', '.'].include? rel_path @tree[rel_path] ||= {} end def update_file(rel_path, data) dirname, basename = Pathname(rel_path).split.map(&:to_s) _fast_update_file(dirname, basename, data) end def unset_path(rel_path) dirname, basename = Pathname(rel_path).split.map(&:to_s) _fast_unset_path(dirname, basename) end def file_data(rel_path) dirname, basename = Pathname(rel_path).split.map(&:to_s) if [nil, '', '.'].include? dirname tree[basename] ||= {} tree[basename].dup else tree[dirname] ||= {} tree[dirname][basename] ||= {} tree[dirname][basename].dup end end def dir_entries(rel_path) subtree = if [nil, '', '.'].include? rel_path.to_s tree else tree[rel_path.to_s] ||= _auto_hash tree[rel_path.to_s] end result = {} subtree.each do |key, values| # only get data for file entries result[key] = values.key?(:mtime) ? values : {} end result end def build @tree = _auto_hash # TODO: test with a file name given # TODO: test other permissions # TODO: test with mixed encoding symlink_detector = SymlinkDetector.new remaining = ::Queue.new remaining << Entry.new(root, nil, nil) _fast_build_dir(remaining, symlink_detector) until remaining.empty? end private def _auto_hash Hash.new { |h, k| h[k] = Hash.new } end def tree @tree end def _fast_update_file(dirname, basename, data) if [nil, '', '.'].include? dirname tree[basename] = (tree[basename] || {}).merge(data) else tree[dirname] ||= {} tree[dirname][basename] = (tree[dirname][basename] || {}).merge(data) end end def _fast_unset_path(dirname, basename) # this may need to be reworked to properly remove # entries from a tree, without adding non-existing dirs to the record if [nil, '', '.'].include? dirname return unless tree.key?(basename) tree.delete(basename) else return unless tree.key?(dirname) tree[dirname].delete(basename) end end def _fast_build_dir(remaining, symlink_detector) entry = remaining.pop children = entry.children # NOTE: children() implicitly tests if dir symlink_detector.verify_unwatched!(entry) children.each { |child| remaining << child } add_dir(entry.record_dir_key) rescue Errno::ENOTDIR _fast_try_file(entry) rescue SystemCallError, SymlinkDetector::Error _fast_unset_path(entry.relative, entry.name) end def _fast_try_file(entry) _fast_update_file(entry.relative, entry.name, entry.meta) rescue SystemCallError _fast_unset_path(entry.relative, entry.name) end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/version.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/version.rb
module SassListen VERSION = '4.0.0' end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/change.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/change.rb
require 'sass-listen/file' require 'sass-listen/directory' module SassListen # TODO: rename to Snapshot class Change # TODO: test this class for coverage class Config def initialize(queue, silencer) @queue = queue @silencer = silencer end def silenced?(path, type) @silencer.silenced?(Pathname(path), type) end def queue(*args) @queue << args end end attr_reader :record def initialize(config, record) @config = config @record = record end # Invalidate some part of the snapshot/record (dir, file, subtree, etc.) def invalidate(type, rel_path, options) watched_dir = Pathname.new(record.root) change = options[:change] cookie = options[:cookie] if !cookie && config.silenced?(rel_path, type) SassListen::Logger.debug { "(silenced): #{rel_path.inspect}" } return end path = watched_dir + rel_path SassListen::Logger.debug do log_details = options[:silence] && 'recording' || change || 'unknown' "#{log_details}: #{type}:#{path} (#{options.inspect})" end if change options = cookie ? { cookie: cookie } : {} config.queue(type, change, watched_dir, rel_path, options) else if type == :dir # NOTE: POSSIBLE RECURSION # TODO: fix - use a queue instead Directory.scan(self, rel_path, options) else change = File.change(record, rel_path) return if !change || options[:silence] config.queue(:file, change, watched_dir, rel_path) end end rescue RuntimeError => ex msg = format( '%s#%s crashed %s:%s', self.class, __method__, exinspect, ex.backtrace * "\n") SassListen::Logger.error(msg) raise end private attr_reader :config end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/logger.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/logger.rb
module SassListen def self.logger @logger ||= nil end def self.logger=(logger) @logger = logger end def self.setup_default_logger_if_unset self.logger ||= ::Logger.new(STDERR).tap do |logger| debugging = ENV['LISTEN_GEM_DEBUGGING'] logger.level = case debugging.to_s when /2/ ::Logger::DEBUG when /true|yes|1/i ::Logger::INFO else ::Logger::ERROR end end end class Logger [:fatal, :error, :warn, :info, :debug].each do |meth| define_singleton_method(meth) do |*args, &block| SassListen.logger.public_send(meth, *args, &block) if SassListen.logger end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/options.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/options.rb
module SassListen class Options def initialize(opts, defaults) @options = {} given_options = opts.dup defaults.keys.each do |key| @options[key] = given_options.delete(key) || defaults[key] end return if given_options.empty? msg = "Unknown options: #{given_options.inspect}" SassListen::Logger.warn msg fail msg end def method_missing(name, *_) return @options[name] if @options.key?(name) msg = "Bad option: #{name.inspect} (valid:#{@options.keys.inspect})" fail NameError, msg end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/silencer.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/silencer.rb
module SassListen class Silencer # The default list of directories that get ignored. DEFAULT_IGNORED_DIRECTORIES = %r{^(?: \.git | \.svn | \.hg | \.rbx | \.bundle | bundle | vendor/bundle | log | tmp |vendor/ruby )(/|$)}x # The default list of files that get ignored. DEFAULT_IGNORED_EXTENSIONS = /(?: # Kate's tmp\/swp files \..*\d+\.new | \.kate-swp # Gedit tmp files | \.goutputstream-.{6} # Intellij files | ___jb_bak___ | ___jb_old___ # Vim swap files and write test | \.sw[px] | \.swpx | ^4913 # Sed temporary files - but without actual words, like 'sedatives' | (?:^ sed (?: [a-zA-Z0-9]{0}[A-Z]{1}[a-zA-Z0-9]{5} | [a-zA-Z0-9]{1}[A-Z]{1}[a-zA-Z0-9]{4} | [a-zA-Z0-9]{2}[A-Z]{1}[a-zA-Z0-9]{3} | [a-zA-Z0-9]{3}[A-Z]{1}[a-zA-Z0-9]{2} | [a-zA-Z0-9]{4}[A-Z]{1}[a-zA-Z0-9]{1} | [a-zA-Z0-9]{5}[A-Z]{1}[a-zA-Z0-9]{0} ) ) # other files | \.DS_Store | \.tmp | ~ )$/x attr_accessor :only_patterns, :ignore_patterns def initialize configure({}) end def configure(options) @only_patterns = options[:only] ? Array(options[:only]) : nil @ignore_patterns = _init_ignores(options[:ignore], options[:ignore!]) end # Note: relative_path is temporarily expected to be a relative Pathname to # make refactoring easier (ideally, it would take a string) # TODO: switch type and path places - and verify def silenced?(relative_path, type) path = relative_path.to_s if only_patterns && type == :file return true unless only_patterns.any? { |pattern| path =~ pattern } end ignore_patterns.any? { |pattern| path =~ pattern } end private attr_reader :options def _init_ignores(ignores, overrides) patterns = [] unless overrides patterns << DEFAULT_IGNORED_DIRECTORIES patterns << DEFAULT_IGNORED_EXTENSIONS end patterns << ignores patterns << overrides patterns.compact.flatten end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/file.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/file.rb
require 'digest/md5' module SassListen class File def self.change(record, rel_path) path = Pathname.new(record.root) + rel_path lstat = path.lstat data = { mtime: lstat.mtime.to_f, mode: lstat.mode } record_data = record.file_data(rel_path) if record_data.empty? record.update_file(rel_path, data) return :added end if data[:mode] != record_data[:mode] record.update_file(rel_path, data) return :modified end if data[:mtime] != record_data[:mtime] record.update_file(rel_path, data) return :modified end return if /1|true/ =~ ENV['LISTEN_GEM_DISABLE_HASHING'] return unless self.inaccurate_mac_time?(lstat) # Check if change happened within 1 second (maybe it's even # too much, e.g. 0.3-0.5 could be sufficient). # # With rb-fsevent, there's a (configurable) latency between # when file was changed and when the event was triggered. # # If a file is saved at ???14.998, by the time the event is # actually received by SassListen, the time could already be e.g. # ???15.7. # # And since Darwin adapter uses directory scanning, the file # mtime may be the same (e.g. file was changed at ???14.001, # then at ???14.998, but the fstat time would be ???14.0 in # both cases). # # If change happend at ???14.999997, the mtime is 14.0, so for # an mtime=???14.0 we assume it could even be almost ???15.0 # # So if Time.now.to_f is ???15.999998 and stat reports mtime # at ???14.0, then event was due to that file'd change when: # # ???15.999997 - ???14.999998 < 1.0s # # So the "2" is "1 + 1" (1s to cover rb-fsevent latency + # 1s maximum difference between real mtime and that recorded # in the file system) # return if data[:mtime].to_i + 2 <= Time.now.to_f md5 = Digest::MD5.file(path).digest record.update_file(rel_path, data.merge(md5: md5)) :modified if record_data[:md5] && md5 != record_data[:md5] rescue SystemCallError record.unset_path(rel_path) :removed rescue SassListen::Logger.debug "lstat failed for: #{rel_path} (#{$ERROR_INFO})" raise end def self.inaccurate_mac_time?(stat) # 'mac' means Modified/Accessed/Created # Since precision depends on mounted FS (e.g. you can have a FAT partiion # mounted on Linux), check for fields with a remainder to detect this [stat.mtime, stat.ctime, stat.atime].map(&:usec).all?(&:zero?) end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/adapter.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/adapter.rb
require 'sass-listen/adapter/base' require 'sass-listen/adapter/bsd' require 'sass-listen/adapter/darwin' require 'sass-listen/adapter/linux' require 'sass-listen/adapter/polling' require 'sass-listen/adapter/windows' module SassListen module Adapter OPTIMIZED_ADAPTERS = [Darwin, Linux, BSD, Windows] POLLING_FALLBACK_MESSAGE = 'SassListen will be polling for changes.'\ 'Learn more at https://github.com/guard/listen#listen-adapters.' def self.select(options = {}) _log :debug, 'Adapter: considering polling ...' return Polling if options[:force_polling] _log :debug, 'Adapter: considering optimized backend...' return _usable_adapter_class if _usable_adapter_class _log :debug, 'Adapter: falling back to polling...' _warn_polling_fallback(options) Polling rescue _log :warn, format('Adapter: failed: %s:%s', $ERROR_POSITION.inspect, $ERROR_POSITION * "\n") raise end private def self._usable_adapter_class OPTIMIZED_ADAPTERS.detect(&:usable?) end def self._warn_polling_fallback(options) msg = options.fetch(:polling_fallback_message, POLLING_FALLBACK_MESSAGE) Kernel.warn "[SassListen warning]:\n #{msg}" if msg end def self._log(type, message) SassListen::Logger.send(type, message) end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/fsm.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/fsm.rb
# Code copied from https://github.com/celluloid/celluloid-fsm module SassListen module FSM DEFAULT_STATE = :default # Default state name unless one is explicitly set # Included hook to extend class methods def self.included(klass) klass.send :extend, ClassMethods end module ClassMethods # Obtain or set the default state # Passing a state name sets the default state def default_state(new_default = nil) if new_default @default_state = new_default.to_sym else defined?(@default_state) ? @default_state : DEFAULT_STATE end end # Obtain the valid states for this FSM def states @states ||= {} end # Declare an FSM state and optionally provide a callback block to fire # Options: # * to: a state or array of states this state can transition to def state(*args, &block) if args.last.is_a? Hash # Stringify keys :/ options = args.pop.each_with_object({}) { |(k, v), h| h[k.to_s] = v } else options = {} end args.each do |name| name = name.to_sym default_state name if options['default'] states[name] = State.new(name, options['to'], &block) end end end # Be kind and call super if you must redefine initialize def initialize @state = self.class.default_state end # Obtain the current state of the FSM attr_reader :state def transition(state_name) new_state = validate_and_sanitize_new_state(state_name) return unless new_state transition_with_callbacks!(new_state) end # Immediate state transition with no checks, or callbacks. "Dangerous!" def transition!(state_name) @state = state_name end protected def validate_and_sanitize_new_state(state_name) state_name = state_name.to_sym return if current_state_name == state_name if current_state && !current_state.valid_transition?(state_name) valid = current_state.transitions.map(&:to_s).join(', ') msg = "#{self.class} can't change state from '#{@state}'"\ " to '#{state_name}', only to: #{valid}" fail ArgumentError, msg end new_state = states[state_name] unless new_state return if state_name == default_state fail ArgumentError, "invalid state for #{self.class}: #{state_name}" end new_state end def transition_with_callbacks!(state_name) transition! state_name.name state_name.call(self) end def states self.class.states end def default_state self.class.default_state end def current_state states[@state] end def current_state_name current_state && current_state.name || '' end class State attr_reader :name, :transitions def initialize(name, transitions = nil, &block) @name, @block = name, block @transitions = nil @transitions = Array(transitions).map(&:to_sym) if transitions end def call(obj) obj.instance_eval(&@block) if @block end def valid_transition?(new_state) # All transitions are allowed unless expressly return true unless @transitions @transitions.include? new_state.to_sym end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/backend.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/backend.rb
require 'sass-listen/adapter' require 'sass-listen/adapter/base' require 'sass-listen/adapter/config' require 'forwardable' # This class just aggregates configuration object to avoid Listener specs # from exploding with huge test setup blocks module SassListen class Backend def initialize(directories, queue, silencer, config) adapter_select_opts = config.adapter_select_options adapter_class = Adapter.select(adapter_select_opts) # Use default from adapter if possible @min_delay_between_events = config.min_delay_between_events @min_delay_between_events ||= adapter_class::DEFAULTS[:wait_for_delay] @min_delay_between_events ||= 0.1 adapter_opts = config.adapter_instance_options(adapter_class) aconfig = Adapter::Config.new(directories, queue, silencer, adapter_opts) @adapter = adapter_class.new(aconfig) end def start adapter.start end def stop adapter.stop end def min_delay_between_events @min_delay_between_events end private attr_reader :adapter end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/cli.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/cli.rb
require 'thor' require 'sass-listen' require 'logger' module SassListen class CLI < Thor default_task :start desc 'start', 'Starts SassListen' class_option :verbose, type: :boolean, default: false, aliases: '-v', banner: 'Verbose' class_option :directory, type: :array, default: '.', aliases: '-d', banner: 'The directory to listen to' class_option :relative, type: :boolean, default: false, aliases: '-r', banner: 'Convert paths relative to current directory' def start SassListen::Forwarder.new(options).start end end class Forwarder attr_reader :logger def initialize(options) @options = options @logger = ::Logger.new(STDOUT) @logger.level = ::Logger::INFO @logger.formatter = proc { |_, _, _, msg| "#{msg}\n" } end def start logger.info 'Starting listen...' directory = @options[:directory] relative = @options[:relative] callback = proc do |modified, added, removed| if @options[:verbose] logger.info "+ #{added}" unless added.empty? logger.info "- #{removed}" unless removed.empty? logger.info "> #{modified}" unless modified.empty? end end listener = SassListen.to( directory, relative: relative, &callback) listener.start sleep 0.5 while listener.processing? end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/queue_optimizer.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/queue_optimizer.rb
module SassListen class QueueOptimizer class Config def initialize(adapter_class, silencer) @adapter_class = adapter_class @silencer = silencer end def exist?(path) Pathname(path).exist? end def silenced?(path, type) @silencer.silenced?(path, type) end def debug(*args, &block) SassListen.logger.debug(*args, &block) end end def smoosh_changes(changes) # TODO: adapter could be nil at this point (shutdown) cookies = changes.group_by do |_, _, _, _, options| (options || {})[:cookie] end _squash_changes(_reinterpret_related_changes(cookies)) end def initialize(config) @config = config end private attr_reader :config # groups changes into the expected structure expected by # clients def _squash_changes(changes) # We combine here for backward compatibility # Newer clients should receive dir and path separately changes = changes.map { |change, dir, path| [change, dir + path] } actions = changes.group_by(&:last).map do |path, action_list| [_logical_action_for(path, action_list.map(&:first)), path.to_s] end config.debug("listen: raw changes: #{actions.inspect}") { modified: [], added: [], removed: [] }.tap do |squashed| actions.each do |type, path| squashed[type] << path unless type.nil? end config.debug("listen: final changes: #{squashed.inspect}") end end def _logical_action_for(path, actions) actions << :added if actions.delete(:moved_to) actions << :removed if actions.delete(:moved_from) modified = actions.detect { |x| x == :modified } _calculate_add_remove_difference(actions, path, modified) end def _calculate_add_remove_difference(actions, path, default_if_exists) added = actions.count { |x| x == :added } removed = actions.count { |x| x == :removed } diff = added - removed # TODO: avoid checking if path exists and instead assume the events are # in order (if last is :removed, it doesn't exist, etc.) if config.exist?(path) if diff > 0 :added elsif diff.zero? && added > 0 :modified else default_if_exists end else diff < 0 ? :removed : nil end end # remove extraneous rb-inotify events, keeping them only if it's a possible # editor rename() call (e.g. Kate and Sublime) def _reinterpret_related_changes(cookies) table = { moved_to: :added, moved_from: :removed } cookies.map do |_, changes| data = _detect_possible_editor_save(changes) if data to_dir, to_file = data [[:modified, to_dir, to_file]] else not_silenced = changes.reject do |type, _, _, path, _| config.silenced?(Pathname(path), type) end not_silenced.map do |_, change, dir, path, _| [table.fetch(change, change), dir, path] end end end.flatten(1) end def _detect_possible_editor_save(changes) return unless changes.size == 2 from_type = from_change = from = nil to_type = to_change = to_dir = to = nil changes.each do |data| case data[1] when :moved_from from_type, from_change, _, from, _ = data when :moved_to to_type, to_change, to_dir, to, _ = data else return nil end end return unless from && to # Expect an ignored moved_from and non-ignored moved_to # to qualify as an "editor modify" return unless config.silenced?(Pathname(from), from_type) config.silenced?(Pathname(to), to_type) ? nil : [to_dir, to] end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/listener.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/listener.rb
require 'English' require 'sass-listen/version' require 'sass-listen/backend' require 'sass-listen/silencer' require 'sass-listen/silencer/controller' require 'sass-listen/queue_optimizer' require 'sass-listen/fsm' require 'sass-listen/event/loop' require 'sass-listen/event/queue' require 'sass-listen/event/config' require 'sass-listen/listener/config' module SassListen class Listener include SassListen::FSM # Initializes the directories listener. # # @param [String] directory the directories to listen to # @param [Hash] options the listen options (see SassListen::Listener::Options) # # @yield [modified, added, removed] the changed files # @yieldparam [Array<String>] modified the list of modified files # @yieldparam [Array<String>] added the list of added files # @yieldparam [Array<String>] removed the list of removed files # def initialize(*dirs, &block) options = dirs.last.is_a?(Hash) ? dirs.pop : {} @config = Config.new(options) eq_config = Event::Queue::Config.new(@config.relative?) queue = Event::Queue.new(eq_config) { @processor.wakeup_on_event } silencer = Silencer.new rules = @config.silencer_rules @silencer_controller = Silencer::Controller.new(silencer, rules) @backend = Backend.new(dirs, queue, silencer, @config) optimizer_config = QueueOptimizer::Config.new(@backend, silencer) pconfig = Event::Config.new( self, queue, QueueOptimizer.new(optimizer_config), @backend.min_delay_between_events, &block) @processor = Event::Loop.new(pconfig) super() # FSM end default_state :initializing state :initializing, to: [:backend_started, :stopped] state :backend_started, to: [:frontend_ready, :stopped] do backend.start end state :frontend_ready, to: [:processing_events, :stopped] do processor.setup end state :processing_events, to: [:paused, :stopped] do processor.resume end state :paused, to: [:processing_events, :stopped] do processor.pause end state :stopped, to: [:backend_started] do backend.stop # should be before processor.teardown to halt events ASAP processor.teardown end # Starts processing events and starts adapters # or resumes invoking callbacks if paused def start transition :backend_started if state == :initializing transition :frontend_ready if state == :backend_started transition :processing_events if state == :frontend_ready transition :processing_events if state == :paused end # Stops both listening for events and processing them def stop transition :stopped end # Stops invoking callbacks (messages pile up) def pause transition :paused end # processing means callbacks are called def processing? state == :processing_events end def paused? state == :paused end def ignore(regexps) @silencer_controller.append_ignores(regexps) end def ignore!(regexps) @silencer_controller.replace_with_bang_ignores(regexps) end def only(regexps) @silencer_controller.replace_with_only(regexps) end private attr_reader :processor attr_reader :backend end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/silencer/controller.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/silencer/controller.rb
module SassListen class Silencer class Controller def initialize(silencer, default_options) @silencer = silencer opts = default_options @prev_silencer_options = {} rules = [:only, :ignore, :ignore!].map do |option| [option, opts[option]] if opts.key? option end _reconfigure_silencer(Hash[rules.compact]) end def append_ignores(*regexps) prev_ignores = Array(@prev_silencer_options[:ignore]) _reconfigure_silencer(ignore: [prev_ignores + regexps]) end def replace_with_bang_ignores(regexps) _reconfigure_silencer(ignore!: regexps) end def replace_with_only(regexps) _reconfigure_silencer(only: regexps) end private def _reconfigure_silencer(extra_options) opts = extra_options.dup opts = opts.map do |key, value| [key, Array(value).flatten.compact] end opts = Hash[opts] if opts.key?(:ignore) && opts[:ignore].empty? opts.delete(:ignore) end @prev_silencer_options = opts @silencer.configure(@prev_silencer_options.dup.freeze) end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/record/entry.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/record/entry.rb
module SassListen # @private api class Record # Represents a directory entry (dir or file) class Entry # file: "/home/me/watched_dir", "app/models", "foo.rb" # dir, "/home/me/watched_dir", "." def initialize(root, relative, name = nil) @root, @relative, @name = root, relative, name end attr_reader :root, :relative, :name def children child_relative = _join (_entries(sys_path) - %w(. ..)).map do |name| Entry.new(@root, child_relative, name) end end def meta lstat = ::File.lstat(sys_path) { mtime: lstat.mtime.to_f, mode: lstat.mode } end # record hash is e.g. # if @record["/home/me/watched_dir"]["project/app/models"]["foo.rb"] # if @record["/home/me/watched_dir"]["project/app"]["models"] # record_dir_key is "project/app/models" def record_dir_key ::File.join(*[@relative, @name].compact) end def sys_path # Use full path in case someone uses chdir ::File.join(*[@root, @relative, @name].compact) end def real_path @real_path ||= ::File.realpath(sys_path) end private def _join args = [@relative, @name].compact args.empty? ? nil : ::File.join(*args) end def _entries(dir) return Dir.entries(dir) unless RUBY_ENGINE == 'jruby' # JRuby inconsistency workaround, see: # https://github.com/jruby/jruby/issues/3840 exists = ::File.exist?(dir) directory = ::File.directory?(dir) return Dir.entries(dir) unless (exists && !directory) raise Errno::ENOTDIR, dir end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/record/symlink_detector.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/record/symlink_detector.rb
require 'set' module SassListen # @private api class Record class SymlinkDetector WIKI = 'https://github.com/guard/listen/wiki/Duplicate-directory-errors' SYMLINK_LOOP_ERROR = <<-EOS ** ERROR: directory is already being watched! ** Directory: %s is already being watched through: %s MORE INFO: #{WIKI} EOS class Error < RuntimeError end def initialize @real_dirs = Set.new end def verify_unwatched!(entry) real_path = entry.real_path @real_dirs.add?(real_path) || _fail(entry.sys_path, real_path) end private def _fail(symlinked, real_path) STDERR.puts format(SYMLINK_LOOP_ERROR, symlinked, real_path) fail Error, 'Failed due to looped symlinks' end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/internals/thread_pool.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/internals/thread_pool.rb
module SassListen # @private api module Internals module ThreadPool def self.add(&block) Thread.new { block.call }.tap do |th| (@threads ||= Queue.new) << th end end def self.stop return unless @threads ||= nil return if @threads.empty? # return to avoid using possibly stubbed Queue killed = Queue.new # You can't kill a read on a descriptor in JRuby, so let's just # ignore running threads (listen rb-inotify waiting for disk activity # before closing) pray threads die faster than they are created... limit = RUBY_ENGINE == 'jruby' ? [1] : [] killed << @threads.pop.kill until @threads.empty? until killed.empty? th = killed.pop th.join(*limit) unless th[:listen_blocking_read_thread] end end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/event/processor.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/event/processor.rb
module SassListen module Event class Processor def initialize(config, reasons) @config = config @reasons = reasons _reset_no_unprocessed_events end # TODO: implement this properly instead of checking the state at arbitrary # points in time def loop_for(latency) @latency = latency loop do _wait_until_events _wait_until_events_calm_down _wait_until_no_longer_paused _process_changes end rescue Stopped SassListen::Logger.debug('Processing stopped') end private class Stopped < RuntimeError end def _wait_until_events_calm_down loop do now = _timestamp # Assure there's at least latency between callbacks to allow # for accumulating changes diff = _deadline - now break if diff <= 0 # give events a bit of time to accumulate so they can be # compressed/optimized _sleep(:waiting_until_latency, diff) end end def _wait_until_no_longer_paused # TODO: may not be a good idea? _sleep(:waiting_for_unpause) while config.paused? end def _check_stopped return unless config.stopped? _flush_wakeup_reasons raise Stopped end def _sleep(_local_reason, *args) _check_stopped sleep_duration = config.sleep(*args) _check_stopped _flush_wakeup_reasons do |reason| next unless reason == :event _remember_time_of_first_unprocessed_event unless config.paused? end sleep_duration end def _remember_time_of_first_unprocessed_event @first_unprocessed_event_time ||= _timestamp end def _reset_no_unprocessed_events @first_unprocessed_event_time = nil end def _deadline @first_unprocessed_event_time + @latency end def _wait_until_events # TODO: long sleep may not be a good idea? _sleep(:waiting_for_events) while config.event_queue.empty? @first_unprocessed_event_time ||= _timestamp end def _flush_wakeup_reasons reasons = @reasons until reasons.empty? reason = reasons.pop yield reason if block_given? end end def _timestamp config.timestamp end # for easier testing without sleep loop def _process_changes _reset_no_unprocessed_events changes = [] changes << config.event_queue.pop until config.event_queue.empty? callable = config.callable? return unless callable hash = config.optimize_changes(changes) result = [hash[:modified], hash[:added], hash[:removed]] return if result.all?(&:empty?) block_start = _timestamp config.call(*result) SassListen::Logger.debug "Callback took #{_timestamp - block_start} sec" end attr_reader :config end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/event/queue.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/event/queue.rb
require 'thread' require 'forwardable' module SassListen module Event class Queue class Config def initialize(relative) @relative = relative end def relative? @relative end end def initialize(config, &block) @event_queue = ::Queue.new @block = block @config = config end def <<(args) type, change, dir, path, options = *args fail "Invalid type: #{type.inspect}" unless [:dir, :file].include? type fail "Invalid change: #{change.inspect}" unless change.is_a?(Symbol) fail "Invalid path: #{path.inspect}" unless path.is_a?(String) dir = _safe_relative_from_cwd(dir) event_queue.public_send(:<<, [type, change, dir, path, options]) block.call(args) if block end def empty? event_queue.empty? end def pop event_queue.pop end private attr_reader :event_queue attr_reader :block attr_reader :config def _safe_relative_from_cwd(dir) return dir unless config.relative? dir.relative_path_from(Pathname.pwd) rescue ArgumentError dir end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/event/loop.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/event/loop.rb
require 'thread' require 'timeout' require 'sass-listen/event/processor' module SassListen module Event class Loop class Error < RuntimeError class NotStarted < Error end end def initialize(config) @config = config @wait_thread = nil @state = :paused @reasons = ::Queue.new end def wakeup_on_event return if stopped? return unless processing? return unless wait_thread.alive? _wakeup(:event) end def paused? wait_thread && state == :paused end def processing? return false if stopped? return false if paused? state == :processing end def setup # TODO: use a Fiber instead? q = ::Queue.new @wait_thread = Internals::ThreadPool.add do _wait_for_changes(q, config) end SassListen::Logger.debug('Waiting for processing to start...') Timeout.timeout(5) { q.pop } end def resume fail Error::NotStarted if stopped? return unless wait_thread _wakeup(:resume) end def pause # TODO: works? # fail NotImplementedError end def teardown return unless wait_thread if wait_thread.alive? _wakeup(:teardown) wait_thread.join end @wait_thread = nil end def stopped? !wait_thread end private attr_reader :config attr_reader :wait_thread attr_accessor :state def _wait_for_changes(ready_queue, config) processor = Event::Processor.new(config, @reasons) _wait_until_resumed(ready_queue) processor.loop_for(config.min_delay_between_events) rescue StandardError => ex _nice_error(ex) end def _sleep(*args) Kernel.sleep(*args) end def _wait_until_resumed(ready_queue) self.state = :paused ready_queue << :ready sleep self.state = :processing end def _nice_error(ex) indent = "\n -- " msg = format( 'exception while processing events: %s Backtrace:%s%s', ex, indent, ex.backtrace * indent ) SassListen::Logger.error(msg) end def _wakeup(reason) @reasons << reason wait_thread.wakeup end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/event/config.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/event/config.rb
module SassListen module Event class Config def initialize( listener, event_queue, queue_optimizer, wait_for_delay, &block) @listener = listener @event_queue = event_queue @queue_optimizer = queue_optimizer @min_delay_between_events = wait_for_delay @block = block end def sleep(*args) Kernel.sleep(*args) end def call(*args) @block.call(*args) if @block end def timestamp Time.now.to_f end def event_queue @event_queue end def callable? @block end def optimize_changes(changes) @queue_optimizer.smoosh_changes(changes) end def min_delay_between_events @min_delay_between_events end def stopped? listener.state == :stopped end def paused? listener.state == :paused end private attr_reader :listener end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/adapter/polling.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/adapter/polling.rb
module SassListen module Adapter # Polling Adapter that works cross-platform and # has no dependencies. This is the adapter that # uses the most CPU processing power and has higher # file IO than the other implementations. # class Polling < Base OS_REGEXP = // # match every OS DEFAULTS = { latency: 1.0, wait_for_delay: 0.05 } private def _configure(_, &callback) @polling_callbacks ||= [] @polling_callbacks << callback end def _run loop do start = Time.now.to_f @polling_callbacks.each do |callback| callback.call(nil) nap_time = options.latency - (Time.now.to_f - start) # TODO: warn if nap_time is negative (polling too slow) sleep(nap_time) if nap_time > 0 end end end def _process_event(dir, _) _queue_change(:dir, dir, '.', recursive: true) end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/adapter/base.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/adapter/base.rb
require 'sass-listen/options' require 'sass-listen/record' require 'sass-listen/change' module SassListen module Adapter class Base attr_reader :options # TODO: only used by tests DEFAULTS = {} attr_reader :config def initialize(config) @started = false @config = config @configured = nil fail 'No directories to watch!' if config.directories.empty? defaults = self.class.const_get('DEFAULTS') @options = SassListen::Options.new(config.adapter_options, defaults) rescue _log_exception 'adapter config failed: %s:%s called from: %s', caller raise end # TODO: it's a separate method as a temporary workaround for tests def configure if @configured _log(:warn, 'Adapter already configured!') return end @configured = true @callbacks ||= {} config.directories.each do |dir| callback = @callbacks[dir] || lambda do |event| _process_event(dir, event) end @callbacks[dir] = callback _configure(dir, &callback) end @snapshots ||= {} # TODO: separate config per directory (some day maybe) change_config = Change::Config.new(config.queue, config.silencer) config.directories.each do |dir| record = Record.new(dir) snapshot = Change.new(change_config, record) @snapshots[dir] = snapshot end end def started? @started end def start configure if started? _log(:warn, 'Adapter already started!') return end @started = true calling_stack = caller.dup SassListen::Internals::ThreadPool.add do begin @snapshots.values.each do |snapshot| _timed('Record.build()') { snapshot.record.build } end _run rescue msg = 'run() in thread failed: %s:\n'\ ' %s\n\ncalled from:\n %s' _log_exception(msg, calling_stack) raise # for unit tests mostly end end end def stop _stop end def self.usable? const_get('OS_REGEXP') =~ RbConfig::CONFIG['target_os'] end private def _stop end def _timed(title) start = Time.now.to_f yield diff = Time.now.to_f - start SassListen::Logger.info format('%s: %.05f seconds', title, diff) rescue SassListen::Logger.warn "#{title} crashed: #{$ERROR_INFO.inspect}" raise end # TODO: allow backend adapters to pass specific invalidation objects # e.g. Darwin -> DirRescan, INotify -> MoveScan, etc. def _queue_change(type, dir, rel_path, options) @snapshots[dir].invalidate(type, rel_path, options) end def _log(*args, &block) self.class.send(:_log, *args, &block) end def _log_exception(msg, caller_stack) formatted = format( msg, $ERROR_INFO, $ERROR_POSITION * "\n", caller_stack * "\n" ) _log(:error, formatted) end def self._log(*args, &block) SassListen::Logger.send(*args, &block) end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/adapter/darwin.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/adapter/darwin.rb
require 'thread' require 'sass-listen/internals/thread_pool' module SassListen module Adapter # Adapter implementation for Mac OS X `FSEvents`. # class Darwin < Base OS_REGEXP = /darwin(?<major_version>1\d+)/i # The default delay between checking for changes. DEFAULTS = { latency: 0.1 } INCOMPATIBLE_GEM_VERSION = <<-EOS.gsub(/^ {8}/, '') rb-fsevent > 0.9.4 no longer supports OS X 10.6 through 10.8. Please add the following to your Gemfile to avoid polling for changes: require 'rbconfig' if RbConfig::CONFIG['target_os'] =~ /darwin(1[0-3])/i gem 'rb-fsevent', '<= 0.9.4' end EOS def self.usable? require 'rb-fsevent' darwin_version = RbConfig::CONFIG['target_os'][OS_REGEXP, :major_version] or return false return true if darwin_version.to_i >= 13 # darwin13 is OS X 10.9 return true if Gem::Version.new(FSEvent::VERSION) <= Gem::Version.new('0.9.4') Kernel.warn INCOMPATIBLE_GEM_VERSION false end private # NOTE: each directory gets a DIFFERENT callback! def _configure(dir, &callback) opts = { latency: options.latency } @workers ||= ::Queue.new @workers << FSEvent.new.tap do |worker| _log :debug, "fsevent: watching: #{dir.to_s.inspect}" worker.watch(dir.to_s, opts, &callback) end end def _run first = @workers.pop # NOTE: _run is called within a thread, so run every other # worker in it's own thread _run_workers_in_background(_to_array(@workers)) _run_worker(first) end def _process_event(dir, event) _log :debug, "fsevent: processing event: #{event.inspect}" event.each do |path| new_path = Pathname.new(path.sub(/\/$/, '')) _log :debug, "fsevent: #{new_path}" # TODO: does this preserve symlinks? rel_path = new_path.relative_path_from(dir).to_s _queue_change(:dir, dir, rel_path, recursive: true) end end def _run_worker(worker) _log :debug, "fsevent: running worker: #{worker.inspect}" worker.run rescue _log_exception 'fsevent: running worker failed: %s:%s called from: %s', caller end def _run_workers_in_background(workers) workers.each do |worker| # NOTE: while passing local variables to the block below is not # thread safe, using 'worker' from the enumerator above is ok SassListen::Internals::ThreadPool.add { _run_worker(worker) } end end def _to_array(queue) workers = [] workers << queue.pop until queue.empty? workers end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/adapter/linux.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/adapter/linux.rb
module SassListen module Adapter # @see https://github.com/nex3/rb-inotify class Linux < Base OS_REGEXP = /linux/i DEFAULTS = { events: [ :recursive, :attrib, :create, :delete, :move, :close_write ], wait_for_delay: 0.1 } private WIKI_URL = 'https://github.com/guard/listen'\ '/wiki/Increasing-the-amount-of-inotify-watchers' INOTIFY_LIMIT_MESSAGE = <<-EOS.gsub(/^\s*/, '') FATAL: SassListen error: unable to monitor directories for changes. Visit #{WIKI_URL} for info on how to fix this. EOS def _configure(directory, &callback) require 'rb-inotify' @worker ||= ::INotify::Notifier.new @worker.watch(directory.to_s, *options.events, &callback) rescue Errno::ENOSPC abort(INOTIFY_LIMIT_MESSAGE) end def _run Thread.current[:listen_blocking_read_thread] = true @worker.run Thread.current[:listen_blocking_read_thread] = false end def _process_event(dir, event) # NOTE: avoid using event.absolute_name since new API # will need to have a custom recursion implemented # to properly match events to configured directories path = Pathname.new(event.watcher.path) + event.name rel_path = path.relative_path_from(dir).to_s _log(:debug) { "inotify: #{rel_path} (#{event.flags.inspect})" } if /1|true/ =~ ENV['LISTEN_GEM_SIMULATE_FSEVENT'] if (event.flags & [:moved_to, :moved_from]) || _dir_event?(event) rel_path = path.dirname.relative_path_from(dir).to_s _queue_change(:dir, dir, rel_path, {}) else _queue_change(:dir, dir, rel_path, {}) end return end return if _skip_event?(event) cookie_params = event.cookie.zero? ? {} : { cookie: event.cookie } # Note: don't pass options to force rescanning the directory, so we can # detect moving/deleting a whole tree if _dir_event?(event) _queue_change(:dir, dir, rel_path, cookie_params) return end params = cookie_params.merge(change: _change(event.flags)) _queue_change(:file, dir, rel_path, params) end def _skip_event?(event) # Event on root directory return true if event.name == '' # INotify reports changes to files inside directories as events # on the directories themselves too. # # @see http://linux.die.net/man/7/inotify _dir_event?(event) && (event.flags & [:close, :modify]).any? end def _change(event_flags) { modified: [:attrib, :close_write], moved_to: [:moved_to], moved_from: [:moved_from], added: [:create], removed: [:delete] }.each do |change, flags| return change unless (flags & event_flags).empty? end nil end def _dir_event?(event) event.flags.include?(:isdir) end def _stop @worker && @worker.close end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/adapter/config.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/adapter/config.rb
require 'pathname' module SassListen module Adapter class Config attr_reader :directories attr_reader :silencer attr_reader :queue attr_reader :adapter_options def initialize(directories, queue, silencer, adapter_options) # Default to current directory if no directories are supplied directories = [Dir.pwd] if directories.to_a.empty? # TODO: fix (flatten, array, compact?) @directories = directories.map do |directory| Pathname.new(directory.to_s).realpath end @silencer = silencer @queue = queue @adapter_options = adapter_options end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/adapter/bsd.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/adapter/bsd.rb
# Listener implementation for BSD's `kqueue`. # @see http://www.freebsd.org/cgi/man.cgi?query=kqueue # @see https://github.com/mat813/rb-kqueue/blob/master/lib/rb-kqueue/queue.rb # module SassListen module Adapter class BSD < Base OS_REGEXP = /bsd|dragonfly/i DEFAULTS = { events: [ :delete, :write, :extend, :attrib, :rename # :link, :revoke ] } BUNDLER_DECLARE_GEM = <<-EOS.gsub(/^ {6}/, '') Please add the following to your Gemfile to avoid polling for changes: require 'rbconfig' if RbConfig::CONFIG['target_os'] =~ /#{OS_REGEXP}/ gem 'rb-kqueue', '>= 0.2' end EOS def self.usable? return false unless super require 'rb-kqueue' require 'find' true rescue LoadError Kernel.warn BUNDLER_DECLARE_GEM false end private def _configure(directory, &_callback) @worker ||= KQueue::Queue.new @callback = _callback # use Record to make a snapshot of dir, so we # can detect new files _find(directory.to_s) { |path| _watch_file(path, @worker) } end def _run @worker.run end def _process_event(dir, event) full_path = _event_path(event) if full_path.directory? # Force dir content tracking to kick in, or we won't have # names of added files _queue_change(:dir, dir, '.', recursive: true) elsif full_path.exist? path = full_path.relative_path_from(dir) _queue_change(:file, dir, path.to_s, change: _change(event.flags)) end # If it is a directory, and it has a write flag, it means a # file has been added so find out which and deal with it. # No need to check for removed files, kqueue will forget them # when the vfs does. _watch_for_new_file(event) if full_path.directory? end def _change(event_flags) { modified: [:attrib, :extend], added: [:write], removed: [:rename, :delete] }.each do |change, flags| return change unless (flags & event_flags).empty? end nil end def _event_path(event) Pathname.new(event.watcher.path) end def _watch_for_new_file(event) queue = event.watcher.queue _find(_event_path(event).to_s) do |file_path| unless queue.watchers.detect { |_, v| v.path == file_path.to_s } _watch_file(file_path, queue) end end end def _watch_file(path, queue) queue.watch_file(path, *options.events, &@callback) rescue Errno::ENOENT => e _log :warn, "kqueue: watch file failed: #{e.message}" end # Quick rubocop workaround def _find(*paths, &block) Find.send(:find, *paths, &block) end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/adapter/windows.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/adapter/windows.rb
module SassListen module Adapter # Adapter implementation for Windows `wdm`. # class Windows < Base OS_REGEXP = /mswin|mingw|cygwin/i BUNDLER_DECLARE_GEM = <<-EOS.gsub(/^ {6}/, '') Please add the following to your Gemfile to avoid polling for changes: gem 'wdm', '>= 0.1.0' if Gem.win_platform? EOS def self.usable? return false unless super require 'wdm' true rescue LoadError _log :debug, format('wdm - load failed: %s:%s', $ERROR_INFO, $ERROR_POSITION * "\n") Kernel.warn BUNDLER_DECLARE_GEM false end private def _configure(dir, &callback) require 'wdm' _log :debug, 'wdm - starting...' @worker ||= WDM::Monitor.new @worker.watch_recursively(dir.to_s, :files) do |change| callback.call([:file, change]) end @worker.watch_recursively(dir.to_s, :directories) do |change| callback.call([:dir, change]) end events = [:attributes, :last_write] @worker.watch_recursively(dir.to_s, *events) do |change| callback.call([:attr, change]) end end def _run @worker.run! end def _process_event(dir, event) _log :debug, "wdm - callback: #{event.inspect}" type, change = event full_path = Pathname(change.path) rel_path = full_path.relative_path_from(dir).to_s options = { change: _change(change.type) } case type when :file _queue_change(:file, dir, rel_path, options) when :attr unless full_path.directory? _queue_change(:file, dir, rel_path, options) end when :dir if change.type == :removed # TODO: check if watched dir? _queue_change(:dir, dir, Pathname(rel_path).dirname.to_s, {}) elsif change.type == :added _queue_change(:dir, dir, rel_path, {}) else # do nothing - changed directory means either: # - removed subdirs (handled above) # - added subdirs (handled above) # - removed files (handled by _file_callback) # - added files (handled by _file_callback) # so what's left? end end rescue details = event.inspect _log :error, format('wdm - callback (%): %s:%s', details, $ERROR_INFO, $ERROR_POSITION * "\n") raise end def _change(type) { modified: [:modified, :attrib], # TODO: is attrib really passed? added: [:added, :renamed_new_file], removed: [:removed, :renamed_old_file] }.each do |change, types| return change if types.include?(type) end nil end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/listener/config.rb
_vendor/ruby/2.6.0/gems/sass-listen-4.0.0/lib/sass-listen/listener/config.rb
module SassListen class Listener class Config DEFAULTS = { # Listener options debug: false, # TODO: is this broken? wait_for_delay: nil, # NOTE: should be provided by adapter if possible relative: false, # Backend selecting options force_polling: false, polling_fallback_message: nil } def initialize(opts) @options = DEFAULTS.merge(opts) @relative = @options[:relative] @min_delay_between_events = @options[:wait_for_delay] @silencer_rules = @options # silencer will extract what it needs end def relative? @relative end def min_delay_between_events @min_delay_between_events end def silencer_rules @silencer_rules end def adapter_instance_options(klass) valid_keys = klass.const_get('DEFAULTS').keys Hash[@options.select { |key, _| valid_keys.include?(key) }] end def adapter_select_options valid_keys = %w(force_polling polling_fallback_message).map(&:to_sym) Hash[@options.select { |key, _| valid_keys.include?(key) }] end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-3.8.4/rubocop/jekyll.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/rubocop/jekyll.rb
# frozen_string_literal: true Dir[File.join(File.expand_path("jekyll", __dir__), "*.rb")].each do |ruby_file| require ruby_file end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-3.8.4/rubocop/jekyll/no_puts_allowed.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/rubocop/jekyll/no_puts_allowed.rb
# frozen_string_literal: true require "rubocop" module RuboCop module Cop module Jekyll class NoPutsAllowed < Cop MSG = "Avoid using `puts` to print things. Use `Jekyll.logger` instead.".freeze def_node_search :puts_called?, <<-PATTERN (send nil? :puts _) PATTERN def on_send(node) if puts_called?(node) add_offense(node, :location => :selector) end end end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-3.8.4/rubocop/jekyll/no_p_allowed.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/rubocop/jekyll/no_p_allowed.rb
# frozen_string_literal: true require "rubocop" module RuboCop module Cop module Jekyll class NoPAllowed < Cop MSG = "Avoid using `p` to print things. Use `Jekyll.logger` instead.".freeze def_node_search :p_called?, <<-PATTERN (send _ :p _) PATTERN def on_send(node) if p_called?(node) add_offense(node, :location => :selector) end end end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll.rb
# frozen_string_literal: true $LOAD_PATH.unshift __dir__ # For use/testing when no gem is installed # Require all of the Ruby files in the given directory. # # path - The String relative path from here to the directory. # # Returns nothing. def require_all(path) glob = File.join(__dir__, path, "*.rb") Dir[glob].sort.each do |f| require f end end # rubygems require "rubygems" # stdlib require "forwardable" require "fileutils" require "time" require "English" require "pathname" require "logger" require "set" require "csv" require "json" # 3rd party require "pathutil" require "addressable/uri" require "safe_yaml/load" require "liquid" require "kramdown" require "colorator" require "i18n" SafeYAML::OPTIONS[:suppress_warnings] = true module Jekyll # internal requires autoload :Cleaner, "jekyll/cleaner" autoload :Collection, "jekyll/collection" autoload :Configuration, "jekyll/configuration" autoload :Convertible, "jekyll/convertible" autoload :Deprecator, "jekyll/deprecator" autoload :Document, "jekyll/document" autoload :EntryFilter, "jekyll/entry_filter" autoload :Errors, "jekyll/errors" autoload :Excerpt, "jekyll/excerpt" autoload :External, "jekyll/external" autoload :FrontmatterDefaults, "jekyll/frontmatter_defaults" autoload :Hooks, "jekyll/hooks" autoload :Layout, "jekyll/layout" autoload :CollectionReader, "jekyll/readers/collection_reader" autoload :DataReader, "jekyll/readers/data_reader" autoload :LayoutReader, "jekyll/readers/layout_reader" autoload :PostReader, "jekyll/readers/post_reader" autoload :PageReader, "jekyll/readers/page_reader" autoload :StaticFileReader, "jekyll/readers/static_file_reader" autoload :ThemeAssetsReader, "jekyll/readers/theme_assets_reader" autoload :LogAdapter, "jekyll/log_adapter" autoload :Page, "jekyll/page" autoload :PageWithoutAFile, "jekyll/page_without_a_file" autoload :PluginManager, "jekyll/plugin_manager" autoload :Publisher, "jekyll/publisher" autoload :Reader, "jekyll/reader" autoload :Regenerator, "jekyll/regenerator" autoload :RelatedPosts, "jekyll/related_posts" autoload :Renderer, "jekyll/renderer" autoload :LiquidRenderer, "jekyll/liquid_renderer" autoload :Site, "jekyll/site" autoload :StaticFile, "jekyll/static_file" autoload :Stevenson, "jekyll/stevenson" autoload :Theme, "jekyll/theme" autoload :ThemeBuilder, "jekyll/theme_builder" autoload :URL, "jekyll/url" autoload :Utils, "jekyll/utils" autoload :VERSION, "jekyll/version" # extensions require "jekyll/plugin" require "jekyll/converter" require "jekyll/generator" require "jekyll/command" require "jekyll/liquid_extensions" require "jekyll/filters" class << self # Public: Tells you which Jekyll environment you are building in so you can skip tasks # if you need to. This is useful when doing expensive compression tasks on css and # images and allows you to skip that when working in development. def env ENV["JEKYLL_ENV"] || "development" end # Public: Generate a Jekyll configuration Hash by merging the default # options with anything in _config.yml, and adding the given options on top. # # override - A Hash of config directives that override any options in both # the defaults and the config file. # See Jekyll::Configuration::DEFAULTS for a # list of option names and their defaults. # # Returns the final configuration Hash. def configuration(override = {}) config = Configuration.new override = Configuration[override].stringify_keys unless override.delete("skip_config_files") config = config.read_config_files(config.config_files(override)) end # Merge DEFAULTS < _config.yml < override Configuration.from(Utils.deep_merge_hashes(config, override)).tap do |obj| set_timezone(obj["timezone"]) if obj["timezone"] end end # Public: Set the TZ environment variable to use the timezone specified # # timezone - the IANA Time Zone # # Returns nothing # rubocop:disable Naming/AccessorMethodName def set_timezone(timezone) ENV["TZ"] = if Utils::Platforms.really_windows? Utils::WinTZ.calculate(timezone) else timezone end end # rubocop:enable Naming/AccessorMethodName # Public: Fetch the logger instance for this Jekyll process. # # Returns the LogAdapter instance. def logger @logger ||= LogAdapter.new(Stevenson.new, (ENV["JEKYLL_LOG_LEVEL"] || :info).to_sym) end # Public: Set the log writer. # New log writer must respond to the same methods # as Ruby's interal Logger. # # writer - the new Logger-compatible log transport # # Returns the new logger. def logger=(writer) @logger = LogAdapter.new(writer, (ENV["JEKYLL_LOG_LEVEL"] || :info).to_sym) end # Public: An array of sites # # Returns the Jekyll sites created. def sites @sites ||= [] end # Public: Ensures the questionable path is prefixed with the base directory # and prepends the questionable path with the base directory if false. # # base_directory - the directory with which to prefix the questionable path # questionable_path - the path we're unsure about, and want prefixed # # Returns the sanitized path. def sanitized_path(base_directory, questionable_path) return base_directory if base_directory.eql?(questionable_path) clean_path = questionable_path.dup clean_path.insert(0, "/") if clean_path.start_with?("~") clean_path = File.expand_path(clean_path, "/") return clean_path if clean_path.eql?(base_directory) if clean_path.start_with?(base_directory.sub(%r!\z!, "/")) clean_path else clean_path.sub!(%r!\A\w:/!, "/") File.join(base_directory, clean_path) end end # Conditional optimizations Jekyll::External.require_if_present("liquid-c") end end require "jekyll/drops/drop" require "jekyll/drops/document_drop" require_all "jekyll/commands" require_all "jekyll/converters" require_all "jekyll/converters/markdown" require_all "jekyll/drops" require_all "jekyll/generators" require_all "jekyll/tags" require "jekyll-sass-converter"
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/command.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/command.rb
# frozen_string_literal: true module Jekyll class Command class << self # A list of subclasses of Jekyll::Command def subclasses @subclasses ||= [] end # Keep a list of subclasses of Jekyll::Command every time it's inherited # Called automatically. # # base - the subclass # # Returns nothing def inherited(base) subclasses << base super(base) end # Run Site#process and catch errors # # site - the Jekyll::Site object # # Returns nothing def process_site(site) site.process rescue Jekyll::Errors::FatalException => e Jekyll.logger.error "ERROR:", "YOUR SITE COULD NOT BE BUILT:" Jekyll.logger.error "", "------------------------------------" Jekyll.logger.error "", e.message exit(1) end # Create a full Jekyll configuration with the options passed in as overrides # # options - the configuration overrides # # Returns a full Jekyll configuration def configuration_from_options(options) return options if options.is_a?(Jekyll::Configuration) Jekyll.configuration(options) end # Add common options to a command for building configuration # # cmd - the Jekyll::Command to add these options to # # Returns nothing # rubocop:disable Metrics/MethodLength def add_build_options(cmd) cmd.option "config", "--config CONFIG_FILE[,CONFIG_FILE2,...]", Array, "Custom configuration file" cmd.option "destination", "-d", "--destination DESTINATION", "The current folder will be generated into DESTINATION" cmd.option "source", "-s", "--source SOURCE", "Custom source directory" cmd.option "future", "--future", "Publishes posts with a future date" cmd.option "limit_posts", "--limit_posts MAX_POSTS", Integer, "Limits the number of posts to parse and publish" cmd.option "watch", "-w", "--[no-]watch", "Watch for changes and rebuild" cmd.option "baseurl", "-b", "--baseurl URL", "Serve the website from the given base URL" cmd.option "force_polling", "--force_polling", "Force watch to use polling" cmd.option "lsi", "--lsi", "Use LSI for improved related posts" cmd.option "show_drafts", "-D", "--drafts", "Render posts in the _drafts folder" cmd.option "unpublished", "--unpublished", "Render posts that were marked as unpublished" cmd.option "quiet", "-q", "--quiet", "Silence output." cmd.option "verbose", "-V", "--verbose", "Print verbose output." cmd.option "incremental", "-I", "--incremental", "Enable incremental rebuild." cmd.option "strict_front_matter", "--strict_front_matter", "Fail if errors are present in front matter" end # rubocop:enable Metrics/MethodLength end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/convertible.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/convertible.rb
# frozen_string_literal: true # Convertible provides methods for converting a pagelike item # from a certain type of markup into actual content # # Requires # self.site -> Jekyll::Site # self.content # self.content= # self.data= # self.ext= # self.output= # self.name # self.path # self.type -> :page, :post or :draft module Jekyll module Convertible # Returns the contents as a String. def to_s content || "" end # Whether the file is published or not, as indicated in YAML front-matter def published? !(data.key?("published") && data["published"] == false) end # Read the YAML frontmatter. # # base - The String path to the dir containing the file. # name - The String filename of the file. # opts - optional parameter to File.read, default at site configs # # Returns nothing. # rubocop:disable Metrics/AbcSize def read_yaml(base, name, opts = {}) filename = File.join(base, name) begin self.content = File.read(@path || site.in_source_dir(base, name), Utils.merged_file_read_opts(site, opts)) if content =~ Document::YAML_FRONT_MATTER_REGEXP self.content = $POSTMATCH self.data = SafeYAML.load(Regexp.last_match(1)) end rescue Psych::SyntaxError => e Jekyll.logger.warn "YAML Exception reading #{filename}: #{e.message}" raise e if self.site.config["strict_front_matter"] rescue StandardError => e Jekyll.logger.warn "Error reading file #{filename}: #{e.message}" raise e if self.site.config["strict_front_matter"] end self.data ||= {} validate_data! filename validate_permalink! filename self.data end # rubocop:enable Metrics/AbcSize def validate_data!(filename) unless self.data.is_a?(Hash) raise Errors::InvalidYAMLFrontMatterError, "Invalid YAML front matter in #{filename}" end end def validate_permalink!(filename) if self.data["permalink"] && self.data["permalink"].to_s.empty? raise Errors::InvalidPermalinkError, "Invalid permalink in #{filename}" end end # Transform the contents based on the content type. # # Returns the transformed contents. def transform _renderer.convert(content) end # Determine the extension depending on content_type. # # Returns the String extension for the output file. # e.g. ".html" for an HTML output file. def output_ext _renderer.output_ext end # Determine which converter to use based on this convertible's # extension. # # Returns the Converter instance. def converters _renderer.converters end # Render Liquid in the content # # content - the raw Liquid content to render # payload - the payload for Liquid # info - the info for Liquid # # Returns the converted content def render_liquid(content, payload, info, path) _renderer.render_liquid(content, payload, info, path) end # Convert this Convertible's data to a Hash suitable for use by Liquid. # # Returns the Hash representation of this Convertible. def to_liquid(attrs = nil) further_data = Hash[(attrs || self.class::ATTRIBUTES_FOR_LIQUID).map do |attribute| [attribute, send(attribute)] end] defaults = site.frontmatter_defaults.all(relative_path, type) Utils.deep_merge_hashes defaults, Utils.deep_merge_hashes(data, further_data) end # The type of a document, # i.e., its classname downcase'd and to_sym'd. # # Returns the type of self. def type if is_a?(Page) :pages end end # returns the owner symbol for hook triggering def hook_owner if is_a?(Page) :pages end end # Determine whether the document is an asset file. # Asset files include CoffeeScript files and Sass/SCSS files. # # Returns true if the extname belongs to the set of extensions # that asset files use. def asset_file? sass_file? || coffeescript_file? end # Determine whether the document is a Sass file. # # Returns true if extname == .sass or .scss, false otherwise. def sass_file? %w(.sass .scss).include?(ext) end # Determine whether the document is a CoffeeScript file. # # Returns true if extname == .coffee, false otherwise. def coffeescript_file? ext == ".coffee" end # Determine whether the file should be rendered with Liquid. # # Returns true if the file has Liquid Tags or Variables, false otherwise. def render_with_liquid? Jekyll::Utils.has_liquid_construct?(content) end # Determine whether the file should be placed into layouts. # # Returns false if the document is an asset file or if the front matter # specifies `layout: none` def place_in_layout? !(asset_file? || no_layout?) end # Checks if the layout specified in the document actually exists # # layout - the layout to check # # Returns true if the layout is invalid, false if otherwise def invalid_layout?(layout) !data["layout"].nil? && layout.nil? && !(self.is_a? Jekyll::Excerpt) end # Recursively render layouts # # layouts - a list of the layouts # payload - the payload for Liquid # info - the info for Liquid # # Returns nothing def render_all_layouts(layouts, payload, info) _renderer.layouts = layouts self.output = _renderer.place_in_layouts(output, payload, info) ensure @_renderer = nil # this will allow the modifications above to disappear end # Add any necessary layouts to this convertible document. # # payload - The site payload Drop or Hash. # layouts - A Hash of {"name" => "layout"}. # # Returns nothing. def do_layout(payload, layouts) self.output = _renderer.tap do |renderer| renderer.layouts = layouts renderer.payload = payload end.run Jekyll.logger.debug "Post-Render Hooks:", self.relative_path Jekyll::Hooks.trigger hook_owner, :post_render, self ensure @_renderer = nil # this will allow the modifications above to disappear end # Write the generated page file to the destination directory. # # dest - The String path to the destination dir. # # Returns nothing. def write(dest) path = destination(dest) FileUtils.mkdir_p(File.dirname(path)) Jekyll.logger.debug "Writing:", path File.write(path, output, :mode => "wb") Jekyll::Hooks.trigger hook_owner, :post_write, self end # Accessor for data properties by Liquid. # # property - The String name of the property to retrieve. # # Returns the String value or nil if the property isn't included. def [](property) if self.class::ATTRIBUTES_FOR_LIQUID.include?(property) send(property) else data[property] end end private def _renderer @_renderer ||= Jekyll::Renderer.new(site, self) end def no_layout? data["layout"] == "none" end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/collection.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/collection.rb
# frozen_string_literal: true module Jekyll class Collection attr_reader :site, :label, :metadata attr_writer :docs # Create a new Collection. # # site - the site to which this collection belongs. # label - the name of the collection # # Returns nothing. def initialize(site, label) @site = site @label = sanitize_label(label) @metadata = extract_metadata end # Fetch the Documents in this collection. # Defaults to an empty array if no documents have been read in. # # Returns an array of Jekyll::Document objects. def docs @docs ||= [] end # Override of normal respond_to? to match method_missing's logic for # looking in @data. def respond_to_missing?(method, include_private = false) docs.respond_to?(method.to_sym, include_private) || super end # Override of method_missing to check in @data for the key. def method_missing(method, *args, &blck) if docs.respond_to?(method.to_sym) Jekyll.logger.warn "Deprecation:", "#{label}.#{method} should be changed to #{label}.docs.#{method}." Jekyll.logger.warn "", "Called by #{caller(0..0)}." docs.public_send(method.to_sym, *args, &blck) else super end end # Fetch the static files in this collection. # Defaults to an empty array if no static files have been read in. # # Returns an array of Jekyll::StaticFile objects. def files @files ||= [] end # Read the allowed documents into the collection's array of docs. # # Returns the sorted array of docs. def read filtered_entries.each do |file_path| full_path = collection_dir(file_path) next if File.directory?(full_path) if Utils.has_yaml_header? full_path read_document(full_path) else read_static_file(file_path, full_path) end end docs.sort! end # All the entries in this collection. # # Returns an Array of file paths to the documents in this collection # relative to the collection's directory def entries return [] unless exists? @entries ||= Utils.safe_glob(collection_dir, ["**", "*"], File::FNM_DOTMATCH).map do |entry| entry["#{collection_dir}/"] = "" entry end end # Filtered version of the entries in this collection. # See `Jekyll::EntryFilter#filter` for more information. # # Returns a list of filtered entry paths. def filtered_entries return [] unless exists? @filtered_entries ||= Dir.chdir(directory) do entry_filter.filter(entries).reject do |f| path = collection_dir(f) File.directory?(path) || entry_filter.symlink?(f) end end end # The directory for this Collection, relative to the site source or the directory # containing the collection. # # Returns a String containing the directory name where the collection # is stored on the filesystem. def relative_directory @relative_directory ||= "_#{label}" end # The full path to the directory containing the collection. # # Returns a String containing th directory name where the collection # is stored on the filesystem. def directory @directory ||= site.in_source_dir( File.join(container, relative_directory) ) end # The full path to the directory containing the collection, with # optional subpaths. # # *files - (optional) any other path pieces relative to the # directory to append to the path # # Returns a String containing th directory name where the collection # is stored on the filesystem. def collection_dir(*files) return directory if files.empty? site.in_source_dir(container, relative_directory, *files) end # Checks whether the directory "exists" for this collection. # The directory must exist on the filesystem and must not be a symlink # if in safe mode. # # Returns false if the directory doesn't exist or if it's a symlink # and we're in safe mode. def exists? File.directory?(directory) && !entry_filter.symlink?(directory) end # The entry filter for this collection. # Creates an instance of Jekyll::EntryFilter. # # Returns the instance of Jekyll::EntryFilter for this collection. def entry_filter @entry_filter ||= Jekyll::EntryFilter.new(site, relative_directory) end # An inspect string. # # Returns the inspect string def inspect "#<Jekyll::Collection @label=#{label} docs=#{docs}>" end # Produce a sanitized label name # Label names may not contain anything but alphanumeric characters, # underscores, and hyphens. # # label - the possibly-unsafe label # # Returns a sanitized version of the label. def sanitize_label(label) label.gsub(%r![^a-z0-9_\-\.]!i, "") end # Produce a representation of this Collection for use in Liquid. # Exposes two attributes: # - label # - docs # # Returns a representation of this collection for use in Liquid. def to_liquid Drops::CollectionDrop.new self end # Whether the collection's documents ought to be written as individual # files in the output. # # Returns true if the 'write' metadata is true, false otherwise. def write? !!metadata.fetch("output", false) end # The URL template to render collection's documents at. # # Returns the URL template to render collection's documents at. def url_template @url_template ||= metadata.fetch("permalink") do Utils.add_permalink_suffix("/:collection/:path", site.permalink_style) end end # Extract options for this collection from the site configuration. # # Returns the metadata for this collection def extract_metadata if site.config["collections"].is_a?(Hash) site.config["collections"][label] || {} else {} end end private def container @container ||= site.config["collections_dir"] end private def read_document(full_path) doc = Document.new(full_path, :site => site, :collection => self) doc.read if site.unpublished || doc.published? docs << doc end end private def read_static_file(file_path, full_path) relative_dir = Jekyll.sanitized_path( relative_directory, File.dirname(file_path) ).chomp("/.") files << StaticFile.new( site, site.source, relative_dir, File.basename(full_path), self ) end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/external.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/external.rb
# frozen_string_literal: true module Jekyll module External class << self # # Gems that, if installed, should be loaded. # Usually contain subcommands. # def blessed_gems %w( jekyll-docs jekyll-import ) end # # Require a gem or file if it's present, otherwise silently fail. # # names - a string gem name or array of gem names # def require_if_present(names) Array(names).each do |name| begin require name rescue LoadError Jekyll.logger.debug "Couldn't load #{name}. Skipping." yield(name, version_constraint(name)) if block_given? false end end end # # The version constraint required to activate a given gem. # Usually the gem version requirement is "> 0," because any version # will do. In the case of jekyll-docs, however, we require the exact # same version as Jekyll. # # Returns a String version constraint in a parseable form for # RubyGems. def version_constraint(gem_name) return "= #{Jekyll::VERSION}" if gem_name.to_s.eql?("jekyll-docs") "> 0" end # # Require a gem or gems. If it's not present, show a very nice error # message that explains everything and is much more helpful than the # normal LoadError. # # names - a string gem name or array of gem names # def require_with_graceful_fail(names) Array(names).each do |name| begin Jekyll.logger.debug "Requiring:", name.to_s require name rescue LoadError => e Jekyll.logger.error "Dependency Error:", <<-MSG Yikes! It looks like you don't have #{name} or one of its dependencies installed. In order to use Jekyll as currently configured, you'll need to install this gem. The full error message from Ruby is: '#{e.message}' If you run into trouble, you can find helpful resources at https://jekyllrb.com/help/! MSG raise Jekyll::Errors::MissingDependencyException, name end end end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/liquid_renderer.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/liquid_renderer.rb
# frozen_string_literal: true require_relative "liquid_renderer/file" require_relative "liquid_renderer/table" module Jekyll class LiquidRenderer extend Forwardable private def_delegator :@site, :in_source_dir, :source_dir private def_delegator :@site, :in_theme_dir, :theme_dir def initialize(site) @site = site Liquid::Template.error_mode = @site.config["liquid"]["error_mode"].to_sym reset end def reset @stats = {} end def file(filename) filename.match(filename_regex) filename = if Regexp.last_match(1) == theme_dir("") ::File.join(::File.basename(Regexp.last_match(1)), Regexp.last_match(2)) else Regexp.last_match(2) end LiquidRenderer::File.new(self, filename).tap do @stats[filename] ||= new_profile_hash @stats[filename][:count] += 1 end end def increment_bytes(filename, bytes) @stats[filename][:bytes] += bytes end def increment_time(filename, time) @stats[filename][:time] += time end def stats_table(num_of_rows = 50) LiquidRenderer::Table.new(@stats).to_s(num_of_rows) end def self.format_error(error, path) "#{error.message} in #{path}" end private def filename_regex @filename_regex ||= %r!\A(#{source_dir}/|#{theme_dir}/|\W*)(.*)!i end def new_profile_hash Hash.new { |hash, key| hash[key] = 0 } end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/plugin_manager.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/plugin_manager.rb
# frozen_string_literal: true module Jekyll class PluginManager attr_reader :site # Create an instance of this class. # # site - the instance of Jekyll::Site we're concerned with # # Returns nothing def initialize(site) @site = site end # Require all the plugins which are allowed. # # Returns nothing def conscientious_require require_theme_deps if site.theme require_plugin_files require_gems deprecation_checks end # Require each of the gem plugins specified. # # Returns nothing. def require_gems Jekyll::External.require_with_graceful_fail( site.gems.select { |plugin| plugin_allowed?(plugin) } ) end # Require each of the runtime_dependencies specified by the theme's gemspec. # # Returns false only if no dependencies have been specified, otherwise nothing. def require_theme_deps return false unless site.theme.runtime_dependencies site.theme.runtime_dependencies.each do |dep| next if dep.name == "jekyll" External.require_with_graceful_fail(dep.name) if plugin_allowed?(dep.name) end end def self.require_from_bundler if !ENV["JEKYLL_NO_BUNDLER_REQUIRE"] && File.file?("Gemfile") require "bundler" Bundler.setup required_gems = Bundler.require(:jekyll_plugins) message = "Required #{required_gems.map(&:name).join(", ")}" Jekyll.logger.debug("PluginManager:", message) ENV["JEKYLL_NO_BUNDLER_REQUIRE"] = "true" true else false end end # Check whether a gem plugin is allowed to be used during this build. # # plugin_name - the name of the plugin # # Returns true if the plugin name is in the whitelist or if the site is not # in safe mode. def plugin_allowed?(plugin_name) !site.safe || whitelist.include?(plugin_name) end # Build an array of allowed plugin gem names. # # Returns an array of strings, each string being the name of a gem name # that is allowed to be used. def whitelist @whitelist ||= Array[site.config["whitelist"]].flatten end # Require all .rb files if safe mode is off # # Returns nothing. def require_plugin_files unless site.safe plugins_path.each do |plugin_search_path| plugin_files = Utils.safe_glob(plugin_search_path, File.join("**", "*.rb")) Jekyll::External.require_with_graceful_fail(plugin_files) end end end # Public: Setup the plugin search path # # Returns an Array of plugin search paths def plugins_path if site.config["plugins_dir"].eql? Jekyll::Configuration::DEFAULTS["plugins_dir"] [site.in_source_dir(site.config["plugins_dir"])] else Array(site.config["plugins_dir"]).map { |d| File.expand_path(d) } end end def deprecation_checks pagination_included = (site.config["plugins"] || []).include?("jekyll-paginate") || defined?(Jekyll::Paginate) if site.config["paginate"] && !pagination_included Jekyll::Deprecator.deprecation_message "You appear to have pagination " \ "turned on, but you haven't included the `jekyll-paginate` gem. " \ "Ensure you have `plugins: [jekyll-paginate]` in your configuration file." end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/version.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/version.rb
# frozen_string_literal: true module Jekyll VERSION = "3.8.4".freeze end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false
grab/engineering-blog
https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/static_file.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/static_file.rb
# frozen_string_literal: true module Jekyll class StaticFile extend Forwardable attr_reader :relative_path, :extname, :name, :data def_delegator :to_liquid, :to_json, :to_json class << self # The cache of last modification times [path] -> mtime. def mtimes @mtimes ||= {} end def reset_cache @mtimes = nil end end # Initialize a new StaticFile. # # site - The Site. # base - The String path to the <source>. # dir - The String path between <source> and the file. # name - The String filename of the file. # rubocop: disable ParameterLists def initialize(site, base, dir, name, collection = nil) @site = site @base = base @dir = dir @name = name @collection = collection @relative_path = File.join(*[@dir, @name].compact) @extname = File.extname(@name) @data = @site.frontmatter_defaults.all(relative_path, type) end # rubocop: enable ParameterLists # Returns source file path. def path # Static file is from a collection inside custom collections directory if !@collection.nil? && !@site.config["collections_dir"].empty? File.join(*[@base, @site.config["collections_dir"], @dir, @name].compact) else File.join(*[@base, @dir, @name].compact) end end # Obtain destination path. # # dest - The String path to the destination dir. # # Returns destination file path. def destination(dest) @site.in_dest_dir(*[dest, destination_rel_dir, @name].compact) end def destination_rel_dir if @collection File.dirname(url) else @dir end end def modified_time @modified_time ||= File.stat(path).mtime end # Returns last modification time for this file. def mtime modified_time.to_i end # Is source path modified? # # Returns true if modified since last write. def modified? self.class.mtimes[path] != mtime end # Whether to write the file to the filesystem # # Returns true unless the defaults for the destination path from # _config.yml contain `published: false`. def write? defaults.fetch("published", true) end # Write the static file to the destination directory (if modified). # # dest - The String path to the destination dir. # # Returns false if the file was not modified since last time (no-op). def write(dest) dest_path = destination(dest) return false if File.exist?(dest_path) && !modified? self.class.mtimes[path] = mtime FileUtils.mkdir_p(File.dirname(dest_path)) FileUtils.rm(dest_path) if File.exist?(dest_path) copy_file(dest_path) true end def to_liquid @to_liquid ||= Drops::StaticFileDrop.new(self) end def basename File.basename(name, extname) end def placeholders { :collection => @collection.label, :path => relative_path[ @collection.relative_directory.size..relative_path.size], :output_ext => "", :name => "", :title => "", } end # Applies a similar URL-building technique as Jekyll::Document that takes # the collection's URL template into account. The default URL template can # be overriden in the collection's configuration in _config.yml. def url @url ||= if @collection.nil? relative_path else ::Jekyll::URL.new({ :template => @collection.url_template, :placeholders => placeholders, }) end.to_s.chomp("/") end # Returns the type of the collection if present, nil otherwise. def type @type ||= @collection.nil? ? nil : @collection.label.to_sym end # Returns the front matter defaults defined for the file's URL and/or type # as defined in _config.yml. def defaults @defaults ||= @site.frontmatter_defaults.all url, type end private def copy_file(dest_path) if @site.safe || Jekyll.env == "production" FileUtils.cp(path, dest_path) else FileUtils.copy_entry(path, dest_path) end unless File.symlink?(dest_path) File.utime(self.class.mtimes[path], self.class.mtimes[path], dest_path) end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false