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/jekyll-3.8.4/lib/jekyll/errors.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/errors.rb
# frozen_string_literal: true module Jekyll module Errors FatalException = Class.new(::RuntimeError) InvalidThemeName = Class.new(FatalException) DropMutationException = Class.new(FatalException) InvalidPermalinkError = Class.new(FatalException) InvalidYAMLFrontMatterError = Class.new(FatalException) MissingDependencyException = Class.new(FatalException) InvalidDateError = Class.new(FatalException) InvalidPostNameError = Class.new(FatalException) PostURLError = Class.new(FatalException) InvalidURLError = Class.new(FatalException) InvalidConfigurationError = Class.new(FatalException) 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/converter.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/converter.rb
# frozen_string_literal: true module Jekyll class Converter < Plugin # Public: Get or set the highlighter prefix. When an argument is specified, # the prefix will be set. If no argument is specified, the current prefix # will be returned. # # highlighter_prefix - The String prefix (default: nil). # # Returns the String prefix. def self.highlighter_prefix(highlighter_prefix = nil) unless defined?(@highlighter_prefix) && highlighter_prefix.nil? @highlighter_prefix = highlighter_prefix end @highlighter_prefix end # Public: Get or set the highlighter suffix. When an argument is specified, # the suffix will be set. If no argument is specified, the current suffix # will be returned. # # highlighter_suffix - The String suffix (default: nil). # # Returns the String suffix. def self.highlighter_suffix(highlighter_suffix = nil) unless defined?(@highlighter_suffix) && highlighter_suffix.nil? @highlighter_suffix = highlighter_suffix end @highlighter_suffix end # Initialize the converter. # # Returns an initialized Converter. def initialize(config = {}) @config = config end # Get the highlighter prefix. # # Returns the String prefix. def highlighter_prefix self.class.highlighter_prefix end # Get the highlighter suffix. # # Returns the String suffix. def highlighter_suffix self.class.highlighter_suffix 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/hooks.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/hooks.rb
# frozen_string_literal: true module Jekyll module Hooks DEFAULT_PRIORITY = 20 # compatibility layer for octopress-hooks users PRIORITY_MAP = { :low => 10, :normal => 20, :high => 30, }.freeze # initial empty hooks @registry = { :site => { :after_init => [], :after_reset => [], :post_read => [], :pre_render => [], :post_render => [], :post_write => [], }, :pages => { :post_init => [], :pre_render => [], :post_render => [], :post_write => [], }, :posts => { :post_init => [], :pre_render => [], :post_render => [], :post_write => [], }, :documents => { :post_init => [], :pre_render => [], :post_render => [], :post_write => [], }, :clean => { :on_obsolete => [], }, } # map of all hooks and their priorities @hook_priority = {} NotAvailable = Class.new(RuntimeError) Uncallable = Class.new(RuntimeError) # register hook(s) to be called later, public API def self.register(owners, event, priority: DEFAULT_PRIORITY, &block) Array(owners).each do |owner| register_one(owner, event, priority_value(priority), &block) end end # Ensure the priority is a Fixnum def self.priority_value(priority) return priority if priority.is_a?(Integer) PRIORITY_MAP[priority] || DEFAULT_PRIORITY end # register a single hook to be called later, internal API def self.register_one(owner, event, priority, &block) @registry[owner] ||= { :post_init => [], :pre_render => [], :post_render => [], :post_write => [], } unless @registry[owner][event] raise NotAvailable, "Invalid hook. #{owner} supports only the " \ "following hooks #{@registry[owner].keys.inspect}" end unless block.respond_to? :call raise Uncallable, "Hooks must respond to :call" end insert_hook owner, event, priority, &block end def self.insert_hook(owner, event, priority, &block) @hook_priority[block] = [-priority, @hook_priority.size] @registry[owner][event] << block end # interface for Jekyll core components to trigger hooks def self.trigger(owner, event, *args) # proceed only if there are hooks to call return unless @registry[owner] return unless @registry[owner][event] # hooks to call for this owner and event hooks = @registry[owner][event] # sort and call hooks according to priority and load order hooks.sort_by { |h| @hook_priority[h] }.each do |hook| hook.call(*args) 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/theme.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/theme.rb
# frozen_string_literal: true module Jekyll class Theme extend Forwardable attr_reader :name def_delegator :gemspec, :version, :version def initialize(name) @name = name.downcase.strip Jekyll.logger.debug "Theme:", name Jekyll.logger.debug "Theme source:", root configure_sass end def root # Must use File.realpath to resolve symlinks created by rbenv # Otherwise, Jekyll.sanitized path with prepend the unresolved root @root ||= File.realpath(gemspec.full_gem_path) rescue Errno::ENOENT, Errno::EACCES, Errno::ELOOP raise "Path #{gemspec.full_gem_path} does not exist, is not accessible "\ "or includes a symbolic link loop" end def includes_path @includes_path ||= path_for "_includes".freeze end def layouts_path @layouts_path ||= path_for "_layouts".freeze end def sass_path @sass_path ||= path_for "_sass".freeze end def assets_path @assets_path ||= path_for "assets".freeze end def configure_sass return unless sass_path External.require_with_graceful_fail("sass") unless defined?(Sass) Sass.load_paths << sass_path end def runtime_dependencies gemspec.runtime_dependencies end private def path_for(folder) path = realpath_for(folder) path if path && File.directory?(path) end def realpath_for(folder) File.realpath(Jekyll.sanitized_path(root, folder.to_s)) rescue Errno::ENOENT, Errno::EACCES, Errno::ELOOP Jekyll.logger.warn "Invalid theme folder:", folder nil end def gemspec @gemspec ||= Gem::Specification.find_by_name(name) rescue Gem::LoadError raise Jekyll::Errors::MissingDependencyException, "The #{name} theme could not be found." 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/page.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/page.rb
# frozen_string_literal: true module Jekyll class Page include Convertible attr_writer :dir attr_accessor :site, :pager attr_accessor :name, :ext, :basename attr_accessor :data, :content, :output alias_method :extname, :ext FORWARD_SLASH = "/".freeze # Attributes for Liquid templates ATTRIBUTES_FOR_LIQUID = %w( content dir name path url ).freeze # A set of extensions that are considered HTML or HTML-like so we # should not alter them, this includes .xhtml through XHTM5. HTML_EXTENSIONS = %w( .html .xhtml .htm ).freeze # Initialize a new Page. # # site - The Site object. # base - The String path to the source. # dir - The String path between the source and the file. # name - The String filename of the file. def initialize(site, base, dir, name) @site = site @base = base @dir = dir @name = name @path = if site.in_theme_dir(base) == base # we're in a theme site.in_theme_dir(base, dir, name) else site.in_source_dir(base, dir, name) end process(name) read_yaml(File.join(base, dir), name) data.default_proc = proc do |_, key| site.frontmatter_defaults.find(File.join(dir, name), type, key) end Jekyll::Hooks.trigger :pages, :post_init, self end # The generated directory into which the page will be placed # upon generation. This is derived from the permalink or, if # permalink is absent, will be '/' # # Returns the String destination directory. def dir if url.end_with?(FORWARD_SLASH) url else url_dir = File.dirname(url) url_dir.end_with?(FORWARD_SLASH) ? url_dir : "#{url_dir}/" end end # The full path and filename of the post. Defined in the YAML of the post # body. # # Returns the String permalink or nil if none has been set. def permalink data.nil? ? nil : data["permalink"] end # The template of the permalink. # # Returns the template String. def template if !html? "/:path/:basename:output_ext" elsif index? "/:path/" else Utils.add_permalink_suffix("/:path/:basename", site.permalink_style) 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 => permalink, }).to_s end # Returns a hash of URL placeholder names (as symbols) mapping to the # desired placeholder replacements. For details see "url.rb" def url_placeholders { :path => @dir, :basename => basename, :output_ext => output_ext, } end # Extract information from the page filename. # # name - The String filename of the page file. # # Returns nothing. def process(name) self.ext = File.extname(name) self.basename = name[0..-ext.length - 1] end # Add any necessary layouts to this post # # layouts - The Hash of {"name" => "layout"}. # site_payload - The site payload Hash. # # Returns String rendered page. def render(layouts, site_payload) site_payload["page"] = to_liquid site_payload["paginator"] = pager.to_liquid do_layout(site_payload, layouts) end # The path to the source file # # Returns the path to the source file def path data.fetch("path") { relative_path } end # The path to the page source file, relative to the site source def relative_path File.join(*[@dir, @name].map(&:to_s).reject(&:empty?)).sub(%r!\A\/!, "") end # Obtain destination path. # # dest - The String path to the destination dir. # # Returns the destination file path String. def destination(dest) path = site.in_dest_dir(dest, URL.unescape_path(url)) path = File.join(path, "index") if url.end_with?("/") path << output_ext unless path.end_with? output_ext path end # Returns the object as a debug String. def inspect "#<Jekyll::Page @name=#{name.inspect}>" end # Returns the Boolean of whether this Page is HTML or not. def html? HTML_EXTENSIONS.include?(output_ext) end # Returns the Boolean of whether this Page is an index file or not. def index? basename == "index" end def trigger_hooks(hook_name, *args) Jekyll::Hooks.trigger :pages, hook_name, self, *args end def write? true 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/publisher.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/publisher.rb
# frozen_string_literal: true module Jekyll class Publisher def initialize(site) @site = site end def publish?(thing) can_be_published?(thing) && !hidden_in_the_future?(thing) end def hidden_in_the_future?(thing) thing.respond_to?(:date) && !@site.future && thing.date.to_i > @site.time.to_i end private def can_be_published?(thing) thing.data.fetch("published", true) || @site.unpublished 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/utils.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/utils.rb
# frozen_string_literal: true module Jekyll module Utils extend self autoload :Ansi, "jekyll/utils/ansi" autoload :Exec, "jekyll/utils/exec" autoload :Internet, "jekyll/utils/internet" autoload :Platforms, "jekyll/utils/platforms" autoload :Rouge, "jekyll/utils/rouge" autoload :ThreadEvent, "jekyll/utils/thread_event" autoload :WinTZ, "jekyll/utils/win_tz" # Constants for use in #slugify SLUGIFY_MODES = %w(raw default pretty ascii latin).freeze SLUGIFY_RAW_REGEXP = Regexp.new('\\s+').freeze SLUGIFY_DEFAULT_REGEXP = Regexp.new("[^[:alnum:]]+").freeze SLUGIFY_PRETTY_REGEXP = Regexp.new("[^[:alnum:]._~!$&'()+,;=@]+").freeze SLUGIFY_ASCII_REGEXP = Regexp.new("[^[A-Za-z0-9]]+").freeze # Takes an indented string and removes the preceding spaces on each line def strip_heredoc(str) str.gsub(%r!^[ \t]{#{(str.scan(%r!^[ \t]*(?=\S)!).min || "").size}}!, "") end # Takes a slug and turns it into a simple title. def titleize_slug(slug) slug.split("-").map!(&:capitalize).join(" ") end # Non-destructive version of deep_merge_hashes! See that method. # # Returns the merged hashes. def deep_merge_hashes(master_hash, other_hash) deep_merge_hashes!(master_hash.dup, other_hash) end # Merges a master hash with another hash, recursively. # # master_hash - the "parent" hash whose values will be overridden # other_hash - the other hash whose values will be persisted after the merge # # This code was lovingly stolen from some random gem: # http://gemjack.com/gems/tartan-0.1.1/classes/Hash.html # # Thanks to whoever made it. def deep_merge_hashes!(target, overwrite) merge_values(target, overwrite) merge_default_proc(target, overwrite) duplicate_frozen_values(target) target end def mergable?(value) value.is_a?(Hash) || value.is_a?(Drops::Drop) end def duplicable?(obj) case obj when nil, false, true, Symbol, Numeric false else true end end # Read array from the supplied hash favouring the singular key # and then the plural key, and handling any nil entries. # # hash - the hash to read from # singular_key - the singular key # plural_key - the plural key # # Returns an array def pluralized_array_from_hash(hash, singular_key, plural_key) [].tap do |array| value = value_from_singular_key(hash, singular_key) value ||= value_from_plural_key(hash, plural_key) array << value end.flatten.compact end def value_from_singular_key(hash, key) hash[key] if hash.key?(key) || (hash.default_proc && hash[key]) end def value_from_plural_key(hash, key) if hash.key?(key) || (hash.default_proc && hash[key]) val = hash[key] case val when String val.split when Array val.compact end end end def transform_keys(hash) result = {} hash.each_key do |key| result[yield(key)] = hash[key] end result end # Apply #to_sym to all keys in the hash # # hash - the hash to which to apply this transformation # # Returns a new hash with symbolized keys def symbolize_hash_keys(hash) transform_keys(hash) { |key| key.to_sym rescue key } end # Apply #to_s to all keys in the Hash # # hash - the hash to which to apply this transformation # # Returns a new hash with stringified keys def stringify_hash_keys(hash) transform_keys(hash) { |key| key.to_s rescue key } end # Parse a date/time and throw an error if invalid # # input - the date/time to parse # msg - (optional) the error message to show the user # # Returns the parsed date if successful, throws a FatalException # if not def parse_date(input, msg = "Input could not be parsed.") Time.parse(input).localtime rescue ArgumentError raise Errors::InvalidDateError, "Invalid date '#{input}': #{msg}" end # Determines whether a given file has # # Returns true if the YAML front matter is present. # rubocop: disable PredicateName def has_yaml_header?(file) !!(File.open(file, "rb", &:readline) =~ %r!\A---\s*\r?\n!) rescue EOFError false end # Determine whether the given content string contains Liquid Tags or Vaiables # # Returns true is the string contains sequences of `{%` or `{{` def has_liquid_construct?(content) return false if content.nil? || content.empty? content.include?("{%") || content.include?("{{") end # rubocop: enable PredicateName # Slugify a filename or title. # # string - the filename or title to slugify # mode - how string is slugified # cased - whether to replace all uppercase letters with their # lowercase counterparts # # When mode is "none", return the given string. # # When mode is "raw", return the given string, # with every sequence of spaces characters replaced with a hyphen. # # When mode is "default" or nil, non-alphabetic characters are # replaced with a hyphen too. # # When mode is "pretty", some non-alphabetic characters (._~!$&'()+,;=@) # are not replaced with hyphen. # # When mode is "ascii", some everything else except ASCII characters # a-z (lowercase), A-Z (uppercase) and 0-9 (numbers) are not replaced with hyphen. # # When mode is "latin", the input string is first preprocessed so that # any letters with accents are replaced with the plain letter. Afterwards, # it follows the "default" mode of operation. # # If cased is true, all uppercase letters in the result string are # replaced with their lowercase counterparts. # # Examples: # slugify("The _config.yml file") # # => "the-config-yml-file" # # slugify("The _config.yml file", "pretty") # # => "the-_config.yml-file" # # slugify("The _config.yml file", "pretty", true) # # => "The-_config.yml file" # # slugify("The _config.yml file", "ascii") # # => "the-config-yml-file" # # slugify("The _config.yml file", "latin") # # => "the-config-yml-file" # # Returns the slugified string. def slugify(string, mode: nil, cased: false) mode ||= "default" return nil if string.nil? unless SLUGIFY_MODES.include?(mode) return cased ? string : string.downcase end # Drop accent marks from latin characters. Everything else turns to ? if mode == "latin" I18n.config.available_locales = :en if I18n.config.available_locales.empty? string = I18n.transliterate(string) end slug = replace_character_sequence_with_hyphen(string, :mode => mode) # Remove leading/trailing hyphen slug.gsub!(%r!^\-|\-$!i, "") slug.downcase! unless cased slug end # Add an appropriate suffix to template so that it matches the specified # permalink style. # # template - permalink template without trailing slash or file extension # permalink_style - permalink style, either built-in or custom # # The returned permalink template will use the same ending style as # specified in permalink_style. For example, if permalink_style contains a # trailing slash (or is :pretty, which indirectly has a trailing slash), # then so will the returned template. If permalink_style has a trailing # ":output_ext" (or is :none, :date, or :ordinal) then so will the returned # template. Otherwise, template will be returned without modification. # # Examples: # add_permalink_suffix("/:basename", :pretty) # # => "/:basename/" # # add_permalink_suffix("/:basename", :date) # # => "/:basename:output_ext" # # add_permalink_suffix("/:basename", "/:year/:month/:title/") # # => "/:basename/" # # add_permalink_suffix("/:basename", "/:year/:month/:title") # # => "/:basename" # # Returns the updated permalink template def add_permalink_suffix(template, permalink_style) template = template.dup case permalink_style when :pretty template << "/" when :date, :ordinal, :none template << ":output_ext" else template << "/" if permalink_style.to_s.end_with?("/") template << ":output_ext" if permalink_style.to_s.end_with?(":output_ext") end template end # Work the same way as Dir.glob but seperating the input into two parts # ('dir' + '/' + 'pattern') to make sure the first part('dir') does not act # as a pattern. # # For example, Dir.glob("path[/*") always returns an empty array, # because the method fails to find the closing pattern to '[' which is ']' # # Examples: # safe_glob("path[", "*") # # => ["path[/file1", "path[/file2"] # # safe_glob("path", "*", File::FNM_DOTMATCH) # # => ["path/.", "path/..", "path/file1"] # # safe_glob("path", ["**", "*"]) # # => ["path[/file1", "path[/folder/file2"] # # dir - the dir where glob will be executed under # (the dir will be included to each result) # patterns - the patterns (or the pattern) which will be applied under the dir # flags - the flags which will be applied to the pattern # # Returns matched pathes def safe_glob(dir, patterns, flags = 0) return [] unless Dir.exist?(dir) pattern = File.join(Array(patterns)) return [dir] if pattern.empty? Dir.chdir(dir) do Dir.glob(pattern, flags).map { |f| File.join(dir, f) } end end # Returns merged option hash for File.read of self.site (if exists) # and a given param def merged_file_read_opts(site, opts) merged = (site ? site.file_read_opts : {}).merge(opts) if merged[:encoding] && !merged[:encoding].start_with?("bom|") merged[:encoding] = "bom|#{merged[:encoding]}" end if merged["encoding"] && !merged["encoding"].start_with?("bom|") merged["encoding"] = "bom|#{merged["encoding"]}" end merged end private def merge_values(target, overwrite) target.merge!(overwrite) do |_key, old_val, new_val| if new_val.nil? old_val elsif mergable?(old_val) && mergable?(new_val) deep_merge_hashes(old_val, new_val) else new_val end end end private def merge_default_proc(target, overwrite) if target.is_a?(Hash) && overwrite.is_a?(Hash) && target.default_proc.nil? target.default_proc = overwrite.default_proc end end private def duplicate_frozen_values(target) target.each do |key, val| target[key] = val.dup if val.frozen? && duplicable?(val) end end # Replace each character sequence with a hyphen. # # See Utils#slugify for a description of the character sequence specified # by each mode. private def replace_character_sequence_with_hyphen(string, mode: "default") replaceable_char = case mode when "raw" SLUGIFY_RAW_REGEXP when "pretty" # "._~!$&'()+,;=@" is human readable (not URI-escaped) in URL # and is allowed in both extN and NTFS. SLUGIFY_PRETTY_REGEXP when "ascii" # For web servers not being able to handle Unicode, the safe # method is to ditch anything else but latin letters and numeric # digits. SLUGIFY_ASCII_REGEXP else SLUGIFY_DEFAULT_REGEXP end # Strip according to the mode string.gsub(replaceable_char, "-") 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/reader.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/reader.rb
# frozen_string_literal: true module Jekyll class Reader attr_reader :site def initialize(site) @site = site end # Read Site data from disk and load it into internal data structures. # # Returns nothing. def read @site.layouts = LayoutReader.new(site).read read_directories sort_files! @site.data = DataReader.new(site).read(site.config["data_dir"]) CollectionReader.new(site).read ThemeAssetsReader.new(site).read end # Sorts posts, pages, and static files. def sort_files! site.collections.each_value { |c| c.docs.sort! } site.pages.sort_by!(&:name) site.static_files.sort_by!(&:relative_path) end # Recursively traverse directories to find pages and static files # that will become part of the site according to the rules in # filter_entries. # # dir - The String relative path of the directory to read. Default: ''. # # Returns nothing. def read_directories(dir = "") base = site.in_source_dir(dir) return unless File.directory?(base) dot = Dir.chdir(base) { filter_entries(Dir.entries("."), base) } dot_dirs = dot.select { |file| File.directory?(@site.in_source_dir(base, file)) } dot_files = (dot - dot_dirs) dot_pages = dot_files.select do |file| Utils.has_yaml_header?(@site.in_source_dir(base, file)) end dot_static_files = dot_files - dot_pages retrieve_posts(dir) retrieve_dirs(base, dir, dot_dirs) retrieve_pages(dir, dot_pages) retrieve_static_files(dir, dot_static_files) end # Retrieves all the posts(posts/drafts) from the given directory # and add them to the site and sort them. # # dir - The String representing the directory to retrieve the posts from. # # Returns nothing. def retrieve_posts(dir) return if outside_configured_directory?(dir) site.posts.docs.concat(post_reader.read_posts(dir)) site.posts.docs.concat(post_reader.read_drafts(dir)) if site.show_drafts end # Recursively traverse directories with the read_directories function. # # base - The String representing the site's base directory. # dir - The String representing the directory to traverse down. # dot_dirs - The Array of subdirectories in the dir. # # Returns nothing. def retrieve_dirs(_base, dir, dot_dirs) dot_dirs.each do |file| dir_path = site.in_source_dir(dir, file) rel_path = File.join(dir, file) unless @site.dest.chomp("/") == dir_path @site.reader.read_directories(rel_path) end end end # Retrieve all the pages from the current directory, # add them to the site and sort them. # # dir - The String representing the directory retrieve the pages from. # dot_pages - The Array of pages in the dir. # # Returns nothing. def retrieve_pages(dir, dot_pages) site.pages.concat(PageReader.new(site, dir).read(dot_pages)) end # Retrieve all the static files from the current directory, # add them to the site and sort them. # # dir - The directory retrieve the static files from. # dot_static_files - The static files in the dir. # # Returns nothing. def retrieve_static_files(dir, dot_static_files) site.static_files.concat(StaticFileReader.new(site, dir).read(dot_static_files)) end # Filter out any files/directories that are hidden or backup files (start # with "." or "#" or end with "~"), or contain site content (start with "_"), # or are excluded in the site configuration, unless they are web server # files such as '.htaccess'. # # entries - The Array of String file/directory entries to filter. # base_directory - The string representing the optional base directory. # # Returns the Array of filtered entries. def filter_entries(entries, base_directory = nil) EntryFilter.new(site, base_directory).filter(entries) end # Read the entries from a particular directory for processing # # dir - The String representing the relative path of the directory to read. # subfolder - The String representing the directory to read. # # Returns the list of entries to process def get_entries(dir, subfolder) base = site.in_source_dir(dir, subfolder) return [] unless File.exist?(base) entries = Dir.chdir(base) { filter_entries(Dir["**/*"], base) } entries.delete_if { |e| File.directory?(site.in_source_dir(base, e)) } end private # Internal # # Determine if the directory is supposed to contain posts and drafts. # If the user has defined a custom collections_dir, then attempt to read # posts and drafts only from within that directory. # # Returns true if a custom collections_dir has been set but current directory lies # outside that directory. def outside_configured_directory?(dir) collections_dir = site.config["collections_dir"] !collections_dir.empty? && !dir.start_with?("/#{collections_dir}") end # Create a single PostReader instance to retrieve drafts and posts from all valid # directories in current site. def post_reader @post_reader ||= PostReader.new(site) 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.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/plugin.rb
# frozen_string_literal: true module Jekyll class Plugin PRIORITIES = { :low => -10, :highest => 100, :lowest => -100, :normal => 0, :high => 10, }.freeze # def self.inherited(const) return catch_inheritance(const) do |const_| catch_inheritance(const_) end end # def self.catch_inheritance(const) const.define_singleton_method :inherited do |const_| (@children ||= Set.new).add const_ if block_given? yield const_ end end end # def self.descendants @children ||= Set.new out = @children.map(&:descendants) out << self unless superclass == Plugin Set.new(out).flatten end # Get or set the priority of this plugin. When called without an # argument it returns the priority. When an argument is given, it will # set the priority. # # priority - The Symbol priority (default: nil). Valid options are: # :lowest, :low, :normal, :high, :highest # # Returns the Symbol priority. def self.priority(priority = nil) @priority ||= nil if priority && PRIORITIES.key?(priority) @priority = priority end @priority || :normal end # Get or set the safety of this plugin. When called without an argument # it returns the safety. When an argument is given, it will set the # safety. # # safe - The Boolean safety (default: nil). # # Returns the safety Boolean. def self.safe(safe = nil) unless defined?(@safe) && safe.nil? @safe = safe end @safe || false end # Spaceship is priority [higher -> lower] # # other - The class to be compared. # # Returns -1, 0, 1. def self.<=>(other) PRIORITIES[other.priority] <=> PRIORITIES[self.priority] end # Spaceship is priority [higher -> lower] # # other - The class to be compared. # # Returns -1, 0, 1. def <=>(other) self.class <=> other.class end # Initialize a new plugin. This should be overridden by the subclass. # # config - The Hash of configuration options. # # Returns a new instance. def initialize(config = {}) # no-op for default 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/cleaner.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/cleaner.rb
# frozen_string_literal: true module Jekyll # Handles the cleanup of a site's destination before it is built. class Cleaner HIDDEN_FILE_REGEX = %r!\/\.{1,2}$! attr_reader :site def initialize(site) @site = site end # Cleans up the site's destination directory def cleanup! FileUtils.rm_rf(obsolete_files) FileUtils.rm_rf(metadata_file) unless @site.incremental? end private # Private: The list of files and directories to be deleted during cleanup process # # Returns an Array of the file and directory paths def obsolete_files out = (existing_files - new_files - new_dirs + replaced_files).to_a Jekyll::Hooks.trigger :clean, :on_obsolete, out out end # Private: The metadata file storing dependency tree and build history # # Returns an Array with the metdata file as the only item def metadata_file [site.regenerator.metadata_file] end # Private: The list of existing files, apart from those included in # keep_files and hidden files. # # Returns a Set with the file paths def existing_files files = Set.new regex = keep_file_regex dirs = keep_dirs Utils.safe_glob(site.in_dest_dir, ["**", "*"], File::FNM_DOTMATCH).each do |file| next if file =~ HIDDEN_FILE_REGEX || file =~ regex || dirs.include?(file) files << file end files end # Private: The list of files to be created when site is built. # # Returns a Set with the file paths def new_files @new_files ||= Set.new.tap do |files| site.each_site_file { |item| files << item.destination(site.dest) } end end # Private: The list of directories to be created when site is built. # These are the parent directories of the files in #new_files. # # Returns a Set with the directory paths def new_dirs @new_dirs ||= new_files.map { |file| parent_dirs(file) }.flatten.to_set end # Private: The list of parent directories of a given file # # Returns an Array with the directory paths def parent_dirs(file) parent_dir = File.dirname(file) if parent_dir == site.dest [] else [parent_dir] + parent_dirs(parent_dir) end end # Private: The list of existing files that will be replaced by a directory # during build # # Returns a Set with the file paths def replaced_files new_dirs.select { |dir| File.file?(dir) }.to_set end # Private: The list of directories that need to be kept because they are # parent directories of files specified in keep_files # # Returns a Set with the directory paths def keep_dirs site.keep_files.map { |file| parent_dirs(site.in_dest_dir(file)) }.flatten.to_set end # Private: Creates a regular expression from the config's keep_files array # # Examples # ['.git','.svn'] with site.dest "/myblog/_site" creates # the following regex: /\A\/myblog\/_site\/(\.git|\/.svn)/ # # Returns the regular expression def keep_file_regex %r!\A#{Regexp.quote(site.dest)}\/(#{Regexp.union(site.keep_files).source})! 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/related_posts.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/related_posts.rb
# frozen_string_literal: true module Jekyll class RelatedPosts class << self attr_accessor :lsi end attr_reader :post, :site def initialize(post) @post = post @site = post.site Jekyll::External.require_with_graceful_fail("classifier-reborn") if site.lsi end def build return [] unless site.posts.docs.size > 1 if site.lsi build_index lsi_related_posts else most_recent_posts end end def build_index self.class.lsi ||= begin lsi = ClassifierReborn::LSI.new(:auto_rebuild => false) Jekyll.logger.info("Populating LSI...") site.posts.docs.each do |x| lsi.add_item(x) end Jekyll.logger.info("Rebuilding index...") lsi.build_index Jekyll.logger.info("") lsi end end def lsi_related_posts self.class.lsi.find_related(post, 11) end def most_recent_posts @most_recent_posts ||= (site.posts.docs.last(11).reverse - [post]).first(10) 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/theme_builder.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/theme_builder.rb
# frozen_string_literal: true class Jekyll::ThemeBuilder SCAFFOLD_DIRECTORIES = %w( assets _layouts _includes _sass ).freeze attr_reader :name, :path, :code_of_conduct def initialize(theme_name, opts) @name = theme_name.to_s.tr(" ", "_").squeeze("_") @path = Pathname.new(File.expand_path(name, Dir.pwd)) @code_of_conduct = !!opts["code_of_conduct"] end def create! create_directories create_starter_files create_gemspec create_accessories initialize_git_repo end def user_name @user_name ||= `git config user.name`.chomp end def user_email @user_email ||= `git config user.email`.chomp end private def root @root ||= Pathname.new(File.expand_path("../", __dir__)) end def template_file(filename) [ root.join("theme_template", "#{filename}.erb"), root.join("theme_template", filename.to_s), ].find(&:exist?) end def template(filename) erb.render(template_file(filename).read) end def erb @erb ||= ERBRenderer.new(self) end def mkdir_p(directories) Array(directories).each do |directory| full_path = path.join(directory) Jekyll.logger.info "create", full_path.to_s FileUtils.mkdir_p(full_path) end end def write_file(filename, contents) full_path = path.join(filename) Jekyll.logger.info "create", full_path.to_s File.write(full_path, contents) end def create_directories mkdir_p(SCAFFOLD_DIRECTORIES) end def create_starter_files %w(page post default).each do |layout| write_file("_layouts/#{layout}.html", template("_layouts/#{layout}.html")) end end def create_gemspec write_file("Gemfile", template("Gemfile")) write_file("#{name}.gemspec", template("theme.gemspec")) end def create_accessories accessories = %w(README.md LICENSE.txt) accessories << "CODE_OF_CONDUCT.md" if code_of_conduct accessories.each do |filename| write_file(filename, template(filename)) end end def initialize_git_repo Jekyll.logger.info "initialize", path.join(".git").to_s Dir.chdir(path.to_s) { `git init` } write_file(".gitignore", template("gitignore")) end class ERBRenderer extend Forwardable def_delegator :@theme_builder, :name, :theme_name def_delegator :@theme_builder, :user_name, :user_name def_delegator :@theme_builder, :user_email, :user_email def initialize(theme_builder) @theme_builder = theme_builder end def jekyll_version_with_minor Jekyll::VERSION.split(".").take(2).join(".") end def theme_directories SCAFFOLD_DIRECTORIES end def render(contents) ERB.new(contents).result binding 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/stevenson.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/stevenson.rb
# frozen_string_literal: true module Jekyll class Stevenson < ::Logger def initialize @progname = nil @level = DEBUG @default_formatter = Formatter.new @logdev = $stdout @formatter = proc do |_, _, _, msg| msg.to_s end end def add(severity, message = nil, progname = nil) severity ||= UNKNOWN @logdev = logdevice(severity) if @logdev.nil? || severity < @level return true end progname ||= @progname if message.nil? if block_given? message = yield else message = progname progname = @progname end end @logdev.puts( format_message(format_severity(severity), Time.now, progname, message) ) true end # Log a +WARN+ message def warn(progname = nil, &block) add(WARN, nil, progname.yellow, &block) end # Log an +ERROR+ message def error(progname = nil, &block) add(ERROR, nil, progname.red, &block) end def close # No LogDevice in use end private def logdevice(severity) if severity > INFO $stderr else $stdout 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/url.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/url.rb
# frozen_string_literal: true # Public: Methods that generate a URL for a resource such as a Post or a Page. # # Examples # # URL.new({ # :template => /:categories/:title.html", # :placeholders => {:categories => "ruby", :title => "something"} # }).to_s # module Jekyll class URL # options - One of :permalink or :template must be supplied. # :template - The String used as template for URL generation, # for example "/:path/:basename:output_ext", where # a placeholder is prefixed with a colon. # :placeholders - A hash containing the placeholders which will be # replaced when used inside the template. E.g. # { "year" => Time.now.strftime("%Y") } would replace # the placeholder ":year" with the current year. # :permalink - If supplied, no URL will be generated from the # template. Instead, the given permalink will be # used as URL. def initialize(options) @template = options[:template] @placeholders = options[:placeholders] || {} @permalink = options[:permalink] if (@template || @permalink).nil? raise ArgumentError, "One of :template or :permalink must be supplied." end end # The generated relative URL of the resource # # Returns the String URL def to_s sanitize_url(generated_permalink || generated_url) end # Generates a URL from the permalink # # Returns the _unsanitized String URL def generated_permalink (@generated_permalink ||= generate_url(@permalink)) if @permalink end # Generates a URL from the template # # Returns the unsanitized String URL def generated_url @generated_url ||= generate_url(@template) end # Internal: Generate the URL by replacing all placeholders with their # respective values in the given template # # Returns the unsanitized String URL def generate_url(template) if @placeholders.is_a? Drops::UrlDrop generate_url_from_drop(template) else generate_url_from_hash(template) end end def generate_url_from_hash(template) @placeholders.inject(template) do |result, token| break result if result.index(":").nil? if token.last.nil? # Remove leading "/" to avoid generating urls with `//` result.gsub("/:#{token.first}", "") else result.gsub(":#{token.first}", self.class.escape_path(token.last)) end end end # We include underscores in keys to allow for 'i_month' and so forth. # This poses a problem for keys which are followed by an underscore # but the underscore is not part of the key, e.g. '/:month_:day'. # That should be :month and :day, but our key extraction regexp isn't # smart enough to know that so we have to make it an explicit # possibility. def possible_keys(key) if key.end_with?("_") [key, key.chomp("_")] else [key] end end def generate_url_from_drop(template) template.gsub(%r!:([a-z_]+)!) do |match| pool = possible_keys(match.sub(":", "")) winner = pool.find { |key| @placeholders.key?(key) } if winner.nil? raise NoMethodError, "The URL template doesn't have #{pool.join(" or ")} keys. "\ "Check your permalink template!" end value = @placeholders[winner] value = "" if value.nil? replacement = self.class.escape_path(value) match.sub(":#{winner}", replacement) end.squeeze("/") end # Returns a sanitized String URL, stripping "../../" and multiples of "/", # as well as the beginning "/" so we can enforce and ensure it. def sanitize_url(str) "/#{str}".gsub("..", "/").gsub("./", "").squeeze("/") end # Escapes a path to be a valid URL path segment # # path - The path to be escaped. # # Examples: # # URL.escape_path("/a b") # # => "/a%20b" # # Returns the escaped path. def self.escape_path(path) # Because URI.escape doesn't escape "?", "[" and "]" by default, # specify unsafe string (except unreserved, sub-delims, ":", "@" and "/"). # # URI path segment is defined in RFC 3986 as follows: # segment = *pchar # pchar = unreserved / pct-encoded / sub-delims / ":" / "@" # unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" # pct-encoded = "%" HEXDIG HEXDIG # sub-delims = "!" / "$" / "&" / "'" / "(" / ")" # / "*" / "+" / "," / ";" / "=" path = Addressable::URI.encode(path) path.encode("utf-8").sub("#", "%23") end # Unescapes a URL path segment # # path - The path to be unescaped. # # Examples: # # URL.unescape_path("/a%20b") # # => "/a b" # # Returns the unescaped path. def self.unescape_path(path) Addressable::URI.unencode(path.encode("utf-8")) 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/configuration.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/configuration.rb
# frozen_string_literal: true module Jekyll class Configuration < Hash # Default options. Overridden by values in _config.yml. # Strings rather than symbols are used for compatibility with YAML. DEFAULTS = Configuration[{ # Where things are "source" => Dir.pwd, "destination" => File.join(Dir.pwd, "_site"), "collections_dir" => "", "plugins_dir" => "_plugins", "layouts_dir" => "_layouts", "data_dir" => "_data", "includes_dir" => "_includes", "collections" => {}, # Handling Reading "safe" => false, "include" => [".htaccess"], "exclude" => %w( Gemfile Gemfile.lock node_modules vendor/bundle/ vendor/cache/ vendor/gems/ vendor/ruby/ ), "keep_files" => [".git", ".svn"], "encoding" => "utf-8", "markdown_ext" => "markdown,mkdown,mkdn,mkd,md", "strict_front_matter" => false, # Filtering Content "show_drafts" => nil, "limit_posts" => 0, "future" => false, "unpublished" => false, # Plugins "whitelist" => [], "plugins" => [], # Conversion "markdown" => "kramdown", "highlighter" => "rouge", "lsi" => false, "excerpt_separator" => "\n\n", "incremental" => false, # Serving "detach" => false, # default to not detaching the server "port" => "4000", "host" => "127.0.0.1", "baseurl" => nil, # this mounts at /, i.e. no subdirectory "show_dir_listing" => false, # Output Configuration "permalink" => "date", "paginate_path" => "/page:num", "timezone" => nil, # use the local timezone "quiet" => false, "verbose" => false, "defaults" => [], "liquid" => { "error_mode" => "warn", "strict_filters" => false, "strict_variables" => false, }, "rdiscount" => { "extensions" => [], }, "redcarpet" => { "extensions" => [], }, "kramdown" => { "auto_ids" => true, "toc_levels" => "1..6", "entity_output" => "as_char", "smart_quotes" => "lsquo,rsquo,ldquo,rdquo", "input" => "GFM", "hard_wrap" => false, "footnote_nr" => 1, "show_warnings" => false, }, }.map { |k, v| [k, v.freeze] }].freeze class << self # Static: Produce a Configuration ready for use in a Site. # It takes the input, fills in the defaults where values do not # exist, and patches common issues including migrating options for # backwards compatiblity. Except where a key or value is being fixed, # the user configuration will override the defaults. # # user_config - a Hash or Configuration of overrides. # # Returns a Configuration filled with defaults and fixed for common # problems and backwards-compatibility. def from(user_config) Utils.deep_merge_hashes(DEFAULTS, Configuration[user_config].stringify_keys) .add_default_collections end end # Public: Turn all keys into string # # Return a copy of the hash where all its keys are strings def stringify_keys reduce({}) { |hsh, (k, v)| hsh.merge(k.to_s => v) } end def get_config_value_with_override(config_key, override) override[config_key] || self[config_key] || DEFAULTS[config_key] end # Public: Directory of the Jekyll source folder # # override - the command-line options hash # # Returns the path to the Jekyll source directory def source(override) get_config_value_with_override("source", override) end def quiet(override = {}) get_config_value_with_override("quiet", override) end alias_method :quiet?, :quiet def verbose(override = {}) get_config_value_with_override("verbose", override) end alias_method :verbose?, :verbose def safe_load_file(filename) case File.extname(filename) when %r!\.toml!i Jekyll::External.require_with_graceful_fail("tomlrb") unless defined?(Tomlrb) Tomlrb.load_file(filename) when %r!\.ya?ml!i SafeYAML.load_file(filename) || {} else raise ArgumentError, "No parser for '#{filename}' is available. Use a .y(a)ml or .toml file instead." end end # Public: Generate list of configuration files from the override # # override - the command-line options hash # # Returns an Array of config files def config_files(override) # Adjust verbosity quickly Jekyll.logger.adjust_verbosity( :quiet => quiet?(override), :verbose => verbose?(override) ) # Get configuration from <source>/_config.yml or <source>/<config_file> config_files = override["config"] if config_files.to_s.empty? default = %w(yml yaml).find(-> { "yml" }) do |ext| File.exist?(Jekyll.sanitized_path(source(override), "_config.#{ext}")) end config_files = Jekyll.sanitized_path(source(override), "_config.#{default}") @default_config_file = true end Array(config_files) end # Public: Read configuration and return merged Hash # # file - the path to the YAML file to be read in # # Returns this configuration, overridden by the values in the file def read_config_file(file) next_config = safe_load_file(file) check_config_is_hash!(next_config, file) Jekyll.logger.info "Configuration file:", file next_config rescue SystemCallError if @default_config_file ||= nil Jekyll.logger.warn "Configuration file:", "none" {} else Jekyll.logger.error "Fatal:", "The configuration file '#{file}' could not be found." raise LoadError, "The Configuration file '#{file}' could not be found." end end # Public: Read in a list of configuration files and merge with this hash # # files - the list of configuration file paths # # Returns the full configuration, with the defaults overridden by the values in the # configuration files def read_config_files(files) configuration = clone begin files.each do |config_file| next if config_file.nil? || config_file.empty? new_config = read_config_file(config_file) configuration = Utils.deep_merge_hashes(configuration, new_config) end rescue ArgumentError => err Jekyll.logger.warn "WARNING:", "Error reading configuration. " \ "Using defaults (and options)." warn err end configuration.backwards_compatibilize.add_default_collections end # Public: Split a CSV string into an array containing its values # # csv - the string of comma-separated values # # Returns an array of the values contained in the CSV def csv_to_array(csv) csv.split(",").map(&:strip) end # Public: Ensure the proper options are set in the configuration to allow for # backwards-compatibility with Jekyll pre-1.0 # # Returns the backwards-compatible configuration def backwards_compatibilize config = clone # Provide backwards-compatibility check_auto(config) check_server(config) check_plugins(config) renamed_key "server_port", "port", config renamed_key "gems", "plugins", config renamed_key "layouts", "layouts_dir", config renamed_key "data_source", "data_dir", config check_pygments(config) check_include_exclude(config) check_coderay(config) check_maruku(config) config end # DEPRECATED. def fix_common_issues self end def add_default_collections config = clone # It defaults to `{}`, so this is only if someone sets it to null manually. return config if config["collections"].nil? # Ensure we have a hash. if config["collections"].is_a?(Array) config["collections"] = Hash[config["collections"].map { |c| [c, {}] }] end config["collections"] = Utils.deep_merge_hashes( { "posts" => {} }, config["collections"] ).tap do |collections| collections["posts"]["output"] = true if config["permalink"] collections["posts"]["permalink"] ||= style_to_permalink(config["permalink"]) end end config end def renamed_key(old, new, config, _ = nil) if config.key?(old) Jekyll::Deprecator.deprecation_message "The '#{old}' configuration" \ " option has been renamed to '#{new}'. Please update your config" \ " file accordingly." config[new] = config.delete(old) end end private def style_to_permalink(permalink_style) case permalink_style.to_sym when :pretty "/:categories/:year/:month/:day/:title/" when :none "/:categories/:title:output_ext" when :date "/:categories/:year/:month/:day/:title:output_ext" when :ordinal "/:categories/:year/:y_day/:title:output_ext" else permalink_style.to_s end end # Private: Checks if a given config is a hash # # extracted_config - the value to check # file - the file from which the config was extracted # # Raises an ArgumentError if given config is not a hash private def check_config_is_hash!(extracted_config, file) unless extracted_config.is_a?(Hash) raise ArgumentError, "Configuration file: (INVALID) #{file}".yellow end end private def check_auto(config) if config.key?("auto") || config.key?("watch") Jekyll::Deprecator.deprecation_message "Auto-regeneration can no longer" \ " be set from your configuration file(s). Use the" \ " --[no-]watch/-w command-line option instead." config.delete("auto") config.delete("watch") end end private def check_server(config) if config.key?("server") Jekyll::Deprecator.deprecation_message "The 'server' configuration option" \ " is no longer accepted. Use the 'jekyll serve'" \ " subcommand to serve your site with WEBrick." config.delete("server") end end private def check_pygments(config) if config.key?("pygments") Jekyll::Deprecator.deprecation_message "The 'pygments' configuration option" \ " has been renamed to 'highlighter'. Please update your" \ " config file accordingly. The allowed values are 'rouge', " \ "'pygments' or null." config["highlighter"] = "pygments" if config["pygments"] config.delete("pygments") end end private def check_include_exclude(config) %w(include exclude).each do |option| if config[option].is_a?(String) Jekyll::Deprecator.deprecation_message "The '#{option}' configuration option" \ " must now be specified as an array, but you specified" \ " a string. For now, we've treated the string you provided" \ " as a list of comma-separated values." config[option] = csv_to_array(config[option]) end config[option].map!(&:to_s) if config[option] end end private def check_coderay(config) if (config["kramdown"] || {}).key?("use_coderay") Jekyll::Deprecator.deprecation_message "Please change 'use_coderay'" \ " to 'enable_coderay' in your configuration file." config["kramdown"]["use_coderay"] = config["kramdown"].delete("enable_coderay") end end private def check_maruku(config) if config.fetch("markdown", "kramdown").to_s.casecmp("maruku").zero? Jekyll.logger.abort_with "Error:", "You're using the 'maruku' " \ "Markdown processor, which has been removed as of 3.0.0. " \ "We recommend you switch to Kramdown. To do this, replace " \ "`markdown: maruku` with `markdown: kramdown` in your " \ "`_config.yml` file." end end # Private: Checks if the `plugins` config is a String # # config - the config hash # # Raises a Jekyll::Errors::InvalidConfigurationError if the config `plugins` # is a string private def check_plugins(config) if config.key?("plugins") && config["plugins"].is_a?(String) Jekyll.logger.error "Configuration Error:", "You specified the" \ " `plugins` config in your configuration file as a string, please" \ " use an array instead. If you wanted to set the directory of your" \ " plugins, use the config key `plugins_dir` instead." raise Jekyll::Errors::InvalidConfigurationError, "'plugins' should not be a string, but was: " \ "#{config["plugins"].inspect}. Use 'plugins_dir' instead." 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/page_without_a_file.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/page_without_a_file.rb
# frozen_string_literal: true module Jekyll # A Jekyll::Page subclass to handle processing files without reading it to # determine the page-data and page-content based on Front Matter delimiters. # # The class instance is basically just a bare-bones entity with just # attributes "dir", "name", "path", "url" defined on it. class PageWithoutAFile < Page def read_yaml(*) @data ||= {} end def inspect "#<Jekyll:PageWithoutAFile @name=#{name.inspect}>" 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/regenerator.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/regenerator.rb
# frozen_string_literal: true module Jekyll class Regenerator attr_reader :site, :metadata, :cache attr_accessor :disabled private :disabled, :disabled= def initialize(site) @site = site # Read metadata from file read_metadata # Initialize cache to an empty hash clear_cache end # Checks if a renderable object needs to be regenerated # # Returns a boolean. def regenerate?(document) return true if disabled case document when Page regenerate_page?(document) when Document regenerate_document?(document) else source_path = document.respond_to?(:path) ? document.path : nil dest_path = if document.respond_to?(:destination) document.destination(@site.dest) end source_modified_or_dest_missing?(source_path, dest_path) end end # Add a path to the metadata # # Returns true, also on failure. def add(path) return true unless File.exist?(path) metadata[path] = { "mtime" => File.mtime(path), "deps" => [], } cache[path] = true end # Force a path to regenerate # # Returns true. def force(path) cache[path] = true end # Clear the metadata and cache # # Returns nothing def clear @metadata = {} clear_cache end # Clear just the cache # # Returns nothing def clear_cache @cache = {} end # Checks if the source has been modified or the # destination is missing # # returns a boolean def source_modified_or_dest_missing?(source_path, dest_path) modified?(source_path) || (dest_path && !File.exist?(dest_path)) end # Checks if a path's (or one of its dependencies) # mtime has changed # # Returns a boolean. def modified?(path) return true if disabled? # objects that don't have a path are always regenerated return true if path.nil? # Check for path in cache if cache.key? path return cache[path] end if metadata[path] # If we have seen this file before, # check if it or one of its dependencies has been modified existing_file_modified?(path) else # If we have not seen this file before, add it to the metadata and regenerate it add(path) end end # Add a dependency of a path # # Returns nothing. def add_dependency(path, dependency) return if metadata[path].nil? || disabled unless metadata[path]["deps"].include? dependency metadata[path]["deps"] << dependency add(dependency) unless metadata.include?(dependency) end regenerate? dependency end # Write the metadata to disk # # Returns nothing. def write_metadata unless disabled? Jekyll.logger.debug "Writing Metadata:", ".jekyll-metadata" File.binwrite(metadata_file, Marshal.dump(metadata)) end end # Produce the absolute path of the metadata file # # Returns the String path of the file. def metadata_file @metadata_file ||= site.in_source_dir(".jekyll-metadata") end # Check if metadata has been disabled # # Returns a Boolean (true for disabled, false for enabled). def disabled? self.disabled = !site.incremental? if disabled.nil? disabled end private # Read metadata from the metadata file, if no file is found, # initialize with an empty hash # # Returns the read metadata. def read_metadata @metadata = if !disabled? && File.file?(metadata_file) content = File.binread(metadata_file) begin Marshal.load(content) rescue TypeError SafeYAML.load(content) rescue ArgumentError => e Jekyll.logger.warn("Failed to load #{metadata_file}: #{e}") {} end else {} end end private def regenerate_page?(document) document.asset_file? || document.data["regenerate"] || source_modified_or_dest_missing?( site.in_source_dir(document.relative_path), document.destination(@site.dest) ) end private def regenerate_document?(document) !document.write? || document.data["regenerate"] || source_modified_or_dest_missing?( document.path, document.destination(@site.dest) ) end private def existing_file_modified?(path) # If one of this file dependencies have been modified, # set the regeneration bit for both the dependency and the file to true metadata[path]["deps"].each do |dependency| if modified?(dependency) return cache[dependency] = cache[path] = true end end if File.exist?(path) && metadata[path]["mtime"].eql?(File.mtime(path)) # If this file has not been modified, set the regeneration bit to false cache[path] = false else # If it has been modified, set it to true add(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/jekyll-3.8.4/lib/jekyll/liquid_extensions.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/liquid_extensions.rb
# frozen_string_literal: true module Jekyll module LiquidExtensions # Lookup a Liquid variable in the given context. # # context - the Liquid context in question. # variable - the variable name, as a string. # # Returns the value of the variable in the context # or the variable name if not found. def lookup_variable(context, variable) lookup = context variable.split(".").each do |value| lookup = lookup[value] end lookup || variable 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/entry_filter.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/entry_filter.rb
# frozen_string_literal: true module Jekyll class EntryFilter attr_reader :site SPECIAL_LEADING_CHARACTERS = [ ".", "_", "#", "~", ].freeze def initialize(site, base_directory = nil) @site = site @base_directory = derive_base_directory( @site, base_directory.to_s.dup ) end def base_directory @base_directory.to_s end def derive_base_directory(site, base_dir) base_dir[site.source] = "" if base_dir.start_with?(site.source) base_dir end def relative_to_source(entry) File.join( base_directory, entry ) end def filter(entries) entries.reject do |e| # Reject this entry if it is a symlink. next true if symlink?(e) # Do not reject this entry if it is included. next false if included?(e) # Reject this entry if it is special, a backup file, or excluded. special?(e) || backup?(e) || excluded?(e) end end def included?(entry) glob_include?(site.include, entry) || glob_include?(site.include, File.basename(entry)) end def special?(entry) SPECIAL_LEADING_CHARACTERS.include?(entry[0..0]) || SPECIAL_LEADING_CHARACTERS.include?(File.basename(entry)[0..0]) end def backup?(entry) entry[-1..-1] == "~" end def excluded?(entry) glob_include?(site.exclude, relative_to_source(entry)).tap do |excluded| if excluded Jekyll.logger.debug( "EntryFilter:", "excluded #{relative_to_source(entry)}" ) end end end # -- # Check if a file is a symlink. # NOTE: This can be converted to allowing even in safe, # since we use Pathutil#in_path? now. # -- def symlink?(entry) site.safe && File.symlink?(entry) && symlink_outside_site_source?(entry) end # -- # NOTE: Pathutil#in_path? gets the realpath. # @param [<Anything>] entry the entry you want to validate. # Check if a path is outside of our given root. # -- def symlink_outside_site_source?(entry) !Pathutil.new(entry).in_path?( site.in_source_dir ) end # -- # Check if an entry matches a specific pattern and return true,false. # Returns true if path matches against any glob pattern. # -- def glob_include?(enum, entry) entry_path = Pathutil.new(site.in_source_dir).join(entry) enum.any? do |exp| # Users who send a Regexp knows what they want to # exclude, so let them send a Regexp to exclude files, # we will not bother caring if it works or not, it's # on them at this point. if exp.is_a?(Regexp) entry_path =~ exp else item = Pathutil.new(site.in_source_dir).join(exp) # If it's a directory they want to exclude, AKA # ends with a "/" then we will go on to check and # see if the entry falls within that path and # exclude it if that's the case. if entry.end_with?("/") entry_path.in_path?( item ) else File.fnmatch?(item, entry_path) || entry_path.to_path.start_with?( item ) 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/renderer.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/renderer.rb
# frozen_string_literal: true module Jekyll class Renderer attr_reader :document, :site attr_writer :layouts, :payload def initialize(site, document, site_payload = nil) @site = site @document = document @payload = site_payload end # Fetches the payload used in Liquid rendering. # It can be written with #payload=(new_payload) # Falls back to site.site_payload if no payload is set. # # Returns a Jekyll::Drops::UnifiedPayloadDrop def payload @payload ||= site.site_payload end # The list of layouts registered for this Renderer. # It can be written with #layouts=(new_layouts) # Falls back to site.layouts if no layouts are registered. # # Returns a Hash of String => Jekyll::Layout identified # as basename without the extension name. def layouts @layouts || site.layouts end # Determine which converters to use based on this document's # extension. # # Returns Array of Converter instances. def converters @converters ||= site.converters.select { |c| c.matches(document.extname) }.sort end # Determine the extname the outputted file should have # # Returns String the output extname including the leading period. def output_ext @output_ext ||= (permalink_ext || converter_output_ext) end # Prepare payload and render the document # # Returns String rendered document output def run Jekyll.logger.debug "Rendering:", document.relative_path assign_pages! assign_current_document! assign_highlighter_options! assign_layout_data! Jekyll.logger.debug "Pre-Render Hooks:", document.relative_path document.trigger_hooks(:pre_render, payload) render_document end # Render the document. # # Returns String rendered document output # rubocop: disable AbcSize def render_document info = { :registers => { :site => site, :page => payload["page"] }, :strict_filters => liquid_options["strict_filters"], :strict_variables => liquid_options["strict_variables"], } output = document.content if document.render_with_liquid? Jekyll.logger.debug "Rendering Liquid:", document.relative_path output = render_liquid(output, payload, info, document.path) end Jekyll.logger.debug "Rendering Markup:", document.relative_path output = convert(output.to_s) document.content = output if document.place_in_layout? Jekyll.logger.debug "Rendering Layout:", document.relative_path output = place_in_layouts(output, payload, info) end output end # rubocop: enable AbcSize # Convert the document using the converters which match this renderer's document. # # Returns String the converted content. def convert(content) converters.reduce(content) do |output, converter| begin converter.convert output rescue StandardError => e Jekyll.logger.error "Conversion error:", "#{converter.class} encountered an error while "\ "converting '#{document.relative_path}':" Jekyll.logger.error("", e.to_s) raise e end end end # Render the given content with the payload and info # # content - # payload - # info - # path - (optional) the path to the file, for use in ex # # Returns String the content, rendered by Liquid. def render_liquid(content, payload, info, path = nil) template = site.liquid_renderer.file(path).parse(content) template.warnings.each do |e| Jekyll.logger.warn "Liquid Warning:", LiquidRenderer.format_error(e, path || document.relative_path) end template.render!(payload, info) # rubocop: disable RescueException rescue Exception => e Jekyll.logger.error "Liquid Exception:", LiquidRenderer.format_error(e, path || document.relative_path) raise e end # rubocop: enable RescueException # Checks if the layout specified in the document actually exists # # layout - the layout to check # # Returns Boolean true if the layout is invalid, false if otherwise def invalid_layout?(layout) !document.data["layout"].nil? && layout.nil? && !(document.is_a? Jekyll::Excerpt) end # Render layouts and place document content inside. # # Returns String rendered content def place_in_layouts(content, payload, info) output = content.dup layout = layouts[document.data["layout"].to_s] validate_layout(layout) used = Set.new([layout]) # Reset the payload layout data to ensure it starts fresh for each page. payload["layout"] = nil while layout output = render_layout(output, layout, info) add_regenerator_dependencies(layout) if (layout = site.layouts[layout.data["layout"]]) break if used.include?(layout) used << layout end end output end # Checks if the layout specified in the document actually exists # # layout - the layout to check # Returns nothing private def validate_layout(layout) if invalid_layout?(layout) Jekyll.logger.warn( "Build Warning:", "Layout '#{document.data["layout"]}' requested "\ "in #{document.relative_path} does not exist." ) elsif !layout.nil? layout_source = layout.path.start_with?(site.source) ? :site : :theme Jekyll.logger.debug "Layout source:", layout_source end end # Render layout content into document.output # # Returns String rendered content private def render_layout(output, layout, info) payload["content"] = output payload["layout"] = Utils.deep_merge_hashes(layout.data, payload["layout"] || {}) render_liquid( layout.content, payload, info, layout.relative_path ) end private def add_regenerator_dependencies(layout) return unless document.write? site.regenerator.add_dependency( site.in_source_dir(document.path), layout.path ) end # Set page content to payload and assign pager if document has one. # # Returns nothing private def assign_pages! payload["page"] = document.to_liquid payload["paginator"] = if document.respond_to?(:pager) document.pager.to_liquid end end # Set related posts to payload if document is a post. # # Returns nothing private def assign_current_document! payload["site"].current_document = document end # Set highlighter prefix and suffix # # Returns nothing private def assign_highlighter_options! payload["highlighter_prefix"] = converters.first.highlighter_prefix payload["highlighter_suffix"] = converters.first.highlighter_suffix end private def assign_layout_data! layout = layouts[document.data["layout"]] if layout payload["layout"] = Utils.deep_merge_hashes(layout.data, payload["layout"] || {}) end end private def permalink_ext document_permalink = document.permalink if document_permalink && !document_permalink.end_with?("/") permalink_ext = File.extname(document_permalink) permalink_ext unless permalink_ext.empty? end end private def converter_output_ext if output_exts.size == 1 output_exts.last else output_exts[-2] end end private def output_exts @output_exts ||= converters.map do |c| c.output_ext(document.extname) end.compact end private def liquid_options @liquid_options ||= site.config["liquid"] 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/generator.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/generator.rb
# frozen_string_literal: true module Jekyll Generator = Class.new(Plugin) 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/filters.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/filters.rb
# frozen_string_literal: true require_all "jekyll/filters" module Jekyll module Filters include URLFilters include GroupingFilters include DateFilters # Convert a Markdown string into HTML output. # # input - The Markdown String to convert. # # Returns the HTML formatted String. def markdownify(input) @context.registers[:site].find_converter_instance( Jekyll::Converters::Markdown ).convert(input.to_s) end # Convert quotes into smart quotes. # # input - The String to convert. # # Returns the smart-quotified String. def smartify(input) @context.registers[:site].find_converter_instance( Jekyll::Converters::SmartyPants ).convert(input.to_s) end # Convert a Sass string into CSS output. # # input - The Sass String to convert. # # Returns the CSS formatted String. def sassify(input) @context.registers[:site].find_converter_instance( Jekyll::Converters::Sass ).convert(input) end # Convert a Scss string into CSS output. # # input - The Scss String to convert. # # Returns the CSS formatted String. def scssify(input) @context.registers[:site].find_converter_instance( Jekyll::Converters::Scss ).convert(input) end # Slugify a filename or title. # # input - The filename or title to slugify. # mode - how string is slugified # # Returns the given filename or title as a lowercase URL String. # See Utils.slugify for more detail. def slugify(input, mode = nil) Utils.slugify(input, :mode => mode) end # XML escape a string for use. Replaces any special characters with # appropriate HTML entity replacements. # # input - The String to escape. # # Examples # # xml_escape('foo "bar" <baz>') # # => "foo &quot;bar&quot; &lt;baz&gt;" # # Returns the escaped String. def xml_escape(input) input.to_s.encode(:xml => :attr).gsub(%r!\A"|"\Z!, "") end # CGI escape a string for use in a URL. Replaces any special characters # with appropriate %XX replacements. # # input - The String to escape. # # Examples # # cgi_escape('foo,bar;baz?') # # => "foo%2Cbar%3Bbaz%3F" # # Returns the escaped String. def cgi_escape(input) CGI.escape(input) end # URI escape a string. # # input - The String to escape. # # Examples # # uri_escape('foo, bar \\baz?') # # => "foo,%20bar%20%5Cbaz?" # # Returns the escaped String. def uri_escape(input) Addressable::URI.normalize_component(input) end # Replace any whitespace in the input string with a single space # # input - The String on which to operate. # # Returns the formatted String def normalize_whitespace(input) input.to_s.gsub(%r!\s+!, " ").strip end # Count the number of words in the input string. # # input - The String on which to operate. # # Returns the Integer word count. def number_of_words(input) input.split.length end # Join an array of things into a string by separating with commas and the # word "and" for the last one. # # array - The Array of Strings to join. # connector - Word used to connect the last 2 items in the array # # Examples # # array_to_sentence_string(["apples", "oranges", "grapes"]) # # => "apples, oranges, and grapes" # # Returns the formatted String. def array_to_sentence_string(array, connector = "and") case array.length when 0 "" when 1 array[0].to_s when 2 "#{array[0]} #{connector} #{array[1]}" else "#{array[0...-1].join(", ")}, #{connector} #{array[-1]}" end end # Convert the input into json string # # input - The Array or Hash to be converted # # Returns the converted json string def jsonify(input) as_liquid(input).to_json end # Filter an array of objects # # input - the object array # property - property within each object to filter by # value - desired value # # Returns the filtered array of objects def where(input, property, value) return input if property.nil? || value.nil? return input unless input.respond_to?(:select) input = input.values if input.is_a?(Hash) input_id = input.hash # implement a hash based on method parameters to cache the end-result # for given parameters. @where_filter_cache ||= {} @where_filter_cache[input_id] ||= {} @where_filter_cache[input_id][property] ||= {} # stash or retrive results to return @where_filter_cache[input_id][property][value] ||= begin input.select do |object| Array(item_property(object, property)).map!(&:to_s).include?(value.to_s) end || [] end end # Filters an array of objects against an expression # # input - the object array # variable - the variable to assign each item to in the expression # expression - a Liquid comparison expression passed in as a string # # Returns the filtered array of objects def where_exp(input, variable, expression) return input unless input.respond_to?(:select) input = input.values if input.is_a?(Hash) # FIXME condition = parse_condition(expression) @context.stack do input.select do |object| @context[variable] = object condition.evaluate(@context) end end || [] end # Convert the input into integer # # input - the object string # # Returns the integer value def to_integer(input) return 1 if input == true return 0 if input == false input.to_i end # Sort an array of objects # # input - the object array # property - property within each object to filter by # nils ('first' | 'last') - nils appear before or after non-nil values # # Returns the filtered array of objects def sort(input, property = nil, nils = "first") if input.nil? raise ArgumentError, "Cannot sort a null object." end if property.nil? input.sort else if nils == "first" order = - 1 elsif nils == "last" order = + 1 else raise ArgumentError, "Invalid nils order: " \ "'#{nils}' is not a valid nils order. It must be 'first' or 'last'." end sort_input(input, property, order) end end def pop(array, num = 1) return array unless array.is_a?(Array) num = Liquid::Utils.to_integer(num) new_ary = array.dup new_ary.pop(num) new_ary end def push(array, input) return array unless array.is_a?(Array) new_ary = array.dup new_ary.push(input) new_ary end def shift(array, num = 1) return array unless array.is_a?(Array) num = Liquid::Utils.to_integer(num) new_ary = array.dup new_ary.shift(num) new_ary end def unshift(array, input) return array unless array.is_a?(Array) new_ary = array.dup new_ary.unshift(input) new_ary end def sample(input, num = 1) return input unless input.respond_to?(:sample) num = Liquid::Utils.to_integer(num) rescue 1 if num == 1 input.sample else input.sample(num) end end # Convert an object into its String representation for debugging # # input - The Object to be converted # # Returns a String representation of the object. def inspect(input) xml_escape(input.inspect) end private # Sort the input Enumerable by the given property. # If the property doesn't exist, return the sort order respective of # which item doesn't have the property. # We also utilize the Schwartzian transform to make this more efficient. def sort_input(input, property, order) input.map { |item| [item_property(item, property), item] } .sort! do |apple_info, orange_info| apple_property = apple_info.first orange_property = orange_info.first if !apple_property.nil? && orange_property.nil? - order elsif apple_property.nil? && !orange_property.nil? + order else apple_property <=> orange_property end end .map!(&:last) end private def item_property(item, property) if item.respond_to?(:to_liquid) property.to_s.split(".").reduce(item.to_liquid) do |subvalue, attribute| subvalue[attribute] end elsif item.respond_to?(:data) item.data[property.to_s] else item[property.to_s] end end private def as_liquid(item) case item when Hash pairs = item.map { |k, v| as_liquid([k, v]) } Hash[pairs] when Array item.map { |i| as_liquid(i) } else if item.respond_to?(:to_liquid) liquidated = item.to_liquid # prevent infinite recursion for simple types (which return `self`) if liquidated == item item else as_liquid(liquidated) end else item end end end # Parse a string to a Liquid Condition private def parse_condition(exp) parser = Liquid::Parser.new(exp) left_expr = parser.expression operator = parser.consume?(:comparison) condition = if operator Liquid::Condition.new(Liquid::Expression.parse(left_expr), operator, Liquid::Expression.parse(parser.expression)) else Liquid::Condition.new(Liquid::Expression.parse(left_expr)) end parser.consume(:end_of_string) condition end end end Liquid::Template.register_filter( Jekyll::Filters )
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/frontmatter_defaults.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/frontmatter_defaults.rb
# frozen_string_literal: true module Jekyll # This class handles custom defaults for YAML frontmatter settings. # These are set in _config.yml and apply both to internal use (e.g. layout) # and the data available to liquid. # # It is exposed via the frontmatter_defaults method on the site class. class FrontmatterDefaults # Initializes a new instance. def initialize(site) @site = site end def update_deprecated_types(set) return set unless set.key?("scope") && set["scope"].key?("type") set["scope"]["type"] = case set["scope"]["type"] when "page" Deprecator.defaults_deprecate_type("page", "pages") "pages" when "post" Deprecator.defaults_deprecate_type("post", "posts") "posts" when "draft" Deprecator.defaults_deprecate_type("draft", "drafts") "drafts" else set["scope"]["type"] end set end def ensure_time!(set) return set unless set.key?("values") && set["values"].key?("date") return set if set["values"]["date"].is_a?(Time) set["values"]["date"] = Utils.parse_date( set["values"]["date"], "An invalid date format was found in a front-matter default set: #{set}" ) set end # Finds a default value for a given setting, filtered by path and type # # path - the path (relative to the source) of the page, # post or :draft the default is used in # type - a symbol indicating whether a :page, # a :post or a :draft calls this method # # Returns the default value or nil if none was found def find(path, type, setting) value = nil old_scope = nil matching_sets(path, type).each do |set| if set["values"].key?(setting) && has_precedence?(old_scope, set["scope"]) value = set["values"][setting] old_scope = set["scope"] end end value end # Collects a hash with all default values for a page or post # # path - the relative path of the page or post # type - a symbol indicating the type (:post, :page or :draft) # # Returns a hash with all default values (an empty hash if there are none) def all(path, type) defaults = {} old_scope = nil matching_sets(path, type).each do |set| if has_precedence?(old_scope, set["scope"]) defaults = Utils.deep_merge_hashes(defaults, set["values"]) old_scope = set["scope"] else defaults = Utils.deep_merge_hashes(set["values"], defaults) end end defaults end private # Checks if a given default setting scope matches the given path and type # # scope - the hash indicating the scope, as defined in _config.yml # path - the path to check for # type - the type (:post, :page or :draft) to check for # # Returns true if the scope applies to the given path and type def applies?(scope, path, type) applies_path?(scope, path) && applies_type?(scope, type) end # rubocop:disable Metrics/AbcSize def applies_path?(scope, path) return true if !scope.key?("path") || scope["path"].empty? sanitized_path = Pathname.new(sanitize_path(path)) site_path = Pathname.new(@site.source) rel_scope_path = Pathname.new(scope["path"]) abs_scope_path = File.join(@site.source, rel_scope_path) if scope["path"].to_s.include?("*") Dir.glob(abs_scope_path).each do |scope_path| scope_path = Pathname.new(scope_path).relative_path_from(site_path) scope_path = strip_collections_dir(scope_path) Jekyll.logger.debug "Globbed Scope Path:", scope_path return true if path_is_subpath?(sanitized_path, scope_path) end false else path_is_subpath?(sanitized_path, strip_collections_dir(rel_scope_path)) end end # rubocop:enable Metrics/AbcSize def path_is_subpath?(path, parent_path) path.ascend do |ascended_path| if ascended_path.to_s == parent_path.to_s return true end end false end def strip_collections_dir(path) collections_dir = @site.config["collections_dir"] slashed_coll_dir = "#{collections_dir}/" return path if collections_dir.empty? || !path.to_s.start_with?(slashed_coll_dir) path.sub(slashed_coll_dir, "") end # Determines whether the scope applies to type. # The scope applies to the type if: # 1. no 'type' is specified # 2. the 'type' in the scope is the same as the type asked about # # scope - the Hash defaults set being asked about application # type - the type of the document being processed / asked about # its defaults. # # Returns true if either of the above conditions are satisfied, # otherwise returns false def applies_type?(scope, type) !scope.key?("type") || scope["type"].eql?(type.to_s) end # Checks if a given set of default values is valid # # set - the default value hash, as defined in _config.yml # # Returns true if the set is valid and can be used in this class def valid?(set) set.is_a?(Hash) && set["values"].is_a?(Hash) end # Determines if a new scope has precedence over an old one # # old_scope - the old scope hash, or nil if there's none # new_scope - the new scope hash # # Returns true if the new scope has precedence over the older # rubocop: disable PredicateName def has_precedence?(old_scope, new_scope) return true if old_scope.nil? new_path = sanitize_path(new_scope["path"]) old_path = sanitize_path(old_scope["path"]) if new_path.length != old_path.length new_path.length >= old_path.length elsif new_scope.key?("type") true else !old_scope.key? "type" end end # rubocop: enable PredicateName # Collects a list of sets that match the given path and type # # Returns an array of hashes def matching_sets(path, type) valid_sets.select do |set| !set.key?("scope") || applies?(set["scope"], path, type) end end # Returns a list of valid sets # # This is not cached to allow plugins to modify the configuration # and have their changes take effect # # Returns an array of hashes def valid_sets sets = @site.config["defaults"] return [] unless sets.is_a?(Array) sets.map do |set| if valid?(set) ensure_time!(update_deprecated_types(set)) else Jekyll.logger.warn "Defaults:", "An invalid front-matter default set was found:" Jekyll.logger.warn set.to_s nil end end.compact end # Sanitizes the given path by removing a leading and adding a trailing slash SANITIZATION_REGEX = %r!\A/|(?<=[^/])\z! def sanitize_path(path) if path.nil? || path.empty? "" else path.gsub(SANITIZATION_REGEX, "") 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/deprecator.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/deprecator.rb
# frozen_string_literal: true module Jekyll module Deprecator extend self def process(args) arg_is_present? args, "--server", "The --server command has been replaced by the \ 'serve' subcommand." arg_is_present? args, "--serve", "The --serve command has been replaced by the \ 'serve' subcommand." arg_is_present? args, "--no-server", "To build Jekyll without launching a server, \ use the 'build' subcommand." arg_is_present? args, "--auto", "The switch '--auto' has been replaced with \ '--watch'." arg_is_present? args, "--no-auto", "To disable auto-replication, simply leave off \ the '--watch' switch." arg_is_present? args, "--pygments", "The 'pygments'settings has been removed in \ favour of 'highlighter'." arg_is_present? args, "--paginate", "The 'paginate' setting can only be set in \ your config files." arg_is_present? args, "--url", "The 'url' setting can only be set in your \ config files." no_subcommand(args) end def no_subcommand(args) unless args.empty? || args.first !~ %r(!/^--/!) || %w(--help --version).include?(args.first) deprecation_message "Jekyll now uses subcommands instead of just switches. \ Run `jekyll help` to find out more." abort end end def arg_is_present?(args, deprecated_argument, message) if args.include?(deprecated_argument) deprecation_message(message) end end def deprecation_message(message) Jekyll.logger.warn "Deprecation:", message end def defaults_deprecate_type(old, current) Jekyll.logger.warn "Defaults:", "The '#{old}' type has become '#{current}'." Jekyll.logger.warn "Defaults:", "Please update your front-matter defaults to use \ 'type: #{current}'." 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/excerpt.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/excerpt.rb
# frozen_string_literal: true module Jekyll class Excerpt extend Forwardable attr_accessor :doc attr_accessor :content, :ext attr_writer :output def_delegators :@doc, :site, :name, :ext, :extname, :collection, :related_posts, :coffeescript_file?, :yaml_file?, :url, :next_doc, :previous_doc private :coffeescript_file?, :yaml_file? # Initialize this Excerpt instance. # # doc - The Document. # # Returns the new Excerpt. def initialize(doc) self.doc = doc self.content = extract_excerpt(doc.content) end # Fetch YAML front-matter data from related doc, without layout key # # Returns Hash of doc data def data @data ||= doc.data.dup @data.delete("layout") @data.delete("excerpt") @data end def trigger_hooks(*); end # 'Path' of the excerpt. # # Returns the path for the doc this excerpt belongs to with #excerpt appended def path File.join(doc.path, "#excerpt") end # 'Relative Path' of the excerpt. # # Returns the relative_path for the doc this excerpt belongs to with #excerpt appended def relative_path File.join(doc.relative_path, "#excerpt") end # Check if excerpt includes a string # # Returns true if the string passed in def include?(something) (output && output.include?(something)) || content.include?(something) end # The UID for this doc (useful in feeds). # e.g. /2008/11/05/my-awesome-doc # # Returns the String UID. def id "#{doc.id}#excerpt" end def to_s output || content end def to_liquid Jekyll::Drops::ExcerptDrop.new(self) end # Returns the shorthand String identifier of this doc. def inspect "<Excerpt: #{self.id}>" end def output @output ||= Renderer.new(doc.site, self, site.site_payload).run end def place_in_layout? false end def render_with_liquid? !(coffeescript_file? || yaml_file? || !Utils.has_liquid_construct?(content)) end protected # Internal: Extract excerpt from the content # # By default excerpt is your first paragraph of a doc: everything before # the first two new lines: # # --- # title: Example # --- # # First paragraph with [link][1]. # # Second paragraph. # # [1]: http://example.com/ # # This is fairly good option for Markdown and Textile files. But might cause # problems for HTML docs (which is quite unusual for Jekyll). If default # excerpt delimiter is not good for you, you might want to set your own via # configuration option `excerpt_separator`. For example, following is a good # alternative for HTML docs: # # # file: _config.yml # excerpt_separator: "<!-- more -->" # # Notice that all markdown-style link references will be appended to the # excerpt. So the example doc above will have this excerpt source: # # First paragraph with [link][1]. # # [1]: http://example.com/ # # Excerpts are rendered same time as content is rendered. # # Returns excerpt String LIQUID_TAG_REGEX = %r!{%-?\s*(\w+).+\s*-?%}!m MKDWN_LINK_REF_REGEX = %r!^ {0,3}\[[^\]]+\]:.+$! def extract_excerpt(doc_content) head, _, tail = doc_content.to_s.partition(doc.excerpt_separator) # append appropriate closing tag (to a Liquid block), to the "head" if the # partitioning resulted in leaving the closing tag somewhere in the "tail" # partition. if head.include?("{%") head =~ LIQUID_TAG_REGEX tag_name = Regexp.last_match(1) if liquid_block?(tag_name) && head.match(%r!{%-?\s*end#{tag_name}\s*-?%}!).nil? print_build_warning head << "\n{% end#{tag_name} %}" end end if tail.empty? head else head.to_s.dup << "\n\n" << tail.scan(MKDWN_LINK_REF_REGEX).join("\n") end end private def liquid_block?(tag_name) Liquid::Template.tags[tag_name].superclass == Liquid::Block rescue NoMethodError Jekyll.logger.error "Error:", "A Liquid tag in the excerpt of #{doc.relative_path} couldn't be " \ "parsed." raise end def print_build_warning Jekyll.logger.warn "Warning:", "Excerpt modified in #{doc.relative_path}!" Jekyll.logger.warn "", "Found a Liquid block containing separator '#{doc.excerpt_separator}' and has " \ "been modified with the appropriate closing tag." Jekyll.logger.warn "", "Feel free to define a custom excerpt or excerpt_separator in the document's " \ "Front Matter if the generated excerpt is unsatisfactory." 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/log_adapter.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/log_adapter.rb
# frozen_string_literal: true module Jekyll class LogAdapter attr_reader :writer, :messages, :level LOG_LEVELS = { :debug => ::Logger::DEBUG, :info => ::Logger::INFO, :warn => ::Logger::WARN, :error => ::Logger::ERROR, }.freeze # Public: Create a new instance of a log writer # # writer - Logger compatible instance # log_level - (optional, symbol) the log level # # Returns nothing def initialize(writer, level = :info) @messages = [] @writer = writer self.log_level = level end # Public: Set the log level on the writer # # level - (symbol) the log level # # Returns nothing def log_level=(level) writer.level = LOG_LEVELS.fetch(level) @level = level end def adjust_verbosity(options = {}) # Quiet always wins. if options[:quiet] self.log_level = :error elsif options[:verbose] self.log_level = :debug end debug "Logging at level:", LOG_LEVELS.key(writer.level).to_s end # Public: Print a debug message # # topic - the topic of the message, e.g. "Configuration file", "Deprecation", etc. # message - the message detail # # Returns nothing def debug(topic, message = nil, &block) write(:debug, topic, message, &block) end # Public: Print a message # # topic - the topic of the message, e.g. "Configuration file", "Deprecation", etc. # message - the message detail # # Returns nothing def info(topic, message = nil, &block) write(:info, topic, message, &block) end # Public: Print a message # # topic - the topic of the message, e.g. "Configuration file", "Deprecation", etc. # message - the message detail # # Returns nothing def warn(topic, message = nil, &block) write(:warn, topic, message, &block) end # Public: Print an error message # # topic - the topic of the message, e.g. "Configuration file", "Deprecation", etc. # message - the message detail # # Returns nothing def error(topic, message = nil, &block) write(:error, topic, message, &block) end # Public: Print an error message and immediately abort the process # # topic - the topic of the message, e.g. "Configuration file", "Deprecation", etc. # message - the message detail (can be omitted) # # Returns nothing def abort_with(topic, message = nil, &block) error(topic, message, &block) abort end # Internal: Build a topic method # # topic - the topic of the message, e.g. "Configuration file", "Deprecation", etc. # message - the message detail # # Returns the formatted message def message(topic, message = nil) raise ArgumentError, "block or message, not both" if block_given? && message message = yield if block_given? message = message.to_s.gsub(%r!\s+!, " ") topic = formatted_topic(topic, block_given?) out = topic + message messages << out out end # Internal: Format the topic # # topic - the topic of the message, e.g. "Configuration file", "Deprecation", etc. # colon - # # Returns the formatted topic statement def formatted_topic(topic, colon = false) "#{topic}#{colon ? ": " : " "}".rjust(20) end # Internal: Check if the message should be written given the log level. # # level_of_message - the Symbol level of message, one of :debug, :info, :warn, :error # # Returns whether the message should be written. def write_message?(level_of_message) LOG_LEVELS.fetch(level) <= LOG_LEVELS.fetch(level_of_message) end # Internal: Log a message. # # level_of_message - the Symbol level of message, one of :debug, :info, :warn, :error # topic - the String topic or full message # message - the String message (optional) # block - a block containing the message (optional) # # Returns false if the message was not written, otherwise returns the value of calling # the appropriate writer method, e.g. writer.info. def write(level_of_message, topic, message = nil, &block) return false unless write_message?(level_of_message) writer.public_send(level_of_message, message(topic, message, &block)) 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/layout.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/layout.rb
# frozen_string_literal: true module Jekyll class Layout include Convertible # Gets the Site object. attr_reader :site # Gets the name of this layout. attr_reader :name # Gets the path to this layout. attr_reader :path # Gets the path to this layout relative to its base attr_reader :relative_path # Gets/Sets the extension of this layout. attr_accessor :ext # Gets/Sets the Hash that holds the metadata for this layout. attr_accessor :data # Gets/Sets the content of this layout. attr_accessor :content # Initialize a new Layout. # # site - The Site. # base - The String path to the source. # name - The String filename of the post file. def initialize(site, base, name) @site = site @base = base @name = name if site.theme && site.theme.layouts_path.eql?(base) @base_dir = site.theme.root @path = site.in_theme_dir(base, name) else @base_dir = site.source @path = site.in_source_dir(base, name) end @relative_path = @path.sub(@base_dir, "") self.data = {} process(name) read_yaml(base, name) end # Extract information from the layout filename. # # name - The String filename of the layout file. # # Returns nothing. def process(name) self.ext = File.extname(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/jekyll-3.8.4/lib/jekyll/document.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/document.rb
# frozen_string_literal: true module Jekyll class Document include Comparable extend Forwardable attr_reader :path, :site, :extname, :collection attr_accessor :content, :output def_delegator :self, :read_post_data, :post_read YAML_FRONT_MATTER_REGEXP = %r!\A(---\s*\n.*?\n?)^((---|\.\.\.)\s*$\n?)!m DATELESS_FILENAME_MATCHER = %r!^(?:.+/)*(.*)(\.[^.]+)$! DATE_FILENAME_MATCHER = %r!^(?:.+/)*(\d{2,4}-\d{1,2}-\d{1,2})-(.*)(\.[^.]+)$! # Create a new Document. # # path - the path to the file # relations - a hash with keys :site and :collection, the values of which # are the Jekyll::Site and Jekyll::Collection to which this # Document belong. # # Returns nothing. def initialize(path, relations = {}) @site = relations[:site] @path = path @extname = File.extname(path) @collection = relations[:collection] @has_yaml_header = nil if draft? categories_from_path("_drafts") else categories_from_path(collection.relative_directory) end data.default_proc = proc do |_, key| site.frontmatter_defaults.find(relative_path, collection.label, key) end trigger_hooks(:post_init) end # Fetch the Document's data. # # Returns a Hash containing the data. An empty hash is returned if # no data was read. def data @data ||= {} end # Merge some data in with this document's data. # # Returns the merged data. def merge_data!(other, source: "YAML front matter") merge_categories!(other) Utils.deep_merge_hashes!(data, other) merge_date!(source) data end def date data["date"] ||= (draft? ? source_file_mtime : site.time) end def source_file_mtime @source_file_mtime ||= File.mtime(path) end # Returns whether the document is a draft. This is only the case if # the document is in the 'posts' collection but in a different # directory than '_posts'. # # Returns whether the document is a draft. def draft? data["draft"] ||= relative_path.index(collection.relative_directory).nil? && collection.label == "posts" end # The path to the document, relative to the collections_dir. # # Returns a String path which represents the relative path from the collections_dir # to this document. def relative_path @relative_path ||= path.sub("#{site.collections_path}/", "") end # The output extension of the document. # # Returns the output extension def output_ext @output_ext ||= Jekyll::Renderer.new(site, self).output_ext end # The base filename of the document, without the file extname. # # Returns the basename without the file extname. def basename_without_ext @basename_without_ext ||= File.basename(path, ".*") end # The base filename of the document. # # Returns the base filename of the document. def basename @basename ||= File.basename(path) end # Produces a "cleaned" relative path. # The "cleaned" relative path is the relative path without the extname # and with the collection's directory removed as well. # This method is useful when building the URL of the document. # # Examples: # When relative_path is "_methods/site/generate.md": # cleaned_relative_path # # => "/site/generate" # # Returns the cleaned relative path of the document. def cleaned_relative_path @cleaned_relative_path ||= relative_path[0..-extname.length - 1].sub(collection.relative_directory, "") end # Determine whether the document is a YAML file. # # Returns true if the extname is either .yml or .yaml, false otherwise. def yaml_file? %w(.yaml .yml).include?(extname) 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?(extname) end # Determine whether the document is a CoffeeScript file. # # Returns true if extname == .coffee, false otherwise. def coffeescript_file? extname == ".coffee" end # Determine whether the file should be rendered with Liquid. # # Returns false if the document is either an asset file or a yaml file, # or if the document doesn't contain any Liquid Tags or Variables, # true otherwise. def render_with_liquid? !(coffeescript_file? || yaml_file? || !Utils.has_liquid_construct?(content)) end # Determine whether the file should be rendered with a layout. # # Returns true if the Front Matter specifies that `layout` is set to `none`. def no_layout? data["layout"] == "none" end # Determine whether the file should be placed into layouts. # # Returns false if the document is set to `layouts: none`, or is either an # asset file or a yaml file. Returns true otherwise. def place_in_layout? !(asset_file? || yaml_file? || no_layout?) end # The URL template where the document would be accessible. # # Returns the URL template for the document. def url_template collection.url_template end # Construct a Hash of key-value pairs which contain a mapping between # a key in the URL template and the corresponding value for this document. # # Returns the Hash of key-value pairs for replacement in the URL. def url_placeholders @url_placeholders ||= Drops::UrlDrop.new(self) end # The permalink for this Document. # Permalink is set via the data Hash. # # Returns the permalink or nil if no permalink was set in the data. def permalink data && data.is_a?(Hash) && data["permalink"] end # The computed URL for the document. See `Jekyll::URL#to_s` for more details. # # Returns the computed URL for the document. def url @url ||= URL.new({ :template => url_template, :placeholders => url_placeholders, :permalink => permalink, }).to_s end def [](key) data[key] end # The full path to the output file. # # base_directory - the base path of the output directory # # Returns the full path to the output file of this document. def destination(base_directory) dest = site.in_dest_dir(base_directory) path = site.in_dest_dir(dest, URL.unescape_path(url)) if url.end_with? "/" path = File.join(path, "index.html") else path << output_ext unless path.end_with? output_ext end path end # Write the generated Document 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") trigger_hooks(:post_write) end # Whether the file is published or not, as indicated in YAML front-matter # # Returns 'false' if the 'published' key is specified in the # YAML front-matter and is 'false'. Otherwise returns 'true'. def published? !(data.key?("published") && data["published"] == false) end # Read in the file and assign the content and data based on the file contents. # Merge the frontmatter of the file with the frontmatter default # values # # Returns nothing. def read(opts = {}) Jekyll.logger.debug "Reading:", relative_path if yaml_file? @data = SafeYAML.load_file(path) else begin merge_defaults read_content(opts) read_post_data rescue StandardError => e handle_read_error(e) end end end # Create a Liquid-understandable version of this Document. # # Returns a Hash representing this Document's data. def to_liquid @to_liquid ||= Drops::DocumentDrop.new(self) end # The inspect string for this document. # Includes the relative path and the collection label. # # Returns the inspect string for this document. def inspect "#<Jekyll::Document #{relative_path} collection=#{collection.label}>" end # The string representation for this document. # # Returns the content of the document def to_s output || content || "NO CONTENT" end # Compare this document against another document. # Comparison is a comparison between the 2 paths of the documents. # # Returns -1, 0, +1 or nil depending on whether this doc's path is less than, # equal or greater than the other doc's path. See String#<=> for more details. def <=>(other) return nil unless other.respond_to?(:data) cmp = data["date"] <=> other.data["date"] cmp = path <=> other.path if cmp.nil? || cmp.zero? cmp end # Determine whether this document should be written. # Based on the Collection to which it belongs. # # True if the document has a collection and if that collection's #write? # method returns true, and if the site's Publisher will publish the document. # False otherwise. def write? collection && collection.write? && site.publisher.publish?(self) end # The Document excerpt_separator, from the YAML Front-Matter or site # default excerpt_separator value # # Returns the document excerpt_separator def excerpt_separator (data["excerpt_separator"] || site.config["excerpt_separator"]).to_s end # Whether to generate an excerpt # # Returns true if the excerpt separator is configured. def generate_excerpt? !excerpt_separator.empty? end def next_doc pos = collection.docs.index { |post| post.equal?(self) } if pos && pos < collection.docs.length - 1 collection.docs[pos + 1] end end def previous_doc pos = collection.docs.index { |post| post.equal?(self) } if pos && pos > 0 collection.docs[pos - 1] end end def trigger_hooks(hook_name, *args) Jekyll::Hooks.trigger collection.label.to_sym, hook_name, self, *args if collection Jekyll::Hooks.trigger :documents, hook_name, self, *args end def id @id ||= File.join(File.dirname(url), (data["slug"] || basename_without_ext).to_s) end # Calculate related posts. # # Returns an Array of related Posts. def related_posts @related_posts ||= Jekyll::RelatedPosts.new(self).build end # Override of normal respond_to? to match method_missing's logic for # looking in @data. def respond_to?(method, include_private = false) data.key?(method.to_s) || super end # Override of method_missing to check in @data for the key. def method_missing(method, *args, &blck) if data.key?(method.to_s) Jekyll::Deprecator.deprecation_message "Document##{method} is now a key "\ "in the #data hash." Jekyll::Deprecator.deprecation_message "Called by #{caller(0..0)}." data[method.to_s] else super end end def respond_to_missing?(method, *) data.key?(method.to_s) || super end # Add superdirectories of the special_dir to categories. # In the case of es/_posts, 'es' is added as a category. # In the case of _posts/es, 'es' is NOT added as a category. # # Returns nothing. def categories_from_path(special_dir) superdirs = relative_path.sub(%r!#{special_dir}(.*)!, "") .split(File::SEPARATOR) .reject do |c| c.empty? || c == special_dir || c == basename end merge_data!({ "categories" => superdirs }, :source => "file path") end def populate_categories merge_data!({ "categories" => ( Array(data["categories"]) + Utils.pluralized_array_from_hash( data, "category", "categories" ) ).map(&:to_s).flatten.uniq, }) end def populate_tags merge_data!({ "tags" => Utils.pluralized_array_from_hash(data, "tag", "tags").flatten, }) end private def merge_categories!(other) if other.key?("categories") && !other["categories"].nil? if other["categories"].is_a?(String) other["categories"] = other["categories"].split end other["categories"] = (data["categories"] || []) | other["categories"] end end private def merge_date!(source) if data.key?("date") data["date"] = Utils.parse_date( data["date"].to_s, "Document '#{relative_path}' does not have a valid date in the #{source}." ) end end private def merge_defaults defaults = @site.frontmatter_defaults.all( relative_path, collection.label.to_sym ) merge_data!(defaults, :source => "front matter defaults") unless defaults.empty? end private def read_content(opts) self.content = File.read(path, Utils.merged_file_read_opts(site, opts)) if content =~ YAML_FRONT_MATTER_REGEXP self.content = $POSTMATCH data_file = SafeYAML.load(Regexp.last_match(1)) merge_data!(data_file, :source => "YAML front matter") if data_file end end private def read_post_data populate_title populate_categories populate_tags generate_excerpt end private def handle_read_error(error) if error.is_a? Psych::SyntaxError Jekyll.logger.error "Error:", "YAML Exception reading #{path}: #{error.message}" else Jekyll.logger.error "Error:", "could not read file #{path}: #{error.message}" end if site.config["strict_front_matter"] || error.is_a?(Jekyll::Errors::FatalException) raise error end end private def populate_title if relative_path =~ DATE_FILENAME_MATCHER date, slug, ext = Regexp.last_match.captures modify_date(date) elsif relative_path =~ DATELESS_FILENAME_MATCHER slug, ext = Regexp.last_match.captures end # Try to ensure the user gets a title. data["title"] ||= Utils.titleize_slug(slug) # Only overwrite slug & ext if they aren't specified. data["slug"] ||= slug data["ext"] ||= ext end private def modify_date(date) if !data["date"] || data["date"].to_i == site.time.to_i merge_data!({ "date" => date }, :source => "filename") end end private def generate_excerpt if generate_excerpt? data["excerpt"] ||= Jekyll::Excerpt.new(self) 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/site.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/site.rb
# frozen_string_literal: true module Jekyll class Site attr_reader :source, :dest, :config attr_accessor :layouts, :pages, :static_files, :drafts, :exclude, :include, :lsi, :highlighter, :permalink_style, :time, :future, :unpublished, :safe, :plugins, :limit_posts, :show_drafts, :keep_files, :baseurl, :data, :file_read_opts, :gems, :plugin_manager, :theme attr_accessor :converters, :generators, :reader attr_reader :regenerator, :liquid_renderer, :includes_load_paths # Public: Initialize a new Site. # # config - A Hash containing site configuration details. def initialize(config) # Source and destination may not be changed after the site has been created. @source = File.expand_path(config["source"]).freeze @dest = File.expand_path(config["destination"]).freeze self.config = config @reader = Reader.new(self) @regenerator = Regenerator.new(self) @liquid_renderer = LiquidRenderer.new(self) Jekyll.sites << self reset setup Jekyll::Hooks.trigger :site, :after_init, self end # Public: Set the site's configuration. This handles side-effects caused by # changing values in the configuration. # # config - a Jekyll::Configuration, containing the new configuration. # # Returns the new configuration. def config=(config) @config = config.clone %w(safe lsi highlighter baseurl exclude include future unpublished show_drafts limit_posts keep_files).each do |opt| self.send("#{opt}=", config[opt]) end # keep using `gems` to avoid breaking change self.gems = config["plugins"] configure_plugins configure_theme configure_include_paths configure_file_read_opts self.permalink_style = config["permalink"].to_sym @config end # Public: Read, process, and write this Site to output. # # Returns nothing. def process reset read generate render cleanup write print_stats if config["profile"] end def print_stats Jekyll.logger.info @liquid_renderer.stats_table end # Reset Site details. # # Returns nothing def reset self.time = if config["time"] Utils.parse_date(config["time"].to_s, "Invalid time in _config.yml.") else Time.now end self.layouts = {} self.pages = [] self.static_files = [] self.data = {} @site_data = nil @collections = nil @docs_to_write = nil @regenerator.clear_cache @liquid_renderer.reset @site_cleaner = nil if limit_posts < 0 raise ArgumentError, "limit_posts must be a non-negative number" end Jekyll::Hooks.trigger :site, :after_reset, self end # Load necessary libraries, plugins, converters, and generators. # # Returns nothing. def setup ensure_not_in_dest plugin_manager.conscientious_require self.converters = instantiate_subclasses(Jekyll::Converter) self.generators = instantiate_subclasses(Jekyll::Generator) end # Check that the destination dir isn't the source dir or a directory # parent to the source dir. def ensure_not_in_dest dest_pathname = Pathname.new(dest) Pathname.new(source).ascend do |path| if path == dest_pathname raise Errors::FatalException, "Destination directory cannot be or contain the Source directory." end end end # The list of collections and their corresponding Jekyll::Collection instances. # If config['collections'] is set, a new instance is created # for each item in the collection, a new hash is returned otherwise. # # Returns a Hash containing collection name-to-instance pairs. def collections @collections ||= Hash[collection_names.map do |coll| [coll, Jekyll::Collection.new(self, coll)] end] end # The list of collection names. # # Returns an array of collection names from the configuration, # or an empty array if the `collections` key is not set. def collection_names case config["collections"] when Hash config["collections"].keys when Array config["collections"] when nil [] else raise ArgumentError, "Your `collections` key must be a hash or an array." end end # Read Site data from disk and load it into internal data structures. # # Returns nothing. def read reader.read limit_posts! Jekyll::Hooks.trigger :site, :post_read, self end # Run each of the Generators. # # Returns nothing. def generate generators.each do |generator| start = Time.now generator.generate(self) Jekyll.logger.debug "Generating:", "#{generator.class} finished in #{Time.now - start} seconds." end end # Render the site to the destination. # # Returns nothing. def render relative_permalinks_are_deprecated payload = site_payload Jekyll::Hooks.trigger :site, :pre_render, self, payload render_docs(payload) render_pages(payload) Jekyll::Hooks.trigger :site, :post_render, self, payload end # Remove orphaned files and empty directories in destination. # # Returns nothing. def cleanup site_cleaner.cleanup! end # Write static files, pages, and posts. # # Returns nothing. def write each_site_file do |item| item.write(dest) if regenerator.regenerate?(item) end regenerator.write_metadata Jekyll::Hooks.trigger :site, :post_write, self end def posts collections["posts"] ||= Collection.new(self, "posts") end # Construct a Hash of Posts indexed by the specified Post attribute. # # post_attr - The String name of the Post attribute. # # Examples # # post_attr_hash('categories') # # => { 'tech' => [<Post A>, <Post B>], # # 'ruby' => [<Post B>] } # # Returns the Hash: { attr => posts } where # attr - One of the values for the requested attribute. # posts - The Array of Posts with the given attr value. def post_attr_hash(post_attr) # Build a hash map based on the specified post attribute ( post attr => # array of posts ) then sort each array in reverse order. hash = Hash.new { |h, key| h[key] = [] } posts.docs.each do |p| p.data[post_attr].each { |t| hash[t] << p } if p.data[post_attr] end hash.each_value { |posts| posts.sort!.reverse! } hash end def tags post_attr_hash("tags") end def categories post_attr_hash("categories") end # Prepare site data for site payload. The method maintains backward compatibility # if the key 'data' is already used in _config.yml. # # Returns the Hash to be hooked to site.data. def site_data @site_data ||= (config["data"] || data) end # The Hash payload containing site-wide data. # # Returns the Hash: { "site" => data } where data is a Hash with keys: # "time" - The Time as specified in the configuration or the # current time if none was specified. # "posts" - The Array of Posts, sorted chronologically by post date # and then title. # "pages" - The Array of all Pages. # "html_pages" - The Array of HTML Pages. # "categories" - The Hash of category values and Posts. # See Site#post_attr_hash for type info. # "tags" - The Hash of tag values and Posts. # See Site#post_attr_hash for type info. def site_payload Drops::UnifiedPayloadDrop.new self end alias_method :to_liquid, :site_payload # Get the implementation class for the given Converter. # Returns the Converter instance implementing the given Converter. # klass - The Class of the Converter to fetch. def find_converter_instance(klass) @find_converter_instance ||= {} @find_converter_instance[klass] ||= begin converters.find { |converter| converter.instance_of?(klass) } || \ raise("No Converters found for #{klass}") end end # klass - class or module containing the subclasses. # Returns array of instances of subclasses of parameter. # Create array of instances of the subclasses of the class or module # passed in as argument. def instantiate_subclasses(klass) klass.descendants.select { |c| !safe || c.safe }.sort.map do |c| c.new(config) end end # Warns the user if permanent links are relative to the parent # directory. As this is a deprecated function of Jekyll. # # Returns def relative_permalinks_are_deprecated if config["relative_permalinks"] Jekyll.logger.abort_with "Since v3.0, permalinks for pages" \ " in subfolders must be relative to the" \ " site source directory, not the parent" \ " directory. Check https://jekyllrb.com/docs/upgrading/"\ " for more info." end end # Get the to be written documents # # Returns an Array of Documents which should be written def docs_to_write @docs_to_write ||= documents.select(&:write?) end # Get all the documents # # Returns an Array of all Documents def documents collections.reduce(Set.new) do |docs, (_, collection)| docs + collection.docs + collection.files end.to_a end def each_site_file %w(pages static_files docs_to_write).each do |type| send(type).each do |item| yield item end end end # Returns the FrontmatterDefaults or creates a new FrontmatterDefaults # if it doesn't already exist. # # Returns The FrontmatterDefaults def frontmatter_defaults @frontmatter_defaults ||= FrontmatterDefaults.new(self) end # Whether to perform a full rebuild without incremental regeneration # # Returns a Boolean: true for a full rebuild, false for normal build def incremental?(override = {}) override["incremental"] || config["incremental"] end # Returns the publisher or creates a new publisher if it doesn't # already exist. # # Returns The Publisher def publisher @publisher ||= Publisher.new(self) end # Public: Prefix a given path with the source directory. # # paths - (optional) path elements to a file or directory within the # source directory # # Returns a path which is prefixed with the source directory. def in_source_dir(*paths) paths.reduce(source) do |base, path| Jekyll.sanitized_path(base, path) end end # Public: Prefix a given path with the theme directory. # # paths - (optional) path elements to a file or directory within the # theme directory # # Returns a path which is prefixed with the theme root directory. def in_theme_dir(*paths) return nil unless theme paths.reduce(theme.root) do |base, path| Jekyll.sanitized_path(base, path) end end # Public: Prefix a given path with the destination directory. # # paths - (optional) path elements to a file or directory within the # destination directory # # Returns a path which is prefixed with the destination directory. def in_dest_dir(*paths) paths.reduce(dest) do |base, path| Jekyll.sanitized_path(base, path) end end # Public: The full path to the directory that houses all the collections registered # with the current site. # # Returns the source directory or the absolute path to the custom collections_dir def collections_path dir_str = config["collections_dir"] @collections_path ||= dir_str.empty? ? source : in_source_dir(dir_str) end # Limits the current posts; removes the posts which exceed the limit_posts # # Returns nothing private def limit_posts! if limit_posts > 0 limit = posts.docs.length < limit_posts ? posts.docs.length : limit_posts self.posts.docs = posts.docs[-limit, limit] end end # Returns the Cleaner or creates a new Cleaner if it doesn't # already exist. # # Returns The Cleaner private def site_cleaner @site_cleaner ||= Cleaner.new(self) end private def configure_plugins self.plugin_manager = Jekyll::PluginManager.new(self) self.plugins = plugin_manager.plugins_path end private def configure_theme self.theme = nil return if config["theme"].nil? self.theme = if config["theme"].is_a?(String) Jekyll::Theme.new(config["theme"]) else Jekyll.logger.warn "Theme:", "value of 'theme' in config should be " \ "String to use gem-based themes, but got #{config["theme"].class}" nil end end private def configure_include_paths @includes_load_paths = Array(in_source_dir(config["includes_dir"].to_s)) @includes_load_paths << theme.includes_path if theme && theme.includes_path end private def configure_file_read_opts self.file_read_opts = {} self.file_read_opts[:encoding] = config["encoding"] if config["encoding"] self.file_read_opts = Jekyll::Utils.merged_file_read_opts(self, {}) end private def render_docs(payload) collections.each_value do |collection| collection.docs.each do |document| render_regenerated(document, payload) end end end private def render_pages(payload) pages.flatten.each do |page| render_regenerated(page, payload) end end private def render_regenerated(document, payload) return unless regenerator.regenerate?(document) document.output = Jekyll::Renderer.new(self, document, payload).run document.trigger_hooks(:post_render) 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/converters/identity.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/converters/identity.rb
# frozen_string_literal: true module Jekyll module Converters class Identity < Converter safe true priority :lowest def matches(_ext) true end def output_ext(ext) ext end def convert(content) content 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/converters/markdown.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/converters/markdown.rb
# frozen_string_literal: true module Jekyll module Converters class Markdown < Converter highlighter_prefix "\n" highlighter_suffix "\n" safe true def setup return if @setup ||= false unless (@parser = get_processor) Jekyll.logger.error "Invalid Markdown processor given:", @config["markdown"] if @config["safe"] Jekyll.logger.info "", "Custom processors are not loaded in safe mode" end Jekyll.logger.error( "", "Available processors are: #{valid_processors.join(", ")}" ) raise Errors::FatalException, "Bailing out; invalid Markdown processor." end @setup = true end # Rubocop does not allow reader methods to have names starting with `get_` # To ensure compatibility, this check has been disabled on this method # # rubocop:disable Naming/AccessorMethodName def get_processor case @config["markdown"].downcase when "redcarpet" then return RedcarpetParser.new(@config) when "kramdown" then return KramdownParser.new(@config) when "rdiscount" then return RDiscountParser.new(@config) else custom_processor end end # rubocop:enable Naming/AccessorMethodName # Public: Provides you with a list of processors, the ones we # support internally and the ones that you have provided to us (if you # are not in safe mode.) def valid_processors %w(rdiscount kramdown redcarpet) + third_party_processors end # Public: A list of processors that you provide via plugins. # This is really only available if you are not in safe mode, if you are # in safe mode (re: GitHub) then there will be none. def third_party_processors self.class.constants - \ %w(KramdownParser RDiscountParser RedcarpetParser PRIORITIES).map( &:to_sym ) end def extname_list @extname_list ||= @config["markdown_ext"].split(",").map do |e| ".#{e.downcase}" end end def matches(ext) extname_list.include?(ext.downcase) end def output_ext(_ext) ".html" end def convert(content) setup @parser.convert(content) end private def custom_processor converter_name = @config["markdown"] if custom_class_allowed?(converter_name) self.class.const_get(converter_name).new(@config) end end # Private: Determine whether a class name is an allowed custom # markdown class name. # # parser_name - the name of the parser class # # Returns true if the parser name contains only alphanumeric # characters and is defined within Jekyll::Converters::Markdown private def custom_class_allowed?(parser_name) parser_name !~ %r![^A-Za-z0-9_]! && self.class.constants.include?( parser_name.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/jekyll-3.8.4/lib/jekyll/converters/smartypants.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/converters/smartypants.rb
# frozen_string_literal: true class Kramdown::Parser::SmartyPants < Kramdown::Parser::Kramdown def initialize(source, options) super @block_parsers = [:block_html, :content] @span_parsers = [:smart_quotes, :html_entity, :typographic_syms, :span_html] end def parse_content add_text @src.scan(%r!\A.*\n!) end define_parser(:content, %r!\A!) end module Jekyll module Converters class SmartyPants < Converter safe true priority :low def initialize(config) unless defined?(Kramdown) Jekyll::External.require_with_graceful_fail "kramdown" end @config = config["kramdown"].dup || {} @config[:input] = :SmartyPants end def matches(_) false end def output_ext(_) nil end def convert(content) document = Kramdown::Document.new(content, @config) html_output = document.to_html.chomp if @config["show_warnings"] document.warnings.each do |warning| Jekyll.logger.warn "Kramdown warning:", warning.sub(%r!^Warning:\s+!, "") end end html_output 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/converters/markdown/redcarpet_parser.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/converters/markdown/redcarpet_parser.rb
# frozen_string_literal: true class Jekyll::Converters::Markdown::RedcarpetParser module CommonMethods def add_code_tags(code, lang) code = code.to_s code = code.sub( %r!<pre>!, "<pre><code class=\"language-#{lang}\" data-lang=\"#{lang}\">" ) code = code.sub(%r!</pre>!, "</code></pre>") code end end module WithPygments include CommonMethods def block_code(code, lang) unless defined?(Pygments) Jekyll::External.require_with_graceful_fail("pygments") end lang = lang && lang.split.first || "text" add_code_tags( Pygments.highlight( code, { :lexer => lang, :options => { :encoding => "utf-8" }, } ), lang ) end end module WithoutHighlighting require "cgi" include CommonMethods def code_wrap(code) "<figure class=\"highlight\"><pre>#{CGI.escapeHTML(code)}</pre></figure>" end def block_code(code, lang) lang = lang && lang.split.first || "text" add_code_tags(code_wrap(code), lang) end end module WithRouge def block_code(_code, lang) code = "<pre>#{super}</pre>" "<div class=\"highlight\">#{add_code_tags(code, lang)}</div>" end protected def rouge_formatter(_lexer) Jekyll::Utils::Rouge.html_formatter(:wrap => false) end end def initialize(config) unless defined?(Redcarpet) Jekyll::External.require_with_graceful_fail("redcarpet") end @config = config @redcarpet_extensions = {} @config["redcarpet"]["extensions"].each do |e| @redcarpet_extensions[e.to_sym] = true end @renderer ||= class_with_proper_highlighter(@config["highlighter"]) end def class_with_proper_highlighter(highlighter) Class.new(Redcarpet::Render::HTML) do case highlighter when "pygments" include WithPygments when "rouge" Jekyll::External.require_with_graceful_fail(%w( rouge rouge/plugins/redcarpet )) unless Gem::Version.new(Rouge.version) > Gem::Version.new("1.3.0") abort "Please install Rouge 1.3.0 or greater and try running Jekyll again." end include Rouge::Plugins::Redcarpet include CommonMethods include WithRouge else include WithoutHighlighting end end end def convert(content) @redcarpet_extensions[:fenced_code_blocks] = \ !@redcarpet_extensions[:no_fenced_code_blocks] if @redcarpet_extensions[:smart] @renderer.send :include, Redcarpet::Render::SmartyPants end markdown = Redcarpet::Markdown.new( @renderer.new(@redcarpet_extensions), @redcarpet_extensions ) markdown.render(content) 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/converters/markdown/kramdown_parser.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/converters/markdown/kramdown_parser.rb
# Frozen-string-literal: true module Jekyll module Converters class Markdown class KramdownParser CODERAY_DEFAULTS = { "css" => "style", "bold_every" => 10, "line_numbers" => "inline", "line_number_start" => 1, "tab_width" => 4, "wrap" => "div", }.freeze def initialize(config) @main_fallback_highlighter = config["highlighter"] || "rouge" @config = config["kramdown"] || {} @highlighter = nil setup end # Setup and normalize the configuration: # * Create Kramdown if it doesn't exist. # * Set syntax_highlighter, detecting enable_coderay and merging # highlighter if none. # * Merge kramdown[coderay] into syntax_highlighter_opts stripping coderay_. # * Make sure `syntax_highlighter_opts` exists. def setup @config["syntax_highlighter"] ||= highlighter @config["syntax_highlighter_opts"] ||= {} @config["coderay"] ||= {} # XXX: Legacy. modernize_coderay_config make_accessible end def convert(content) document = Kramdown::Document.new(content, @config) html_output = document.to_html if @config["show_warnings"] document.warnings.each do |warning| Jekyll.logger.warn "Kramdown warning:", warning end end html_output end private def make_accessible(hash = @config) hash.keys.each do |key| hash[key.to_sym] = hash[key] make_accessible(hash[key]) if hash[key].is_a?(Hash) end end # config[kramdown][syntax_higlighter] > # config[kramdown][enable_coderay] > # config[highlighter] # Where `enable_coderay` is now deprecated because Kramdown # supports Rouge now too. private def highlighter return @highlighter if @highlighter if @config["syntax_highlighter"] return @highlighter = @config[ "syntax_highlighter" ] end @highlighter = begin if @config.key?("enable_coderay") && @config["enable_coderay"] Jekyll::Deprecator.deprecation_message( "You are using 'enable_coderay', " \ "use syntax_highlighter: coderay in your configuration file." ) "coderay" else @main_fallback_highlighter end end end private def strip_coderay_prefix(hash) hash.each_with_object({}) do |(key, val), hsh| cleaned_key = key.to_s.gsub(%r!\Acoderay_!, "") if key != cleaned_key Jekyll::Deprecator.deprecation_message( "You are using '#{key}'. Normalizing to #{cleaned_key}." ) end hsh[cleaned_key] = val end end # If our highlighter is CodeRay we go in to merge the CodeRay defaults # with your "coderay" key if it's there, deprecating it in the # process of you using it. private def modernize_coderay_config unless @config["coderay"].empty? Jekyll::Deprecator.deprecation_message( "You are using 'kramdown.coderay' in your configuration, " \ "please use 'syntax_highlighter_opts' instead." ) @config["syntax_highlighter_opts"] = begin strip_coderay_prefix( @config["syntax_highlighter_opts"] \ .merge(CODERAY_DEFAULTS) \ .merge(@config["coderay"]) ) end 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/converters/markdown/rdiscount_parser.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/converters/markdown/rdiscount_parser.rb
# frozen_string_literal: true module Jekyll module Converters class Markdown class RDiscountParser def initialize(config) unless defined?(RDiscount) Jekyll::External.require_with_graceful_fail "rdiscount" end @config = config @rdiscount_extensions = @config["rdiscount"]["extensions"].map(&:to_sym) end def convert(content) rd = RDiscount.new(content, *@rdiscount_extensions) html = rd.to_html if @config["rdiscount"]["toc_token"] html = replace_generated_toc(rd, html, @config["rdiscount"]["toc_token"]) end html end private def replace_generated_toc(rd_instance, html, toc_token) if rd_instance.generate_toc && html.include?(toc_token) utf8_toc = rd_instance.toc_content utf8_toc.force_encoding("utf-8") if utf8_toc.respond_to?(:force_encoding) html.gsub(toc_token, utf8_toc) else html 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/table.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/liquid_renderer/table.rb
# frozen_string_literal: true module Jekyll class LiquidRenderer::Table def initialize(stats) @stats = stats end def to_s(num_of_rows = 50) data = data_for_table(num_of_rows) widths = table_widths(data) generate_table(data, widths) end private def generate_table(data, widths) str = String.new("\n") table_head = data.shift str << generate_row(table_head, widths) str << generate_table_head_border(table_head, widths) data.each do |row_data| str << generate_row(row_data, widths) end str << "\n" str end def generate_table_head_border(row_data, widths) str = String.new("") row_data.each_index do |cell_index| str << "-" * widths[cell_index] str << "-+-" unless cell_index == row_data.length - 1 end str << "\n" str end def generate_row(row_data, widths) str = String.new("") row_data.each_with_index do |cell_data, cell_index| str << if cell_index.zero? cell_data.ljust(widths[cell_index], " ") else cell_data.rjust(widths[cell_index], " ") end str << " | " unless cell_index == row_data.length - 1 end str << "\n" str end def table_widths(data) widths = [] data.each do |row| row.each_with_index do |cell, index| widths[index] = [cell.length, widths[index]].compact.max end end widths end def data_for_table(num_of_rows) sorted = @stats.sort_by { |_, file_stats| -file_stats[:time] } sorted = sorted.slice(0, num_of_rows) table = [%w(Filename Count Bytes Time)] sorted.each do |filename, file_stats| row = [] row << filename row << file_stats[:count].to_s row << format_bytes(file_stats[:bytes]) row << format("%.3f", file_stats[:time]) table << row end table end def format_bytes(bytes) bytes /= 1024.0 format("%.2fK", bytes) 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/file.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/liquid_renderer/file.rb
# frozen_string_literal: true module Jekyll class LiquidRenderer class File def initialize(renderer, filename) @renderer = renderer @filename = filename end def parse(content) measure_time do @template = Liquid::Template.parse(content, :line_numbers => true) end self end def render(*args) measure_time do measure_bytes do @template.render(*args) end end end def render!(*args) measure_time do measure_bytes do @template.render!(*args) end end end def warnings @template.warnings end private def measure_bytes yield.tap do |str| @renderer.increment_bytes(@filename, str.bytesize) end end def measure_time before = Time.now yield ensure after = Time.now @renderer.increment_time(@filename, after - before) 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/commands/serve.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/commands/serve.rb
# frozen_string_literal: true require "thread" module Jekyll module Commands class Serve < Command # Similar to the pattern in Utils::ThreadEvent except we are maintaining the # state of @running instead of just signaling an event. We have to maintain this # state since Serve is just called via class methods instead of an instance # being created each time. @mutex = Mutex.new @run_cond = ConditionVariable.new @running = false class << self COMMAND_OPTIONS = { "ssl_cert" => ["--ssl-cert [CERT]", "X.509 (SSL) certificate."], "host" => ["host", "-H", "--host [HOST]", "Host to bind to"], "open_url" => ["-o", "--open-url", "Launch your site in a browser"], "detach" => ["-B", "--detach", "Run the server in the background",], "ssl_key" => ["--ssl-key [KEY]", "X.509 (SSL) Private Key."], "port" => ["-P", "--port [PORT]", "Port to listen on"], "show_dir_listing" => ["--show-dir-listing", "Show a directory listing instead of loading your index file.",], "skip_initial_build" => ["skip_initial_build", "--skip-initial-build", "Skips the initial site build which occurs before the server is started.",], "livereload" => ["-l", "--livereload", "Use LiveReload to automatically refresh browsers",], "livereload_ignore" => ["--livereload-ignore ignore GLOB1[,GLOB2[,...]]", Array, "Files for LiveReload to ignore. Remember to quote the values so your shell "\ "won't expand them",], "livereload_min_delay" => ["--livereload-min-delay [SECONDS]", "Minimum reload delay",], "livereload_max_delay" => ["--livereload-max-delay [SECONDS]", "Maximum reload delay",], "livereload_port" => ["--livereload-port [PORT]", Integer, "Port for LiveReload to listen on",], }.freeze DIRECTORY_INDEX = %w( index.htm index.html index.rhtml index.cgi index.xml index.json ).freeze LIVERELOAD_PORT = 35_729 LIVERELOAD_DIR = File.join(__dir__, "serve", "livereload_assets") attr_reader :mutex, :run_cond, :running alias_method :running?, :running def init_with_program(prog) prog.command(:serve) do |cmd| cmd.description "Serve your site locally" cmd.syntax "serve [options]" cmd.alias :server cmd.alias :s add_build_options(cmd) COMMAND_OPTIONS.each do |key, val| cmd.option key, *val end cmd.action do |_, opts| opts["livereload_port"] ||= LIVERELOAD_PORT opts["serving"] = true opts["watch"] = true unless opts.key?("watch") start(opts) end end end # def start(opts) # Set the reactor to nil so any old reactor will be GCed. # We can't unregister a hook so in testing when Serve.start is # called multiple times we don't want to inadvertently keep using # a reactor created by a previous test when our test might not @reload_reactor = nil config = configuration_from_options(opts) if Jekyll.env == "development" config["url"] = default_url(config) end [Build, Serve].each { |klass| klass.process(config) } end # def process(opts) opts = configuration_from_options(opts) destination = opts["destination"] register_reload_hooks(opts) if opts["livereload"] setup(destination) start_up_webrick(opts, destination) end def shutdown @server.shutdown if running? end # Perform logical validation of CLI options private def validate_options(opts) if opts["livereload"] if opts["detach"] Jekyll.logger.warn "Warning:", "--detach and --livereload are mutually exclusive. Choosing --livereload" opts["detach"] = false end if opts["ssl_cert"] || opts["ssl_key"] # This is not technically true. LiveReload works fine over SSL, but # EventMachine's SSL support in Windows requires building the gem's # native extensions against OpenSSL and that proved to be a process # so tedious that expecting users to do it is a non-starter. Jekyll.logger.abort_with "Error:", "LiveReload does not support SSL" end unless opts["watch"] # Using livereload logically implies you want to watch the files opts["watch"] = true end elsif %w(livereload_min_delay livereload_max_delay livereload_ignore livereload_port).any? { |o| opts[o] } Jekyll.logger.abort_with "--livereload-min-delay, "\ "--livereload-max-delay, --livereload-ignore, and "\ "--livereload-port require the --livereload option." end end # private # rubocop:disable Metrics/AbcSize def register_reload_hooks(opts) require_relative "serve/live_reload_reactor" @reload_reactor = LiveReloadReactor.new Jekyll::Hooks.register(:site, :post_render) do |site| regenerator = Jekyll::Regenerator.new(site) @changed_pages = site.pages.select do |p| regenerator.regenerate?(p) end end # A note on ignoring files: LiveReload errs on the side of reloading when it # comes to the message it gets. If, for example, a page is ignored but a CSS # file linked in the page isn't, the page will still be reloaded if the CSS # file is contained in the message sent to LiveReload. Additionally, the # path matching is very loose so that a message to reload "/" will always # lead the page to reload since every page starts with "/". Jekyll::Hooks.register(:site, :post_write) do if @changed_pages && @reload_reactor && @reload_reactor.running? ignore, @changed_pages = @changed_pages.partition do |p| Array(opts["livereload_ignore"]).any? do |filter| File.fnmatch(filter, Jekyll.sanitized_path(p.relative_path)) end end Jekyll.logger.debug "LiveReload:", "Ignoring #{ignore.map(&:relative_path)}" @reload_reactor.reload(@changed_pages) end @changed_pages = nil end end # rubocop:enable Metrics/AbcSize # Do a base pre-setup of WEBRick so that everything is in place # when we get ready to party, checking for an setting up an error page # and making sure our destination exists. private def setup(destination) require_relative "serve/servlet" FileUtils.mkdir_p(destination) if File.exist?(File.join(destination, "404.html")) WEBrick::HTTPResponse.class_eval do def create_error_page @header["Content-Type"] = "text/html; charset=UTF-8" @body = IO.read(File.join(@config[:DocumentRoot], "404.html")) end end end end # private def webrick_opts(opts) opts = { :JekyllOptions => opts, :DoNotReverseLookup => true, :MimeTypes => mime_types, :DocumentRoot => opts["destination"], :StartCallback => start_callback(opts["detach"]), :StopCallback => stop_callback(opts["detach"]), :BindAddress => opts["host"], :Port => opts["port"], :DirectoryIndex => DIRECTORY_INDEX, } opts[:DirectoryIndex] = [] if opts[:JekyllOptions]["show_dir_listing"] enable_ssl(opts) enable_logging(opts) opts end # private def start_up_webrick(opts, destination) if opts["livereload"] @reload_reactor.start(opts) end @server = WEBrick::HTTPServer.new(webrick_opts(opts)).tap { |o| o.unmount("") } @server.mount(opts["baseurl"].to_s, Servlet, destination, file_handler_opts) Jekyll.logger.info "Server address:", server_address(@server, opts) launch_browser @server, opts if opts["open_url"] boot_or_detach @server, opts end # Recreate NondisclosureName under utf-8 circumstance private def file_handler_opts WEBrick::Config::FileHandler.merge({ :FancyIndexing => true, :NondisclosureName => [ ".ht*", "~*", ], }) end # private def server_address(server, options = {}) format_url( server.config[:SSLEnable], server.config[:BindAddress], server.config[:Port], options["baseurl"] ) end private def format_url(ssl_enabled, address, port, baseurl = nil) format("%<prefix>s://%<address>s:%<port>i%<baseurl>s", { :prefix => ssl_enabled ? "https" : "http", :address => address, :port => port, :baseurl => baseurl ? "#{baseurl}/" : "", }) end # private def default_url(opts) config = configuration_from_options(opts) format_url( config["ssl_cert"] && config["ssl_key"], config["host"] == "127.0.0.1" ? "localhost" : config["host"], config["port"] ) end # private def launch_browser(server, opts) address = server_address(server, opts) return system "start", address if Utils::Platforms.windows? return system "xdg-open", address if Utils::Platforms.linux? return system "open", address if Utils::Platforms.osx? Jekyll.logger.error "Refusing to launch browser; " \ "Platform launcher unknown." end # Keep in our area with a thread or detach the server as requested # by the user. This method determines what we do based on what you # ask us to do. private def boot_or_detach(server, opts) if opts["detach"] pid = Process.fork do server.start end Process.detach(pid) Jekyll.logger.info "Server detached with pid '#{pid}'.", \ "Run `pkill -f jekyll' or `kill -9 #{pid}' to stop the server." else t = Thread.new { server.start } trap("INT") { server.shutdown } t.join end end # Make the stack verbose if the user requests it. private def enable_logging(opts) opts[:AccessLog] = [] level = WEBrick::Log.const_get(opts[:JekyllOptions]["verbose"] ? :DEBUG : :WARN) opts[:Logger] = WEBrick::Log.new($stdout, level) end # Add SSL to the stack if the user triggers --enable-ssl and they # provide both types of certificates commonly needed. Raise if they # forget to add one of the certificates. private def enable_ssl(opts) cert, key, src = opts[:JekyllOptions].values_at("ssl_cert", "ssl_key", "source") return if cert.nil? && key.nil? raise "Missing --ssl_cert or --ssl_key. Both are required." unless cert && key require "openssl" require "webrick/https" opts[:SSLCertificate] = OpenSSL::X509::Certificate.new(read_file(src, cert)) opts[:SSLPrivateKey] = OpenSSL::PKey::RSA.new(read_file(src, key)) opts[:SSLEnable] = true end private def start_callback(detached) unless detached proc do mutex.synchronize do # Block until EventMachine reactor starts @reload_reactor.started_event.wait unless @reload_reactor.nil? @running = true Jekyll.logger.info("Server running...", "press ctrl-c to stop.") @run_cond.broadcast end end end end private def stop_callback(detached) unless detached proc do mutex.synchronize do unless @reload_reactor.nil? @reload_reactor.stop @reload_reactor.stopped_event.wait end @running = false @run_cond.broadcast end end end end private def mime_types file = File.expand_path("../mime.types", __dir__) WEBrick::HTTPUtils.load_mime_types(file) end private def read_file(source_dir, file_path) File.read(Jekyll.sanitized_path(source_dir, file_path)) 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/commands/clean.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/commands/clean.rb
# frozen_string_literal: true module Jekyll module Commands class Clean < Command class << self def init_with_program(prog) prog.command(:clean) do |c| c.syntax "clean [subcommand]" c.description "Clean the site " \ "(removes site output and metadata file) without building." add_build_options(c) c.action do |_, options| Jekyll::Commands::Clean.process(options) end end end def process(options) options = configuration_from_options(options) destination = options["destination"] metadata_file = File.join(options["source"], ".jekyll-metadata") sass_cache = ".sass-cache" remove(destination, :checker_func => :directory?) remove(metadata_file, :checker_func => :file?) remove(sass_cache, :checker_func => :directory?) end def remove(filename, checker_func: :file?) if File.public_send(checker_func, filename) Jekyll.logger.info "Cleaner:", "Removing #{filename}..." FileUtils.rm_rf(filename) else Jekyll.logger.info "Cleaner:", "Nothing to do for #{filename}." 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/commands/doctor.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/commands/doctor.rb
# frozen_string_literal: true module Jekyll module Commands class Doctor < Command class << self def init_with_program(prog) prog.command(:doctor) do |c| c.syntax "doctor" c.description "Search site and print specific deprecation warnings" c.alias(:hyde) c.option "config", "--config CONFIG_FILE[,CONFIG_FILE2,...]", Array, "Custom configuration file" c.action do |_, options| Jekyll::Commands::Doctor.process(options) end end end def process(options) site = Jekyll::Site.new(configuration_from_options(options)) site.reset site.read site.generate if healthy?(site) Jekyll.logger.info "Your test results", "are in. Everything looks fine." else abort end end def healthy?(site) [ fsnotify_buggy?(site), !deprecated_relative_permalinks(site), !conflicting_urls(site), !urls_only_differ_by_case(site), proper_site_url?(site), properly_gathered_posts?(site), ].all? end def properly_gathered_posts?(site) return true if site.config["collections_dir"].empty? posts_at_root = site.in_source_dir("_posts") return true unless File.directory?(posts_at_root) Jekyll.logger.warn "Warning:", "Detected '_posts' directory outside custom `collections_dir`!" Jekyll.logger.warn "", "Please move '#{posts_at_root}' into the custom directory at " \ "'#{site.in_source_dir(site.config["collections_dir"])}'" false end def deprecated_relative_permalinks(site) if site.config["relative_permalinks"] Jekyll::Deprecator.deprecation_message "Your site still uses relative" \ " permalinks, which was removed in" \ " Jekyll v3.0.0." return true end end def conflicting_urls(site) conflicting_urls = false urls = {} urls = collect_urls(urls, site.pages, site.dest) urls = collect_urls(urls, site.posts.docs, site.dest) urls.each do |url, paths| next unless paths.size > 1 conflicting_urls = true Jekyll.logger.warn "Conflict:", "The URL '#{url}' is the destination" \ " for the following pages: #{paths.join(", ")}" end conflicting_urls end def fsnotify_buggy?(_site) return true unless Utils::Platforms.osx? if Dir.pwd != `pwd`.strip Jekyll.logger.error " " + <<-STR.strip.gsub(%r!\n\s+!, "\n ") We have detected that there might be trouble using fsevent on your operating system, you can read https://github.com/thibaudgg/rb-fsevent/wiki/no-fsevents-fired-(OSX-bug) for possible work arounds or you can work around it immediately with `--force-polling`. STR false end true end def urls_only_differ_by_case(site) urls_only_differ_by_case = false urls = case_insensitive_urls(site.pages + site.docs_to_write, site.dest) urls.each_value do |real_urls| next unless real_urls.uniq.size > 1 urls_only_differ_by_case = true Jekyll.logger.warn "Warning:", "The following URLs only differ" \ " by case. On a case-insensitive file system one of the URLs" \ " will be overwritten by the other: #{real_urls.join(", ")}" end urls_only_differ_by_case end def proper_site_url?(site) url = site.config["url"] [ url_exists?(url), url_valid?(url), url_absolute(url), ].all? end private def collect_urls(urls, things, destination) things.each do |thing| dest = thing.destination(destination) if urls[dest] urls[dest] << thing.path else urls[dest] = [thing.path] end end urls end def case_insensitive_urls(things, destination) things.each_with_object({}) do |thing, memo| dest = thing.destination(destination) (memo[dest.downcase] ||= []) << dest end end def url_exists?(url) return true unless url.nil? || url.empty? Jekyll.logger.warn "Warning:", "You didn't set an URL in the config file, "\ "you may encounter problems with some plugins." false end def url_valid?(url) Addressable::URI.parse(url) true # Addressable::URI#parse only raises a TypeError # https://git.io/vFfbx rescue TypeError Jekyll.logger.warn "Warning:", "The site URL does not seem to be valid, "\ "check the value of `url` in your config file." false end def url_absolute(url) return true if Addressable::URI.parse(url).absolute? Jekyll.logger.warn "Warning:", "Your site URL does not seem to be absolute, "\ "check the value of `url` in your config file." false 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/commands/build.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/commands/build.rb
# frozen_string_literal: true module Jekyll module Commands class Build < Command class << self # Create the Mercenary command for the Jekyll CLI for this Command def init_with_program(prog) prog.command(:build) do |c| c.syntax "build [options]" c.description "Build your site" c.alias :b add_build_options(c) c.action do |_, options| options["serving"] = false Jekyll::Commands::Build.process(options) end end end # Build your jekyll site # Continuously watch if `watch` is set to true in the config. def process(options) # Adjust verbosity quickly Jekyll.logger.adjust_verbosity(options) options = configuration_from_options(options) site = Jekyll::Site.new(options) if options.fetch("skip_initial_build", false) Jekyll.logger.warn "Build Warning:", "Skipping the initial build." \ " This may result in an out-of-date site." else build(site, options) end if options.fetch("detach", false) Jekyll.logger.info "Auto-regeneration:", "disabled when running server detached." elsif options.fetch("watch", false) watch(site, options) else Jekyll.logger.info "Auto-regeneration:", "disabled. Use --watch to enable." end end # Build your Jekyll site. # # site - the Jekyll::Site instance to build # options - A Hash of options passed to the command # # Returns nothing. def build(site, options) t = Time.now source = options["source"] destination = options["destination"] incremental = options["incremental"] Jekyll.logger.info "Source:", source Jekyll.logger.info "Destination:", destination Jekyll.logger.info "Incremental build:", (incremental ? "enabled" : "disabled. Enable with --incremental") Jekyll.logger.info "Generating..." process_site(site) Jekyll.logger.info "", "done in #{(Time.now - t).round(3)} seconds." end # Private: Watch for file changes and rebuild the site. # # site - A Jekyll::Site instance # options - A Hash of options passed to the command # # Returns nothing. def watch(site, options) # Warn Windows users that they might need to upgrade. if Utils::Platforms.bash_on_windows? Jekyll.logger.warn "", "Auto-regeneration may not work on some Windows versions." Jekyll.logger.warn "", "Please see: https://github.com/Microsoft/BashOnWindows/issues/216" Jekyll.logger.warn "", "If it does not work, please upgrade Bash on Windows or "\ "run Jekyll with --no-watch." end External.require_with_graceful_fail "jekyll-watch" watch_method = Jekyll::Watcher.method(:watch) if watch_method.parameters.size == 1 watch_method.call( options ) else watch_method.call( options, site ) 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/commands/new.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/commands/new.rb
# frozen_string_literal: true require "erb" module Jekyll module Commands class New < Command class << self def init_with_program(prog) prog.command(:new) do |c| c.syntax "new PATH" c.description "Creates a new Jekyll site scaffold in PATH" c.option "force", "--force", "Force creation even if PATH already exists" c.option "blank", "--blank", "Creates scaffolding but with empty files" c.option "skip-bundle", "--skip-bundle", "Skip 'bundle install'" c.action do |args, options| Jekyll::Commands::New.process(args, options) end end end def process(args, options = {}) raise ArgumentError, "You must specify a path." if args.empty? new_blog_path = File.expand_path(args.join(" "), Dir.pwd) FileUtils.mkdir_p new_blog_path if preserve_source_location?(new_blog_path, options) Jekyll.logger.error "Conflict:", "#{new_blog_path} exists and is not empty." Jekyll.logger.abort_with "", "Ensure #{new_blog_path} is empty or else " \ "try again with `--force` to proceed and overwrite any files." end if options["blank"] create_blank_site new_blog_path else create_site new_blog_path end after_install(new_blog_path, options) end def create_blank_site(path) Dir.chdir(path) do FileUtils.mkdir(%w(_layouts _posts _drafts)) FileUtils.touch("index.html") end end def scaffold_post_content ERB.new(File.read(File.expand_path(scaffold_path, site_template))).result end # Internal: Gets the filename of the sample post to be created # # Returns the filename of the sample post, as a String def initialized_post_name "_posts/#{Time.now.strftime("%Y-%m-%d")}-welcome-to-jekyll.markdown" end private def gemfile_contents <<-RUBY source "https://rubygems.org" # Hello! This is where you manage which Jekyll version is used to run. # When you want to use a different version, change it below, save the # file and run `bundle install`. Run Jekyll with `bundle exec`, like so: # # bundle exec jekyll serve # # This will help ensure the proper Jekyll version is running. # Happy Jekylling! gem "jekyll", "~> #{Jekyll::VERSION}" # This is the default theme for new Jekyll sites. You may change this to anything you like. gem "minima", "~> 2.0" # If you want to use GitHub Pages, remove the "gem "jekyll"" above and # uncomment the line below. To upgrade, run `bundle update github-pages`. # gem "github-pages", group: :jekyll_plugins # If you have any plugins, put them here! group :jekyll_plugins do gem "jekyll-feed", "~> 0.6" end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem "tzinfo-data", platforms: [:mingw, :mswin, :x64_mingw, :jruby] # Performance-booster for watching directories on Windows gem "wdm", "~> 0.1.0" if Gem.win_platform? RUBY end def create_site(new_blog_path) create_sample_files new_blog_path File.open(File.expand_path(initialized_post_name, new_blog_path), "w") do |f| f.write(scaffold_post_content) end File.open(File.expand_path("Gemfile", new_blog_path), "w") do |f| f.write(gemfile_contents) end end def preserve_source_location?(path, options) !options["force"] && !Dir["#{path}/**/*"].empty? end def create_sample_files(path) FileUtils.cp_r site_template + "/.", path FileUtils.chmod_R "u+w", path FileUtils.rm File.expand_path(scaffold_path, path) end def site_template File.expand_path("../../site_template", __dir__) end def scaffold_path "_posts/0000-00-00-welcome-to-jekyll.markdown.erb" end # After a new blog has been created, print a success notification and # then automatically execute bundle install from within the new blog dir # unless the user opts to generate a blank blog or skip 'bundle install'. def after_install(path, options = {}) unless options["blank"] || options["skip-bundle"] begin require "bundler" bundle_install path rescue LoadError Jekyll.logger.info "Could not load Bundler. Bundle install skipped." end end Jekyll.logger.info "New jekyll site installed in #{path.cyan}." Jekyll.logger.info "Bundle install skipped." if options["skip-bundle"] end def bundle_install(path) Jekyll.logger.info "Running bundle install in #{path.cyan}..." Dir.chdir(path) do exe = Gem.bin_path("bundler", "bundle") process, output = Jekyll::Utils::Exec.run("ruby", exe, "install") output.to_s.each_line do |line| Jekyll.logger.info("Bundler:".green, line.strip) unless line.to_s.empty? end raise SystemExit unless process.success? 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/commands/help.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/commands/help.rb
# frozen_string_literal: true module Jekyll module Commands class Help < Command class << self def init_with_program(prog) prog.command(:help) do |c| c.syntax "help [subcommand]" c.description "Show the help message, optionally for a given subcommand." c.action do |args, _| cmd = (args.first || "").to_sym if args.empty? Jekyll.logger.info prog.to_s elsif prog.has_command? cmd Jekyll.logger.info prog.commands[cmd].to_s else invalid_command(prog, cmd) abort end end end end def invalid_command(prog, cmd) Jekyll.logger.error "Error:", "Hmm... we don't know what the '#{cmd}' command is." Jekyll.logger.info "Valid commands:", prog.commands.keys.join(", ") 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/commands/new_theme.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/commands/new_theme.rb
# frozen_string_literal: true require "erb" class Jekyll::Commands::NewTheme < Jekyll::Command class << self def init_with_program(prog) prog.command(:"new-theme") do |c| c.syntax "new-theme NAME" c.description "Creates a new Jekyll theme scaffold" c.option "code_of_conduct", \ "-c", "--code-of-conduct", \ "Include a Code of Conduct. (defaults to false)" c.action do |args, opts| Jekyll::Commands::NewTheme.process(args, opts) end end end # rubocop:disable Metrics/AbcSize def process(args, opts) if !args || args.empty? raise Jekyll::Errors::InvalidThemeName, "You must specify a theme name." end new_theme_name = args.join("_") theme = Jekyll::ThemeBuilder.new(new_theme_name, opts) if theme.path.exist? Jekyll.logger.abort_with "Conflict:", "#{theme.path} already exists." end theme.create! Jekyll.logger.info "Your new Jekyll theme, #{theme.name.cyan}," \ " is ready for you in #{theme.path.to_s.cyan}!" Jekyll.logger.info "For help getting started, read #{theme.path}/README.md." end # rubocop:enable Metrics/AbcSize 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/commands/serve/websockets.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/commands/serve/websockets.rb
# frozen_string_literal: true require "http/parser" module Jekyll module Commands class Serve # The LiveReload protocol requires the server to serve livereload.js over HTTP # despite the fact that the protocol itself uses WebSockets. This custom connection # class addresses the dual protocols that the server needs to understand. class HttpAwareConnection < EventMachine::WebSocket::Connection attr_reader :reload_body, :reload_size def initialize(_opts) # If EventMachine SSL support on Windows ever gets better, the code below will # set up the reactor to handle SSL # # @ssl_enabled = opts["ssl_cert"] && opts["ssl_key"] # if @ssl_enabled # em_opts[:tls_options] = { # :private_key_file => Jekyll.sanitized_path(opts["source"], opts["ssl_key"]), # :cert_chain_file => Jekyll.sanitized_path(opts["source"], opts["ssl_cert"]) # } # em_opts[:secure] = true # end # This is too noisy even for --verbose, but uncomment if you need it for # a specific WebSockets issue. Adding ?LR-verbose=true onto the URL will # enable logging on the client side. # em_opts[:debug] = true em_opts = {} super(em_opts) reload_file = File.join(Serve.singleton_class::LIVERELOAD_DIR, "livereload.js") @reload_body = File.read(reload_file) @reload_size = @reload_body.bytesize end # rubocop:disable Metrics/MethodLength def dispatch(data) parser = Http::Parser.new parser << data # WebSockets requests will have a Connection: Upgrade header if parser.http_method != "GET" || parser.upgrade? super elsif parser.request_url =~ %r!^\/livereload.js! headers = [ "HTTP/1.1 200 OK", "Content-Type: application/javascript", "Content-Length: #{reload_size}", "", "", ].join("\r\n") send_data(headers) # stream_file_data would free us from keeping livereload.js in memory # but JRuby blocks on that call and never returns send_data(reload_body) close_connection_after_writing else body = "This port only serves livereload.js over HTTP.\n" headers = [ "HTTP/1.1 400 Bad Request", "Content-Type: text/plain", "Content-Length: #{body.bytesize}", "", "", ].join("\r\n") send_data(headers) send_data(body) close_connection_after_writing end end # rubocop:enable Metrics/MethodLength 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/commands/serve/live_reload_reactor.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/commands/serve/live_reload_reactor.rb
# frozen_string_literal: true require "em-websocket" require_relative "websockets" module Jekyll module Commands class Serve class LiveReloadReactor attr_reader :started_event attr_reader :stopped_event attr_reader :thread def initialize @websockets = [] @connections_count = 0 @started_event = Utils::ThreadEvent.new @stopped_event = Utils::ThreadEvent.new end def stop # There is only one EventMachine instance per Ruby process so stopping # it here will stop the reactor thread we have running. EM.stop if EM.reactor_running? Jekyll.logger.debug "LiveReload Server:", "halted" end def running? EM.reactor_running? end def handle_websockets_event(websocket) websocket.onopen { |handshake| connect(websocket, handshake) } websocket.onclose { disconnect(websocket) } websocket.onmessage { |msg| print_message(msg) } websocket.onerror { |error| log_error(error) } end def start(opts) @thread = Thread.new do # Use epoll if the kernel supports it EM.epoll EM.run do EM.error_handler { |e| log_error(e) } EM.start_server( opts["host"], opts["livereload_port"], HttpAwareConnection, opts ) do |ws| handle_websockets_event(ws) end # Notify blocked threads that EventMachine has started or shutdown EM.schedule { @started_event.set } EM.add_shutdown_hook { @stopped_event.set } Jekyll.logger.info "LiveReload address:", "http://#{opts["host"]}:#{opts["livereload_port"]}" end end @thread.abort_on_exception = true end # For a description of the protocol see # http://feedback.livereload.com/knowledgebase/articles/86174-livereload-protocol def reload(pages) pages.each do |p| json_message = JSON.dump({ :command => "reload", :path => p.url, :liveCSS => true, }) Jekyll.logger.debug "LiveReload:", "Reloading #{p.url}" Jekyll.logger.debug "", json_message @websockets.each { |ws| ws.send(json_message) } end end private def connect(websocket, handshake) @connections_count += 1 if @connections_count == 1 message = "Browser connected" message += " over SSL/TLS" if handshake.secure? Jekyll.logger.info "LiveReload:", message end websocket.send( JSON.dump( :command => "hello", :protocols => ["http://livereload.com/protocols/official-7"], :serverName => "jekyll" ) ) @websockets << websocket end private def disconnect(websocket) @websockets.delete(websocket) end private def print_message(json_message) msg = JSON.parse(json_message) # Not sure what the 'url' command even does in LiveReload. The spec is silent # on its purpose. if msg["command"] == "url" Jekyll.logger.info "LiveReload:", "Browser URL: #{msg["url"]}" end end private def log_error(error) Jekyll.logger.error "LiveReload experienced an error. " \ "Run with --trace for more information." raise error 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/commands/serve/servlet.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/commands/serve/servlet.rb
# frozen_string_literal: true require "webrick" module Jekyll module Commands class Serve # This class is used to determine if the Servlet should modify a served file # to insert the LiveReload script tags class SkipAnalyzer BAD_USER_AGENTS = [%r!MSIE!].freeze def self.skip_processing?(request, response, options) new(request, response, options).skip_processing? end def initialize(request, response, options) @options = options @request = request @response = response end def skip_processing? !html? || chunked? || inline? || bad_browser? end def chunked? @response["Transfer-Encoding"] == "chunked" end def inline? @response["Content-Disposition"] =~ %r!^inline! end def bad_browser? BAD_USER_AGENTS.any? { |pattern| @request["User-Agent"] =~ pattern } end def html? @response["Content-Type"] =~ %r!text/html! end end # This class inserts the LiveReload script tags into HTML as it is served class BodyProcessor HEAD_TAG_REGEX = %r!<head>|<head[^(er)][^<]*>! attr_reader :content_length, :new_body, :livereload_added def initialize(body, options) @body = body @options = options @processed = false end def processed? @processed end # rubocop:disable Metrics/MethodLength def process! @new_body = [] # @body will usually be a File object but Strings occur in rare cases if @body.respond_to?(:each) begin @body.each { |line| @new_body << line.to_s } ensure @body.close end else @new_body = @body.lines end @content_length = 0 @livereload_added = false @new_body.each do |line| if !@livereload_added && line["<head"] line.gsub!(HEAD_TAG_REGEX) do |match| %(#{match}#{template.result(binding)}) end @livereload_added = true end @content_length += line.bytesize @processed = true end @new_body = @new_body.join end # rubocop:enable Metrics/MethodLength def template # Unclear what "snipver" does. Doc at # https://github.com/livereload/livereload-js states that the recommended # setting is 1. # Complicated JavaScript to ensure that livereload.js is loaded from the # same origin as the page. Mostly useful for dealing with the browser's # distinction between 'localhost' and 127.0.0.1 template = <<-TEMPLATE <script> document.write( '<script src="http://' + (location.host || 'localhost').split(':')[0] + ':<%=@options["livereload_port"] %>/livereload.js?snipver=1<%= livereload_args %>"' + '></' + 'script>'); </script> TEMPLATE ERB.new(Jekyll::Utils.strip_heredoc(template)) end def livereload_args # XHTML standard requires ampersands to be encoded as entities when in # attributes. See http://stackoverflow.com/a/2190292 src = "" if @options["livereload_min_delay"] src += "&amp;mindelay=#{@options["livereload_min_delay"]}" end if @options["livereload_max_delay"] src += "&amp;maxdelay=#{@options["livereload_max_delay"]}" end if @options["livereload_port"] src += "&amp;port=#{@options["livereload_port"]}" end src end end class Servlet < WEBrick::HTTPServlet::FileHandler DEFAULTS = { "Cache-Control" => "private, max-age=0, proxy-revalidate, " \ "no-store, no-cache, must-revalidate", }.freeze def initialize(server, root, callbacks) # So we can access them easily. @jekyll_opts = server.config[:JekyllOptions] set_defaults super end def search_index_file(req, res) super || search_file(req, res, ".html") end # Add the ability to tap file.html the same way that Nginx does on our # Docker images (or on GitHub Pages.) The difference is that we might end # up with a different preference on which comes first. def search_file(req, res, basename) # /file.* > /file/index.html > /file.html super || super(req, res, "#{basename}.html") end # rubocop:disable Naming/MethodName def do_GET(req, res) rtn = super if @jekyll_opts["livereload"] return rtn if SkipAnalyzer.skip_processing?(req, res, @jekyll_opts) processor = BodyProcessor.new(res.body, @jekyll_opts) processor.process! res.body = processor.new_body res.content_length = processor.content_length.to_s if processor.livereload_added # Add a header to indicate that the page content has been modified res["X-Rack-LiveReload"] = "1" end end validate_and_ensure_charset(req, res) res.header.merge!(@headers) rtn end # rubocop:enable Naming/MethodName # private def validate_and_ensure_charset(_req, res) key = res.header.keys.grep(%r!content-type!i).first typ = res.header[key] unless typ =~ %r!;\s*charset=! res.header[key] = "#{typ}; charset=#{@jekyll_opts["encoding"]}" end end # private def set_defaults hash_ = @jekyll_opts.fetch("webrick", {}).fetch("headers", {}) DEFAULTS.each_with_object(@headers = hash_) do |(key, val), hash| hash[key] = val unless hash.key?(key) 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/tags/include.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/tags/include.rb
# frozen_string_literal: true module Jekyll module Tags class IncludeTagError < StandardError attr_accessor :path def initialize(msg, path) super(msg) @path = path end end class IncludeTag < Liquid::Tag VALID_SYNTAX = %r! ([\w-]+)\s*=\s* (?:"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'|([\w\.-]+)) !x VARIABLE_SYNTAX = %r! (?<variable>[^{]*(\{\{\s*[\w\-\.]+\s*(\|.*)?\}\}[^\s{}]*)+) (?<params>.*) !mx FULL_VALID_SYNTAX = %r!\A\s*(?:#{VALID_SYNTAX}(?=\s|\z)\s*)*\z! VALID_FILENAME_CHARS = %r!^[\w/\.-]+$! INVALID_SEQUENCES = %r![./]{2,}! def initialize(tag_name, markup, tokens) super matched = markup.strip.match(VARIABLE_SYNTAX) if matched @file = matched["variable"].strip @params = matched["params"].strip else @file, @params = markup.strip.split(%r!\s+!, 2) end validate_params if @params @tag_name = tag_name end def syntax_example "{% #{@tag_name} file.ext param='value' param2='value' %}" end def parse_params(context) params = {} markup = @params while (match = VALID_SYNTAX.match(markup)) markup = markup[match.end(0)..-1] value = if match[2] match[2].gsub(%r!\\"!, '"') elsif match[3] match[3].gsub(%r!\\'!, "'") elsif match[4] context[match[4]] end params[match[1]] = value end params end def validate_file_name(file) if file =~ INVALID_SEQUENCES || file !~ VALID_FILENAME_CHARS raise ArgumentError, <<-MSG Invalid syntax for include tag. File contains invalid characters or sequences: #{file} Valid syntax: #{syntax_example} MSG end end def validate_params unless @params =~ FULL_VALID_SYNTAX raise ArgumentError, <<-MSG Invalid syntax for include tag: #{@params} Valid syntax: #{syntax_example} MSG end end # Grab file read opts in the context def file_read_opts(context) context.registers[:site].file_read_opts end # Render the variable if required def render_variable(context) if @file =~ VARIABLE_SYNTAX partial = context.registers[:site] .liquid_renderer .file("(variable)") .parse(@file) partial.render!(context) end end def tag_includes_dirs(context) context.registers[:site].includes_load_paths.freeze end def locate_include_file(context, file, safe) includes_dirs = tag_includes_dirs(context) includes_dirs.each do |dir| path = File.join(dir.to_s, file.to_s) return path if valid_include_file?(path, dir.to_s, safe) end raise IOError, could_not_locate_message(file, includes_dirs, safe) end def render(context) site = context.registers[:site] file = render_variable(context) || @file validate_file_name(file) path = locate_include_file(context, file, site.safe) return unless path add_include_to_dependency(site, path, context) partial = load_cached_partial(path, context) context.stack do context["include"] = parse_params(context) if @params begin partial.render!(context) rescue Liquid::Error => e e.template_name = path e.markup_context = "included " if e.markup_context.nil? raise e end end end def add_include_to_dependency(site, path, context) if context.registers[:page] && context.registers[:page].key?("path") site.regenerator.add_dependency( site.in_source_dir(context.registers[:page]["path"]), path ) end end def load_cached_partial(path, context) context.registers[:cached_partials] ||= {} cached_partial = context.registers[:cached_partials] if cached_partial.key?(path) cached_partial[path] else unparsed_file = context.registers[:site] .liquid_renderer .file(path) begin cached_partial[path] = unparsed_file.parse(read_file(path, context)) rescue Liquid::Error => e e.template_name = path e.markup_context = "included " if e.markup_context.nil? raise e end end end def valid_include_file?(path, dir, safe) !outside_site_source?(path, dir, safe) && File.file?(path) end def outside_site_source?(path, dir, safe) safe && !realpath_prefixed_with?(path, dir) end def realpath_prefixed_with?(path, dir) File.exist?(path) && File.realpath(path).start_with?(dir) rescue StandardError false end # This method allows to modify the file content by inheriting from the class. def read_file(file, context) File.read(file, file_read_opts(context)) end private def could_not_locate_message(file, includes_dirs, safe) message = "Could not locate the included file '#{file}' in any of "\ "#{includes_dirs}. Ensure it exists in one of those directories and" message + if safe " is not a symlink as those are not allowed in safe mode." else ", if it is a symlink, does not point outside your site source." end end end class IncludeRelativeTag < IncludeTag def tag_includes_dirs(context) Array(page_path(context)).freeze end def page_path(context) if context.registers[:page].nil? context.registers[:site].source else site = context.registers[:site] page_payload = context.registers[:page] resource_path = \ if page_payload["collection"].nil? page_payload["path"] else File.join(site.config["collections_dir"], page_payload["path"]) end site.in_source_dir File.dirname(resource_path) end end end end end Liquid::Template.register_tag("include", Jekyll::Tags::IncludeTag) Liquid::Template.register_tag("include_relative", Jekyll::Tags::IncludeRelativeTag)
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/tags/post_url.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/tags/post_url.rb
# frozen_string_literal: true module Jekyll module Tags class PostComparer MATCHER = %r!^(.+/)*(\d+-\d+-\d+)-(.*)$! attr_reader :path, :date, :slug, :name def initialize(name) @name = name all, @path, @date, @slug = *name.sub(%r!^/!, "").match(MATCHER) unless all raise Jekyll::Errors::InvalidPostNameError, "'#{name}' does not contain valid date and/or title." end escaped_slug = Regexp.escape(slug) @name_regex = %r!^_posts/#{path}#{date}-#{escaped_slug}\.[^.]+| ^#{path}_posts/?#{date}-#{escaped_slug}\.[^.]+!x end def post_date @post_date ||= Utils.parse_date(date, "\"#{date}\" does not contain valid date and/or title.") end def ==(other) other.relative_path.match(@name_regex) end def deprecated_equality(other) slug == post_slug(other) && post_date.year == other.date.year && post_date.month == other.date.month && post_date.day == other.date.day end private # Construct the directory-aware post slug for a Jekyll::Post # # other - the Jekyll::Post # # Returns the post slug with the subdirectory (relative to _posts) def post_slug(other) path = other.basename.split("/")[0...-1].join("/") if path.nil? || path == "" other.data["slug"] else path + "/" + other.data["slug"] end end end class PostUrl < Liquid::Tag def initialize(tag_name, post, tokens) super @orig_post = post.strip begin @post = PostComparer.new(@orig_post) rescue StandardError => e raise Jekyll::Errors::PostURLError, <<-MSG Could not parse name of post "#{@orig_post}" in tag 'post_url'. Make sure the post exists and the name is correct. #{e.class}: #{e.message} MSG end end def render(context) site = context.registers[:site] site.posts.docs.each do |p| return p.url if @post == p end # New matching method did not match, fall back to old method # with deprecation warning if this matches site.posts.docs.each do |p| next unless @post.deprecated_equality p Jekyll::Deprecator.deprecation_message "A call to "\ "'{% post_url #{@post.name} %}' did not match " \ "a post using the new matching method of checking name " \ "(path-date-slug) equality. Please make sure that you " \ "change this tag to match the post's name exactly." return p.url end raise Jekyll::Errors::PostURLError, <<-MSG Could not find post "#{@orig_post}" in tag 'post_url'. Make sure the post exists and the name is correct. MSG end end end end Liquid::Template.register_tag("post_url", Jekyll::Tags::PostUrl)
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/tags/link.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/tags/link.rb
# frozen_string_literal: true module Jekyll module Tags class Link < Liquid::Tag class << self def tag_name self.name.split("::").last.downcase end end def initialize(tag_name, relative_path, tokens) super @relative_path = relative_path.strip end def render(context) site = context.registers[:site] site.each_site_file do |item| return item.url if item.relative_path == @relative_path # This takes care of the case for static files that have a leading / return item.url if item.relative_path == "/#{@relative_path}" end raise ArgumentError, <<-MSG Could not find document '#{@relative_path}' in tag '#{self.class.tag_name}'. Make sure the document exists and the path is correct. MSG end end end end Liquid::Template.register_tag(Jekyll::Tags::Link.tag_name, Jekyll::Tags::Link)
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/tags/highlight.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/tags/highlight.rb
# frozen_string_literal: true module Jekyll module Tags class HighlightBlock < Liquid::Block include Liquid::StandardFilters # The regular expression syntax checker. Start with the language specifier. # Follow that by zero or more space separated options that take one of three # forms: name, name=value, or name="<quoted list>" # # <quoted list> is a space-separated list of numbers SYNTAX = %r!^([a-zA-Z0-9.+#_-]+)((\s+\w+(=(\w+|"([0-9]+\s)*[0-9]+"))?)*)$! def initialize(tag_name, markup, tokens) super if markup.strip =~ SYNTAX @lang = Regexp.last_match(1).downcase @highlight_options = parse_options(Regexp.last_match(2)) else raise SyntaxError, <<-MSG Syntax Error in tag 'highlight' while parsing the following markup: #{markup} Valid syntax: highlight <lang> [linenos] MSG end end def render(context) prefix = context["highlighter_prefix"] || "" suffix = context["highlighter_suffix"] || "" code = super.to_s.gsub(%r!\A(\n|\r)+|(\n|\r)+\z!, "") is_safe = !!context.registers[:site].safe output = case context.registers[:site].highlighter when "pygments" render_pygments(code, is_safe) when "rouge" render_rouge(code) else render_codehighlighter(code) end rendered_output = add_code_tag(output) prefix + rendered_output + suffix end def sanitized_opts(opts, is_safe) if is_safe Hash[[ [:startinline, opts.fetch(:startinline, nil)], [:hl_lines, opts.fetch(:hl_lines, nil)], [:linenos, opts.fetch(:linenos, nil)], [:encoding, opts.fetch(:encoding, "utf-8")], [:cssclass, opts.fetch(:cssclass, nil)], ].reject { |f| f.last.nil? }] else opts end end private OPTIONS_REGEX = %r!(?:\w="[^"]*"|\w=\w|\w)+! def parse_options(input) options = {} return options if input.empty? # Split along 3 possible forms -- key="<quoted list>", key=value, or key input.scan(OPTIONS_REGEX) do |opt| key, value = opt.split("=") # If a quoted list, convert to array if value && value.include?('"') value.delete!('"') value = value.split end options[key.to_sym] = value || true end options[:linenos] = "inline" if options[:linenos] == true options end def render_pygments(code, is_safe) Jekyll::External.require_with_graceful_fail("pygments") unless defined?(Pygments) highlighted_code = Pygments.highlight( code, :lexer => @lang, :options => sanitized_opts(@highlight_options, is_safe) ) if highlighted_code.nil? Jekyll.logger.error <<-MSG There was an error highlighting your code: #{code} While attempting to convert the above code, Pygments.rb returned an unacceptable value. This is usually a timeout problem solved by running `jekyll build` again. MSG raise ArgumentError, "Pygments.rb returned an unacceptable value "\ "when attempting to highlight some code." end highlighted_code.sub('<div class="highlight"><pre>', "").sub("</pre></div>", "") end def render_rouge(code) formatter = Jekyll::Utils::Rouge.html_formatter( :line_numbers => @highlight_options[:linenos], :wrap => false, :css_class => "highlight", :gutter_class => "gutter", :code_class => "code" ) lexer = ::Rouge::Lexer.find_fancy(@lang, code) || Rouge::Lexers::PlainText formatter.format(lexer.lex(code)) end def render_codehighlighter(code) h(code).strip end def add_code_tag(code) code_attributes = [ "class=\"language-#{@lang.to_s.tr("+", "-")}\"", "data-lang=\"#{@lang}\"", ].join(" ") "<figure class=\"highlight\"><pre><code #{code_attributes}>"\ "#{code.chomp}</code></pre></figure>" end end end end Liquid::Template.register_tag("highlight", Jekyll::Tags::HighlightBlock)
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/utils/win_tz.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/utils/win_tz.rb
# frozen_string_literal: true module Jekyll module Utils module WinTZ extend self # Public: Calculate the Timezone for Windows when the config file has a defined # 'timezone' key. # # timezone - the IANA Time Zone specified in "_config.yml" # # Returns a string that ultimately re-defines ENV["TZ"] in Windows def calculate(timezone) External.require_with_graceful_fail("tzinfo") unless defined?(TZInfo) tz = TZInfo::Timezone.get(timezone) difference = Time.now.to_i - tz.now.to_i # # POSIX style definition reverses the offset sign. # e.g. Eastern Standard Time (EST) that is 5Hrs. to the 'west' of Prime Meridian # is denoted as: # EST+5 (or) EST+05:00 # Reference: http://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html sign = difference < 0 ? "-" : "+" offset = sign == "-" ? "+" : "-" unless difference.zero? # # convert the difference (in seconds) to hours, as a rational number, and perform # a modulo operation on it. modulo = modulo_of(rational_hour(difference)) # # Format the hour as a two-digit number. # Establish the minutes based on modulo expression. hh = format("%02d", absolute_hour(difference).ceil) mm = modulo.zero? ? "00" : "30" Jekyll.logger.debug "Timezone:", "#{timezone} #{offset}#{hh}:#{mm}" # # Note: The 3-letter-word below doesn't have a particular significance. "WTZ#{sign}#{hh}:#{mm}" end private # Private: Convert given seconds to an hour as a rational number. # # seconds - supplied as an integer, it is converted to a rational number. # 3600 - no. of seconds in an hour. # # Returns a rational number. def rational_hour(seconds) seconds.to_r / 3600 end # Private: Convert given seconds to an hour as an absolute number. # # seconds - supplied as an integer, it is converted to its absolute. # 3600 - no. of seconds in an hour. # # Returns an integer. def absolute_hour(seconds) seconds.abs / 3600 end # Private: Perform a modulo operation on a given fraction. # # fraction - supplied as a rational number, its numerator is divided # by its denominator and the remainder returned. # # Returns an integer. def modulo_of(fraction) fraction.numerator % fraction.denominator 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/utils/exec.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/utils/exec.rb
# frozen_string_literal: true require "open3" module Jekyll module Utils module Exec extend self # Runs a program in a sub-shell. # # *args - a list of strings containing the program name and arguments # # Returns a Process::Status and a String of output in an array in # that order. def run(*args) stdin, stdout, stderr, process = Open3.popen3(*args) out = stdout.read.strip err = stderr.read.strip [stdin, stdout, stderr].each(&:close) [process.value, out + err] 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/utils/thread_event.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/utils/thread_event.rb
# frozen_string_literal: true require "thread" module Jekyll module Utils # Based on the pattern and code from # https://emptysqua.re/blog/an-event-synchronization-primitive-for-ruby/ class ThreadEvent attr_reader :flag def initialize @lock = Mutex.new @cond = ConditionVariable.new @flag = false end def set @lock.synchronize do yield if block_given? @flag = true @cond.broadcast end end def wait @lock.synchronize do unless @flag @cond.wait(@lock) 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/utils/ansi.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/utils/ansi.rb
# Frozen-string-literal: true module Jekyll module Utils module Ansi extend self ESCAPE = format("%c", 27) MATCH = %r!#{ESCAPE}\[(?:\d+)(?:;\d+)*(j|k|m|s|u|A|B|G)|\e\(B\e\[m!ix COLORS = { :red => 31, :green => 32, :black => 30, :magenta => 35, :yellow => 33, :white => 37, :blue => 34, :cyan => 36, }.freeze # Strip ANSI from the current string. It also strips cursor stuff, # well some of it, and it also strips some other stuff that a lot of # the other ANSI strippers don't. def strip(str) str.gsub MATCH, "" end # def has?(str) !!(str =~ MATCH) end # Reset the color back to the default color so that you do not leak any # colors when you move onto the next line. This is probably normally # used as part of a wrapper so that we don't leak colors. def reset(str = "") @ansi_reset ||= format("%c[0m", 27) "#{@ansi_reset}#{str}" end # SEE: `self::COLORS` for a list of methods. They are mostly # standard base colors supported by pretty much any xterm-color, we do # not need more than the base colors so we do not include them. # Actually... if I'm honest we don't even need most of the # base colors. COLORS.each do |color, num| define_method color do |str| "#{format("%c", 27)}[#{num}m#{str}#{reset}" 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/utils/platforms.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/utils/platforms.rb
# frozen_string_literal: true module Jekyll module Utils module Platforms extend self # Provides jruby? and mri? which respectively detect these two types of # tested Engines we support, in the future we might probably support the # other one that everyone used to talk about. { :jruby? => "jruby", :mri? => "ruby" }.each do |k, v| define_method k do ::RUBY_ENGINE == v end end # -- # Allows you to detect "real" Windows, or what we would consider # "real" Windows. That is, that we can pass the basic test and the # /proc/version returns nothing to us. # -- def vanilla_windows? RbConfig::CONFIG["host_os"] =~ %r!mswin|mingw|cygwin!i && \ !proc_version end # -- # XXX: Remove in 4.0 # -- alias_method :really_windows?, \ :vanilla_windows? # def bash_on_windows? RbConfig::CONFIG["host_os"] =~ %r!linux! && \ proc_version =~ %r!microsoft!i end # def windows? vanilla_windows? || bash_on_windows? end # def linux? RbConfig::CONFIG["host_os"] =~ %r!linux! && \ proc_version !~ %r!microsoft!i end # Provides windows?, linux?, osx?, unix? so that we can detect # platforms. This is mostly useful for `jekyll doctor` and for testing # where we kick off certain tests based on the platform. { :osx? => %r!darwin|mac os!, :unix? => %r!solaris|bsd! }.each do |k, v| define_method k do !!( RbConfig::CONFIG["host_os"] =~ v ) end end # private def proc_version @proc_version ||= begin Pathutil.new( "/proc/version" ).read rescue Errno::ENOENT nil 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/utils/rouge.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/utils/rouge.rb
# frozen_string_literal: true Jekyll::External.require_with_graceful_fail("rouge") module Jekyll module Utils module Rouge def self.html_formatter(*args) if old_api? ::Rouge::Formatters::HTML.new(*args) else ::Rouge::Formatters::HTMLLegacy.new(*args) end end def self.old_api? ::Rouge.version.to_s < "2" 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/utils/internet.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/utils/internet.rb
# frozen_string_literal: true module Jekyll module Utils module Internet # Public: Determine whether the present device has a connection to # the Internet. This allows plugin writers which require the outside # world to have a neat fallback mechanism for offline building. # # Example: # if Internet.connected? # Typhoeus.get("https://pages.github.com/versions.json") # else # Jekyll.logger.warn "Warning:", "Version check has been disabled." # Jekyll.logger.warn "", "Connect to the Internet to enable it." # nil # end # # Returns true if a DNS call can successfully be made, or false if not. module_function def connected? !dns("example.com").nil? end private module_function def dns(domain) require "resolv" Resolv::DNS.open do |resolver| resolver.getaddress(domain) end rescue Resolv::ResolvError, Resolv::ResolvTimeout 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/jekyll-3.8.4/lib/jekyll/drops/static_file_drop.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/drops/static_file_drop.rb
# frozen_string_literal: true module Jekyll module Drops class StaticFileDrop < Drop extend Forwardable def_delegators :@obj, :name, :extname, :modified_time, :basename def_delegator :@obj, :relative_path, :path def_delegator :@obj, :type, :collection private def_delegator :@obj, :data, :fallback_data 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/drops/document_drop.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/drops/document_drop.rb
# frozen_string_literal: true module Jekyll module Drops class DocumentDrop < Drop extend Forwardable NESTED_OBJECT_FIELD_BLACKLIST = %w( content output excerpt next previous ).freeze mutable false def_delegator :@obj, :relative_path, :path def_delegators :@obj, :id, :output, :content, :to_s, :relative_path, :url private def_delegator :@obj, :data, :fallback_data def collection @obj.collection.label end def excerpt fallback_data["excerpt"].to_s end def <=>(other) return nil unless other.is_a? DocumentDrop cmp = self["date"] <=> other["date"] cmp = self["path"] <=> other["path"] if cmp.nil? || cmp.zero? cmp end def previous @obj.previous_doc.to_liquid end def next @obj.next_doc.to_liquid end # Generate a Hash for use in generating JSON. # This is useful if fields need to be cleared before the JSON can generate. # # state - the JSON::State object which determines the state of current processing. # # Returns a Hash ready for JSON generation. def hash_for_json(state = nil) to_h.tap do |hash| if state && state.depth >= 2 hash["previous"] = collapse_document(hash["previous"]) if hash["previous"] hash["next"] = collapse_document(hash["next"]) if hash["next"] end end end # Generate a Hash which breaks the recursive chain. # Certain fields which are normally available are omitted. # # Returns a Hash with only non-recursive fields present. def collapse_document(doc) doc.keys.each_with_object({}) do |(key, _), result| result[key] = doc[key] unless NESTED_OBJECT_FIELD_BLACKLIST.include?(key) 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/drops/excerpt_drop.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/drops/excerpt_drop.rb
# frozen_string_literal: true module Jekyll module Drops class ExcerptDrop < DocumentDrop def layout @obj.doc.data["layout"] end def excerpt 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/jekyll-3.8.4/lib/jekyll/drops/collection_drop.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/drops/collection_drop.rb
# frozen_string_literal: true module Jekyll module Drops class CollectionDrop < Drop extend Forwardable mutable false def_delegator :@obj, :write?, :output def_delegators :@obj, :label, :docs, :files, :directory, :relative_directory private def_delegator :@obj, :metadata, :fallback_data def to_s docs.to_s 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/drops/drop.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/drops/drop.rb
# frozen_string_literal: true module Jekyll module Drops class Drop < Liquid::Drop include Enumerable NON_CONTENT_METHODS = [:fallback_data, :collapse_document].freeze # Get or set whether the drop class is mutable. # Mutability determines whether or not pre-defined fields may be # overwritten. # # is_mutable - Boolean set mutability of the class (default: nil) # # Returns the mutability of the class def self.mutable(is_mutable = nil) @is_mutable = if is_mutable is_mutable else false end end def self.mutable? @is_mutable end # Create a new Drop # # obj - the Jekyll Site, Collection, or Document required by the # drop. # # Returns nothing def initialize(obj) @obj = obj @mutations = {} # only if mutable: true end # Access a method in the Drop or a field in the underlying hash data. # If mutable, checks the mutations first. Then checks the methods, # and finally check the underlying hash (e.g. document front matter) # if all the previous places didn't match. # # key - the string key whose value to fetch # # Returns the value for the given key, or nil if none exists def [](key) if self.class.mutable? && @mutations.key?(key) @mutations[key] elsif self.class.invokable? key public_send key else fallback_data[key] end end alias_method :invoke_drop, :[] # Set a field in the Drop. If mutable, sets in the mutations and # returns. If not mutable, checks first if it's trying to override a # Drop method and raises a DropMutationException if so. If not # mutable and the key is not a method on the Drop, then it sets the # key to the value in the underlying hash (e.g. document front # matter) # # key - the String key whose value to set # val - the Object to set the key's value to # # Returns the value the key was set to unless the Drop is not mutable # and the key matches a method in which case it raises a # DropMutationException. def []=(key, val) if respond_to?("#{key}=") public_send("#{key}=", val) elsif respond_to?(key.to_s) if self.class.mutable? @mutations[key] = val else raise Errors::DropMutationException, "Key #{key} cannot be set in the drop." end else fallback_data[key] = val end end # Generates a list of strings which correspond to content getter # methods. # # Returns an Array of strings which represent method-specific keys. def content_methods @content_methods ||= ( self.class.instance_methods \ - Jekyll::Drops::Drop.instance_methods \ - NON_CONTENT_METHODS ).map(&:to_s).reject do |method| method.end_with?("=") end end # Check if key exists in Drop # # key - the string key whose value to fetch # # Returns true if the given key is present def key?(key) return false if key.nil? return true if self.class.mutable? && @mutations.key?(key) respond_to?(key) || fallback_data.key?(key) end # Generates a list of keys with user content as their values. # This gathers up the Drop methods and keys of the mutations and # underlying data hashes and performs a set union to ensure a list # of unique keys for the Drop. # # Returns an Array of unique keys for content for the Drop. def keys (content_methods | @mutations.keys | fallback_data.keys).flatten end # Generate a Hash representation of the Drop by resolving each key's # value. It includes Drop methods, mutations, and the underlying object's # data. See the documentation for Drop#keys for more. # # Returns a Hash with all the keys and values resolved. def to_h keys.each_with_object({}) do |(key, _), result| result[key] = self[key] end end alias_method :to_hash, :to_h # Inspect the drop's keys and values through a JSON representation # of its keys and values. # # Returns a pretty generation of the hash representation of the Drop. def inspect JSON.pretty_generate to_h end # Generate a Hash for use in generating JSON. # This is useful if fields need to be cleared before the JSON can generate. # # Returns a Hash ready for JSON generation. def hash_for_json(*) to_h end # Generate a JSON representation of the Drop. # # state - the JSON::State object which determines the state of current processing. # # Returns a JSON representation of the Drop in a String. def to_json(state = nil) JSON.generate(hash_for_json(state), state) end # Collects all the keys and passes each to the block in turn. # # block - a block which accepts one argument, the key # # Returns nothing. def each_key(&block) keys.each(&block) end def each each_key.each do |key| yield key, self[key] end end def merge(other, &block) self.dup.tap do |me| if block.nil? me.merge!(other) else me.merge!(other, block) end end end def merge!(other) other.each_key do |key| if block_given? self[key] = yield key, self[key], other[key] else if Utils.mergable?(self[key]) && Utils.mergable?(other[key]) self[key] = Utils.deep_merge_hashes(self[key], other[key]) next end self[key] = other[key] unless other[key].nil? end end end # Imitate Hash.fetch method in Drop # # Returns value if key is present in Drop, otherwise returns default value # KeyError is raised if key is not present and no default value given def fetch(key, default = nil, &block) return self[key] if key?(key) raise KeyError, %(key not found: "#{key}") if default.nil? && block.nil? return yield(key) unless block.nil? return default unless default.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/jekyll-3.8.4/lib/jekyll/drops/unified_payload_drop.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/drops/unified_payload_drop.rb
# frozen_string_literal: true module Jekyll module Drops class UnifiedPayloadDrop < Drop mutable true attr_accessor :page, :layout, :content, :paginator attr_accessor :highlighter_prefix, :highlighter_suffix def jekyll JekyllDrop.global end def site @site_drop ||= SiteDrop.new(@obj) end private def fallback_data @fallback_data ||= {} 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/drops/url_drop.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/drops/url_drop.rb
# frozen_string_literal: true module Jekyll module Drops class UrlDrop < Drop extend Forwardable mutable false def_delegator :@obj, :cleaned_relative_path, :path def_delegator :@obj, :output_ext, :output_ext def collection @obj.collection.label end def name Utils.slugify(@obj.basename_without_ext) end def title Utils.slugify(@obj.data["slug"], :mode => "pretty", :cased => true) || Utils.slugify(@obj.basename_without_ext, :mode => "pretty", :cased => true) end def slug Utils.slugify(@obj.data["slug"]) || Utils.slugify(@obj.basename_without_ext) end def categories category_set = Set.new Array(@obj.data["categories"]).each do |category| category_set << category.to_s.downcase end category_set.to_a.join("/") end def year @obj.date.strftime("%Y") end def month @obj.date.strftime("%m") end def day @obj.date.strftime("%d") end def hour @obj.date.strftime("%H") end def minute @obj.date.strftime("%M") end def second @obj.date.strftime("%S") end def i_day @obj.date.strftime("%-d") end def i_month @obj.date.strftime("%-m") end def short_month @obj.date.strftime("%b") end def short_year @obj.date.strftime("%y") end def y_day @obj.date.strftime("%j") end private def fallback_data {} 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/drops/site_drop.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/drops/site_drop.rb
# frozen_string_literal: true module Jekyll module Drops class SiteDrop < Drop extend Forwardable mutable false def_delegator :@obj, :site_data, :data def_delegators :@obj, :time, :pages, :static_files, :documents, :tags, :categories private def_delegator :@obj, :config, :fallback_data def [](key) if @obj.collections.key?(key) && key != "posts" @obj.collections[key].docs else super(key) end end def key?(key) (@obj.collections.key?(key) && key != "posts") || super end def posts @site_posts ||= @obj.posts.docs.sort { |a, b| b <=> a } end def html_pages @site_html_pages ||= @obj.pages.select do |page| page.html? || page.url.end_with?("/") end end def collections @site_collections ||= @obj.collections.values.sort_by(&:label).map(&:to_liquid) end # `{{ site.related_posts }}` is how posts can get posts related to # them, either through LSI if it's enabled, or through the most # recent posts. # We should remove this in 4.0 and switch to `{{ post.related_posts }}`. def related_posts return nil unless @current_document.is_a?(Jekyll::Document) @current_document.related_posts end attr_writer :current_document # return nil for `{{ site.config }}` even if --config was passed via CLI def config; 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/drops/jekyll_drop.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/drops/jekyll_drop.rb
# frozen_string_literal: true module Jekyll module Drops class JekyllDrop < Liquid::Drop class << self def global @global ||= JekyllDrop.new end end def version Jekyll::VERSION end def environment Jekyll.env end def to_h @to_h ||= { "version" => version, "environment" => environment, } end def to_json(state = nil) JSON.generate(to_h, state) 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/readers/static_file_reader.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/readers/static_file_reader.rb
# frozen_string_literal: true module Jekyll class StaticFileReader attr_reader :site, :dir, :unfiltered_content def initialize(site, dir) @site = site @dir = dir @unfiltered_content = [] end # Read all the files in <source>/<dir>/ for Yaml header and create a new Page # object for each file. # # dir - The String relative path of the directory to read. # # Returns an array of static files. def read(files) files.map do |file| @unfiltered_content << StaticFile.new(@site, @site.source, @dir, file) end @unfiltered_content 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/readers/theme_assets_reader.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/readers/theme_assets_reader.rb
# frozen_string_literal: true module Jekyll class ThemeAssetsReader attr_reader :site def initialize(site) @site = site end def read return unless site.theme && site.theme.assets_path Find.find(site.theme.assets_path) do |path| next if File.directory?(path) if File.symlink?(path) Jekyll.logger.warn "Theme reader:", "Ignored symlinked asset: #{path}" else read_theme_asset(path) end end end private def read_theme_asset(path) base = site.theme.root dir = File.dirname(path.sub("#{site.theme.root}/", "")) name = File.basename(path) if Utils.has_yaml_header?(path) append_unless_exists site.pages, Jekyll::Page.new(site, base, dir, name) else append_unless_exists site.static_files, Jekyll::StaticFile.new(site, base, "/#{dir}", name) end end def append_unless_exists(haystack, new_item) if haystack.any? { |file| file.relative_path == new_item.relative_path } Jekyll.logger.debug "Theme:", "Ignoring #{new_item.relative_path} in theme due to existing file " \ "with that path in site." return end haystack << new_item 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/readers/layout_reader.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/readers/layout_reader.rb
# frozen_string_literal: true module Jekyll class LayoutReader attr_reader :site def initialize(site) @site = site @layouts = {} end def read layout_entries.each do |layout_file| @layouts[layout_name(layout_file)] = \ Layout.new(site, layout_directory, layout_file) end theme_layout_entries.each do |layout_file| @layouts[layout_name(layout_file)] ||= \ Layout.new(site, theme_layout_directory, layout_file) end @layouts end def layout_directory @layout_directory ||= (layout_directory_in_cwd || layout_directory_inside_source) end def theme_layout_directory @theme_layout_directory ||= site.theme.layouts_path if site.theme end private def layout_entries entries_in layout_directory end def theme_layout_entries theme_layout_directory ? entries_in(theme_layout_directory) : [] end def entries_in(dir) entries = [] within(dir) do entries = EntryFilter.new(site).filter(Dir["**/*.*"]) end entries end def layout_name(file) file.split(".")[0..-2].join(".") end def within(directory) return unless File.exist?(directory) Dir.chdir(directory) { yield } end def layout_directory_inside_source site.in_source_dir(site.config["layouts_dir"]) end def layout_directory_in_cwd dir = Jekyll.sanitized_path(Dir.pwd, site.config["layouts_dir"]) if File.directory?(dir) && !site.safe 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/jekyll-3.8.4/lib/jekyll/readers/collection_reader.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/readers/collection_reader.rb
# frozen_string_literal: true module Jekyll class CollectionReader SPECIAL_COLLECTIONS = %w(posts data).freeze attr_reader :site, :content def initialize(site) @site = site @content = {} end # Read in all collections specified in the configuration # # Returns nothing. def read site.collections.each_value do |collection| collection.read unless SPECIAL_COLLECTIONS.include?(collection.label) 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/readers/data_reader.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/readers/data_reader.rb
# frozen_string_literal: true module Jekyll class DataReader attr_reader :site, :content def initialize(site) @site = site @content = {} @entry_filter = EntryFilter.new(site) end # Read all the files in <dir> and adds them to @content # # dir - The String relative path of the directory to read. # # Returns @content, a Hash of the .yaml, .yml, # .json, and .csv files in the base directory def read(dir) base = site.in_source_dir(dir) read_data_to(base, @content) @content end # Read and parse all .yaml, .yml, .json, .csv and .tsv # files under <dir> and add them to the <data> variable. # # dir - The string absolute path of the directory to read. # data - The variable to which data will be added. # # Returns nothing def read_data_to(dir, data) return unless File.directory?(dir) && !@entry_filter.symlink?(dir) entries = Dir.chdir(dir) do Dir["*.{yaml,yml,json,csv,tsv}"] + Dir["*"].select { |fn| File.directory?(fn) } end entries.each do |entry| path = @site.in_source_dir(dir, entry) next if @entry_filter.symlink?(path) if File.directory?(path) read_data_to(path, data[sanitize_filename(entry)] = {}) else key = sanitize_filename(File.basename(entry, ".*")) data[key] = read_data_file(path) end end end # Determines how to read a data file. # # Returns the contents of the data file. def read_data_file(path) case File.extname(path).downcase when ".csv" CSV.read(path, { :headers => true, :encoding => site.config["encoding"], }).map(&:to_hash) when ".tsv" CSV.read(path, { :col_sep => "\t", :headers => true, :encoding => site.config["encoding"], }).map(&:to_hash) else SafeYAML.load_file(path) end end def sanitize_filename(name) name.gsub(%r![^\w\s-]+|(?<=^|\b\s)\s+(?=$|\s?\b)!, "") .gsub(%r!\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/jekyll-3.8.4/lib/jekyll/readers/page_reader.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/readers/page_reader.rb
# frozen_string_literal: true module Jekyll class PageReader attr_reader :site, :dir, :unfiltered_content def initialize(site, dir) @site = site @dir = dir @unfiltered_content = [] end # Read all the files in <source>/<dir>/ for Yaml header and create a new Page # object for each file. # # dir - The String relative path of the directory to read. # # Returns an array of static pages. def read(files) files.map do |page| @unfiltered_content << Page.new(@site, @site.source, @dir, page) end @unfiltered_content.select { |page| site.publisher.publish?(page) } 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/readers/post_reader.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/readers/post_reader.rb
# frozen_string_literal: true module Jekyll class PostReader attr_reader :site, :unfiltered_content def initialize(site) @site = site end # Read all the files in <source>/<dir>/_drafts and create a new # Document object with each one. # # dir - The String relative path of the directory to read. # # Returns nothing. def read_drafts(dir) read_publishable(dir, "_drafts", Document::DATELESS_FILENAME_MATCHER) end # Read all the files in <source>/<dir>/_posts and create a new Document # object with each one. # # dir - The String relative path of the directory to read. # # Returns nothing. def read_posts(dir) read_publishable(dir, "_posts", Document::DATE_FILENAME_MATCHER) end # Read all the files in <source>/<dir>/<magic_dir> and create a new # Document object with each one insofar as it matches the regexp matcher. # # dir - The String relative path of the directory to read. # # Returns nothing. def read_publishable(dir, magic_dir, matcher) read_content(dir, magic_dir, matcher).tap { |docs| docs.each(&:read) } .select do |doc| if doc.content.valid_encoding? site.publisher.publish?(doc).tap do |will_publish| if !will_publish && site.publisher.hidden_in_the_future?(doc) Jekyll.logger.debug "Skipping:", "#{doc.relative_path} has a future date" end end else Jekyll.logger.debug "Skipping:", "#{doc.relative_path} is not valid UTF-8" false end end end # Read all the content files from <source>/<dir>/magic_dir # and return them with the type klass. # # dir - The String relative path of the directory to read. # magic_dir - The String relative directory to <dir>, # looks for content here. # klass - The return type of the content. # # Returns klass type of content files def read_content(dir, magic_dir, matcher) @site.reader.get_entries(dir, magic_dir).map do |entry| next unless entry =~ matcher path = @site.in_source_dir(File.join(dir, magic_dir, entry)) Document.new(path, { :site => @site, :collection => @site.posts, }) end.reject(&: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/jekyll-3.8.4/lib/jekyll/filters/url_filters.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/filters/url_filters.rb
# frozen_string_literal: true module Jekyll module Filters module URLFilters # Produces an absolute URL based on site.url and site.baseurl. # # input - the URL to make absolute. # # Returns the absolute URL as a String. def absolute_url(input) return if input.nil? input = input.url if input.respond_to?(:url) return input if Addressable::URI.parse(input.to_s).absolute? site = @context.registers[:site] return relative_url(input) if site.config["url"].nil? Addressable::URI.parse( site.config["url"].to_s + relative_url(input) ).normalize.to_s end # Produces a URL relative to the domain root based on site.baseurl # unless it is already an absolute url with an authority (host). # # input - the URL to make relative to the domain root # # Returns a URL relative to the domain root as a String. def relative_url(input) return if input.nil? input = input.url if input.respond_to?(:url) return input if Addressable::URI.parse(input.to_s).absolute? parts = [sanitized_baseurl, input] Addressable::URI.parse( parts.compact.map { |part| ensure_leading_slash(part.to_s) }.join ).normalize.to_s end # Strips trailing `/index.html` from URLs to create pretty permalinks # # input - the URL with a possible `/index.html` # # Returns a URL with the trailing `/index.html` removed def strip_index(input) return if input.nil? || input.to_s.empty? input.sub(%r!/index\.html?$!, "/") end private def sanitized_baseurl site = @context.registers[:site] site.config["baseurl"].to_s.chomp("/") end def ensure_leading_slash(input) return input if input.nil? || input.empty? || input.start_with?("/") "/#{input}" 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/filters/date_filters.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/filters/date_filters.rb
# frozen_string_literal: true module Jekyll module Filters module DateFilters # Format a date in short format e.g. "27 Jan 2011". # Ordinal format is also supported, in both the UK # (e.g. "27th Jan 2011") and US ("e.g. Jan 27th, 2011") formats. # UK format is the default. # # date - the Time to format. # type - if "ordinal" the returned String will be in ordinal format # style - if "US" the returned String will be in US format. # Otherwise it will be in UK format. # # Returns the formatting String. def date_to_string(date, type = nil, style = nil) stringify_date(date, "%b", type, style) end # Format a date in long format e.g. "27 January 2011". # Ordinal format is also supported, in both the UK # (e.g. "27th January 2011") and US ("e.g. January 27th, 2011") formats. # UK format is the default. # # date - the Time to format. # type - if "ordinal" the returned String will be in ordinal format # style - if "US" the returned String will be in US format. # Otherwise it will be in UK format. # # Returns the formatted String. def date_to_long_string(date, type = nil, style = nil) stringify_date(date, "%B", type, style) end # Format a date for use in XML. # # date - The Time to format. # # Examples # # date_to_xmlschema(Time.now) # # => "2011-04-24T20:34:46+08:00" # # Returns the formatted String. def date_to_xmlschema(date) return date if date.to_s.empty? time(date).xmlschema end # Format a date according to RFC-822 # # date - The Time to format. # # Examples # # date_to_rfc822(Time.now) # # => "Sun, 24 Apr 2011 12:34:46 +0000" # # Returns the formatted String. def date_to_rfc822(date) return date if date.to_s.empty? time(date).rfc822 end private # month_type: Notations that evaluate to 'Month' via `Time#strftime` ("%b", "%B") # type: nil (default) or "ordinal" # style: nil (default) or "US" # # Returns a stringified date or the empty input. def stringify_date(date, month_type, type = nil, style = nil) return date if date.to_s.empty? time = time(date) if type == "ordinal" day = time.day ordinal_day = "#{day}#{ordinal(day)}" return time.strftime("#{month_type} #{ordinal_day}, %Y") if style == "US" return time.strftime("#{ordinal_day} #{month_type} %Y") end time.strftime("%d #{month_type} %Y") end private def ordinal(number) return "th" if (11..13).cover?(number) case number % 10 when 1 then "st" when 2 then "nd" when 3 then "rd" else "th" end end private def time(input) date = Liquid::Utils.to_date(input) unless date.respond_to?(:to_time) raise Errors::InvalidDateError, "Invalid Date: '#{input.inspect}' is not a valid datetime." end date.to_time.dup.localtime 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/filters/grouping_filters.rb
_vendor/ruby/2.6.0/gems/jekyll-3.8.4/lib/jekyll/filters/grouping_filters.rb
# frozen_string_literal: true module Jekyll module Filters module GroupingFilters # Group an array of items by a property # # input - the inputted Enumerable # property - the property # # Returns an array of Hashes, each looking something like this: # {"name" => "larry" # "items" => [...] } # all the items where `property` == "larry" def group_by(input, property) if groupable?(input) groups = input.group_by { |item| item_property(item, property).to_s } grouped_array(groups) else input end end # Group an array of items by an expression # # input - the object array # variable - the variable to assign each item to in the expression # expression -a Liquid comparison expression passed in as a string # # Returns the filtered array of objects def group_by_exp(input, variable, expression) return input unless groupable?(input) parsed_expr = parse_expression(expression) @context.stack do groups = input.group_by do |item| @context[variable] = item parsed_expr.render(@context) end grouped_array(groups) end end private def parse_expression(str) Liquid::Variable.new(str, Liquid::ParseContext.new) end private def groupable?(element) element.respond_to?(:group_by) end private def grouped_array(groups) groups.each_with_object([]) do |item, array| array << { "name" => item.first, "items" => item.last, "size" => item.last.size, } 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/rb-inotify-0.9.10/spec/rb-inotify_spec.rb
_vendor/ruby/2.6.0/gems/rb-inotify-0.9.10/spec/rb-inotify_spec.rb
require 'spec_helper' describe INotify do describe "version" do it "exists" do expect(INotify::VERSION).to be_truthy 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/rb-inotify-0.9.10/spec/spec_helper.rb
_vendor/ruby/2.6.0/gems/rb-inotify-0.9.10/spec/spec_helper.rb
require "bundler/setup" require "rb-inotify" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" config.expect_with :rspec do |c| c.syntax = :expect 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/rb-inotify-0.9.10/spec/rb-inotify/errors_spec.rb
_vendor/ruby/2.6.0/gems/rb-inotify-0.9.10/spec/rb-inotify/errors_spec.rb
require 'spec_helper' describe INotify do describe "QueueOverflowError" do it "exists" do expect(INotify::QueueOverflowError).to be_truthy 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/rb-inotify-0.9.10/lib/rb-inotify.rb
_vendor/ruby/2.6.0/gems/rb-inotify-0.9.10/lib/rb-inotify.rb
require 'rb-inotify/version' require 'rb-inotify/native' require 'rb-inotify/native/flags' require 'rb-inotify/notifier' require 'rb-inotify/watcher' require 'rb-inotify/event' require 'rb-inotify/errors' # The root module of the library, which is laid out as so: # # * {Notifier} -- The main class, where the notifications are set up # * {Watcher} -- A watcher for a single file or directory # * {Event} -- An filesystem event notification module INotify 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/rb-inotify-0.9.10/lib/rb-inotify/watcher.rb
_vendor/ruby/2.6.0/gems/rb-inotify-0.9.10/lib/rb-inotify/watcher.rb
module INotify # Watchers monitor a single path for changes, # specified by {INotify::Notifier#watch event flags}. # A watcher is usually created via \{Notifier#watch}. # # One {Notifier} may have many {Watcher}s. # The Notifier actually takes care of the checking for events, # via \{Notifier#run #run} or \{Notifier#process #process}. # The main purpose of having Watcher objects # is to be able to disable them using \{#close}. class Watcher # The {Notifier} that this Watcher belongs to. # # @return [Notifier] attr_reader :notifier # The path that this Watcher is watching. # # @return [String] attr_reader :path # The {INotify::Notifier#watch flags} # specifying the events that this Watcher is watching for, # and potentially some options as well. # # @return [Array<Symbol>] attr_reader :flags # The id for this Watcher. # Used to retrieve this Watcher from {Notifier#watchers}. # # @private # @return [Fixnum] attr_reader :id # Calls this Watcher's callback with the given {Event}. # # @private # @param event [Event] def callback!(event) @callback[event] end # Disables this Watcher, so that it doesn't fire any more events. # # @raise [SystemCallError] if the watch fails to be disabled for some reason def close if Native.inotify_rm_watch(@notifier.fd, @id) == 0 @notifier.watchers.delete(@id) return end raise SystemCallError.new("Failed to stop watching #{path.inspect}", FFI.errno) end # Creates a new {Watcher}. # # @private # @see Notifier#watch def initialize(notifier, path, *flags, &callback) @notifier = notifier @callback = callback || proc {} @path = path @flags = flags.freeze @id = Native.inotify_add_watch(@notifier.fd, path.dup, Native::Flags.to_mask(flags)) unless @id < 0 @notifier.watchers[@id] = self return end raise SystemCallError.new( "Failed to watch #{path.inspect}" + case FFI.errno when Errno::EACCES::Errno; ": read access to the given file is not permitted." when Errno::EBADF::Errno; ": the given file descriptor is not valid." when Errno::EFAULT::Errno; ": path points outside of the process's accessible address space." when Errno::EINVAL::Errno; ": the given event mask contains no legal events; or fd is not an inotify file descriptor." when Errno::ENOMEM::Errno; ": insufficient kernel memory was available." when Errno::ENOSPC::Errno; ": The user limit on the total number of inotify watches was reached or the kernel failed to allocate a needed resource." else; "" end, FFI.errno) 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/rb-inotify-0.9.10/lib/rb-inotify/version.rb
_vendor/ruby/2.6.0/gems/rb-inotify-0.9.10/lib/rb-inotify/version.rb
# Copyright, 2012, by Natalie Weizenbaum. # Copyright, 2017, by Samuel G. D. Williams. <http://www.codeotaku.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module INotify VERSION = '0.9.10' 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/rb-inotify-0.9.10/lib/rb-inotify/event.rb
_vendor/ruby/2.6.0/gems/rb-inotify-0.9.10/lib/rb-inotify/event.rb
module INotify # An event caused by a change on the filesystem. # Each {Watcher} can fire many events, # which are passed to that watcher's callback. class Event # A list of other events that are related to this one. # Currently, this is only used for files that are moved within the same directory: # the `:moved_from` and the `:moved_to` events will be related. # # @return [Array<Event>] attr_reader :related # The name of the file that the event occurred on. # This is only set for events that occur on files in directories; # otherwise, it's `""`. # Similarly, if the event is being fired for the directory itself # the name will be `""` # # This pathname is relative to the enclosing directory. # For the absolute pathname, use \{#absolute\_name}. # Note that when the `:recursive` flag is passed to {Notifier#watch}, # events in nested subdirectories will still have a `#name` field # relative to their immediately enclosing directory. # For example, an event on the file `"foo/bar/baz"` # will have name `"baz"`. # # @return [String] attr_reader :name # The {Notifier} that fired this event. # # @return [Notifier] attr_reader :notifier # An integer specifying that this event is related to some other event, # which will have the same cookie. # # Currently, this is only used for files that are moved within the same directory. # Both the `:moved_from` and the `:moved_to` events will have the same cookie. # # @private # @return [Fixnum] attr_reader :cookie # The {Watcher#id id} of the {Watcher} that fired this event. # # @private # @return [Fixnum] attr_reader :watcher_id # Returns the {Watcher} that fired this event. # # @return [Watcher] def watcher @watcher ||= @notifier.watchers[@watcher_id] end # The absolute path of the file that the event occurred on. # # This is actually only as absolute as the path passed to the {Watcher} # that created this event. # However, it is relative to the working directory, # assuming that hasn't changed since the watcher started. # # @return [String] def absolute_name return watcher.path if name.empty? return File.join(watcher.path, name) end # Returns the flags that describe this event. # This is generally similar to the input to {Notifier#watch}, # except that it won't contain options flags nor `:all_events`, # and it may contain one or more of the following flags: # # `:unmount` # : The filesystem containing the watched file or directory was unmounted. # # `:ignored` # : The \{#watcher watcher} was closed, or the watched file or directory was deleted. # # `:isdir` # : The subject of this event is a directory. # # @return [Array<Symbol>] def flags @flags ||= Native::Flags.from_mask(@native[:mask]) end # Constructs an {Event} object from a string of binary data, # and destructively modifies the string to get rid of the initial segment # used to construct the Event. # # @private # @param data [String] The string to be modified # @param notifier [Notifier] The {Notifier} that fired the event # @return [Event, nil] The event, or `nil` if the string is empty def self.consume(data, notifier) return nil if data.empty? ev = new(data, notifier) data.replace data[ev.size..-1] ev end # Creates an event from a string of binary data. # Differs from {Event.consume} in that it doesn't modify the string. # # @private # @param data [String] The data string # @param notifier [Notifier] The {Notifier} that fired the event def initialize(data, notifier) ptr = FFI::MemoryPointer.from_string(data) @native = Native::Event.new(ptr) @related = [] @cookie = @native[:cookie] @name = fix_encoding(data[@native.size, @native[:len]].gsub(/\0+$/, '')) @notifier = notifier @watcher_id = @native[:wd] raise QueueOverflowError.new("inotify event queue has overflowed.") if @native[:mask] & Native::Flags::IN_Q_OVERFLOW != 0 end # Calls the callback of the watcher that fired this event, # passing in the event itself. # # @private def callback! watcher && watcher.callback!(self) end # Returns the size of this event object in bytes, # including the \{#name} string. # # @return [Fixnum] def size @native.size + @native[:len] end private def fix_encoding(name) name.force_encoding('filesystem') if name.respond_to?(:force_encoding) 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/rb-inotify-0.9.10/lib/rb-inotify/errors.rb
_vendor/ruby/2.6.0/gems/rb-inotify-0.9.10/lib/rb-inotify/errors.rb
module INotify class QueueOverflowError < RuntimeError; 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/rb-inotify-0.9.10/lib/rb-inotify/native.rb
_vendor/ruby/2.6.0/gems/rb-inotify-0.9.10/lib/rb-inotify/native.rb
require 'ffi' module INotify # This module contains the low-level foreign-function interface code # for dealing with the inotify C APIs. # It's an implementation detail, and not meant for users to deal with. # # @private module Native extend FFI::Library ffi_lib FFI::Library::LIBC begin ffi_lib 'inotify' rescue LoadError end # The C struct describing an inotify event. # # @private class Event < FFI::Struct layout( :wd, :int, :mask, :uint32, :cookie, :uint32, :len, :uint32) end attach_function :inotify_init, [], :int attach_function :inotify_add_watch, [:int, :string, :uint32], :int attach_function :inotify_rm_watch, [:int, :uint32], :int attach_function :fpathconf, [:int, :int], :long attach_function :read, [:int, :pointer, :size_t], :ssize_t attach_function :close, [:int], :int 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/rb-inotify-0.9.10/lib/rb-inotify/notifier.rb
_vendor/ruby/2.6.0/gems/rb-inotify-0.9.10/lib/rb-inotify/notifier.rb
module INotify # Notifier wraps a single instance of inotify. # It's possible to have more than one instance, # but usually unnecessary. # # @example # # Create the notifier # notifier = INotify::Notifier.new # # # Run this callback whenever the file path/to/foo.txt is read # notifier.watch("path/to/foo.txt", :access) do # puts "Foo.txt was accessed!" # end # # # Watch for any file in the directory being deleted # # or moved out of the directory. # notifier.watch("path/to/directory", :delete, :moved_from) do |event| # # The #name field of the event object contains the name of the affected file # puts "#{event.name} is no longer in the directory!" # end # # # Nothing happens until you run the notifier! # notifier.run class Notifier # A list of directories that should never be recursively watched. # # * Files in `/dev/fd` sometimes register as directories, but are not enumerable. RECURSIVE_BLACKLIST = %w[/dev/fd] # A hash from {Watcher} ids to the instances themselves. # # @private # @return [{Fixnum => Watcher}] attr_reader :watchers # The underlying file descriptor for this notifier. # This is a valid OS file descriptor, and can be used as such # (except under JRuby -- see \{#to\_io}). # # @return [Fixnum] attr_reader :fd # @return [Boolean] Whether or not this Ruby implementation supports # wrapping the native file descriptor in a Ruby IO wrapper. def self.supports_ruby_io? RUBY_PLATFORM !~ /java/ end # Creates a new {Notifier}. # # @return [Notifier] # @raise [SystemCallError] if inotify failed to initialize for some reason def initialize @fd = Native.inotify_init @watchers = {} return unless @fd < 0 raise SystemCallError.new( "Failed to initialize inotify" + case FFI.errno when Errno::EMFILE::Errno; ": the user limit on the total number of inotify instances has been reached." when Errno::ENFILE::Errno; ": the system limit on the total number of file descriptors has been reached." when Errno::ENOMEM::Errno; ": insufficient kernel memory is available." else; "" end, FFI.errno) end # Returns a Ruby IO object wrapping the underlying file descriptor. # Since this file descriptor is fully functional (except under JRuby), # this IO object can be used in any way a Ruby-created IO object can. # This includes passing it to functions like `#select`. # # Note that this always returns the same IO object. # Creating lots of IO objects for the same file descriptor # can cause some odd problems. # # **This is not supported under JRuby**. # JRuby currently doesn't use native file descriptors for the IO object, # so we can't use this file descriptor as a stand-in. # # @return [IO] An IO object wrapping the file descriptor # @raise [NotImplementedError] if this is being called in JRuby def to_io unless self.class.supports_ruby_io? raise NotImplementedError.new("INotify::Notifier#to_io is not supported under JRuby") end @io ||= IO.new(@fd) end # Watches a file or directory for changes, # calling the callback when there are. # This is only activated once \{#process} or \{#run} is called. # # **Note that by default, this does not recursively watch subdirectories # of the watched directory**. # To do so, use the `:recursive` flag. # # ## Flags # # `:access` # : A file is accessed (that is, read). # # `:attrib` # : A file's metadata is changed (e.g. permissions, timestamps, etc). # # `:close_write` # : A file that was opened for writing is closed. # # `:close_nowrite` # : A file that was not opened for writing is closed. # # `:modify` # : A file is modified. # # `:open` # : A file is opened. # # ### Directory-Specific Flags # # These flags only apply when a directory is being watched. # # `:moved_from` # : A file is moved out of the watched directory. # # `:moved_to` # : A file is moved into the watched directory. # # `:create` # : A file is created in the watched directory. # # `:delete` # : A file is deleted in the watched directory. # # `:delete_self` # : The watched file or directory itself is deleted. # # `:move_self` # : The watched file or directory itself is moved. # # ### Helper Flags # # These flags are just combinations of the flags above. # # `:close` # : Either `:close_write` or `:close_nowrite` is activated. # # `:move` # : Either `:moved_from` or `:moved_to` is activated. # # `:all_events` # : Any event above is activated. # # ### Options Flags # # These flags don't actually specify events. # Instead, they specify options for the watcher. # # `:onlydir` # : Only watch the path if it's a directory. # # `:dont_follow` # : Don't follow symlinks. # # `:mask_add` # : Add these flags to the pre-existing flags for this path. # # `:oneshot` # : Only send the event once, then shut down the watcher. # # `:recursive` # : Recursively watch any subdirectories that are created. # Note that this is a feature of rb-inotify, # rather than of inotify itself, which can only watch one level of a directory. # This means that the {Event#name} field # will contain only the basename of the modified file. # When using `:recursive`, {Event#absolute_name} should always be used. # # @param path [String] The path to the file or directory # @param flags [Array<Symbol>] Which events to watch for # @yield [event] A block that will be called # whenever one of the specified events occur # @yieldparam event [Event] The Event object containing information # about the event that occured # @return [Watcher] A Watcher set up to watch this path for these events # @raise [SystemCallError] if the file or directory can't be watched, # e.g. if the file isn't found, read access is denied, # or the flags don't contain any events def watch(path, *flags, &callback) return Watcher.new(self, path, *flags, &callback) unless flags.include?(:recursive) dir = Dir.new(path) dir.each do |base| d = File.join(path, base) binary_d = d.respond_to?(:force_encoding) ? d.dup.force_encoding('BINARY') : d next if binary_d =~ /\/\.\.?$/ # Current or parent directory next if RECURSIVE_BLACKLIST.include?(d) next if flags.include?(:dont_follow) && File.symlink?(d) next if !File.directory?(d) watch(d, *flags, &callback) end dir.close rec_flags = [:create, :moved_to] return watch(path, *((flags - [:recursive]) | rec_flags)) do |event| callback.call(event) if flags.include?(:all_events) || !(flags & event.flags).empty? next if (rec_flags & event.flags).empty? || !event.flags.include?(:isdir) begin watch(event.absolute_name, *flags, &callback) rescue Errno::ENOENT # If the file has been deleted since the glob was run, we don't want to error out. end end end # Starts the notifier watching for filesystem events. # Blocks until \{#stop} is called. # # @see #process def run @stop = false process until @stop end # Stop watching for filesystem events. # That is, if we're in a \{#run} loop, # exit out as soon as we finish handling the events. def stop @stop = true end # Blocks until there are one or more filesystem events # that this notifier has watchers registered for. # Once there are events, the appropriate callbacks are called # and this function returns. # # @see #run def process read_events.each do |event| event.callback! event.flags.include?(:ignored) && event.notifier.watchers.delete(event.watcher_id) end end # Close the notifier. # # @raise [SystemCallError] if closing the underlying file descriptor fails. def close stop if Native.close(@fd) == 0 @watchers.clear return end raise SystemCallError.new("Failed to properly close inotify socket" + case FFI.errno when Errno::EBADF::Errno; ": invalid or closed file descriptior" when Errno::EIO::Errno; ": an I/O error occured" end, FFI.errno) end # Blocks until there are one or more filesystem events that this notifier # has watchers registered for. Once there are events, returns their {Event} # objects. # # This can return an empty list if the watcher was closed elsewhere. # # {#run} or {#process} are ususally preferable to calling this directly. def read_events size = Native::Event.size + Native.fpathconf(fd, Native::Flags::PC_NAME_MAX) + 1 tries = 1 begin data = readpartial(size) rescue SystemCallError => er # EINVAL means that there's more data to be read # than will fit in the buffer size raise er unless er.errno == Errno::EINVAL::Errno && tries < 5 size *= 2 tries += 1 retry end return [] if data.nil? events = [] cookies = {} while event = Event.consume(data, self) events << event next if event.cookie == 0 cookies[event.cookie] ||= [] cookies[event.cookie] << event end cookies.each {|c, evs| evs.each {|ev| ev.related.replace(evs - [ev]).freeze}} events end private # Same as IO#readpartial, or as close as we need. def readpartial(size) # Use Ruby's readpartial if possible, to avoid blocking other threads. begin return to_io.readpartial(size) if self.class.supports_ruby_io? rescue Errno::EBADF, IOError # If the IO has already been closed, reading from it will cause # Errno::EBADF. In JRuby it can raise IOError with invalid or # closed file descriptor. return nil rescue IOError => ex return nil if ex.message =~ /stream closed/ raise end tries = 0 begin tries += 1 buffer = FFI::MemoryPointer.new(:char, size) size_read = Native.read(fd, buffer, size) return buffer.read_string(size_read) if size_read >= 0 end while FFI.errno == Errno::EINTR::Errno && tries <= 5 raise SystemCallError.new("Error reading inotify events" + case FFI.errno when Errno::EAGAIN::Errno; ": no data available for non-blocking I/O" when Errno::EBADF::Errno; ": invalid or closed file descriptor" when Errno::EFAULT::Errno; ": invalid buffer" when Errno::EINVAL::Errno; ": invalid file descriptor" when Errno::EIO::Errno; ": I/O error" when Errno::EISDIR::Errno; ": file descriptor is a directory" else; "" end, FFI.errno) 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/rb-inotify-0.9.10/lib/rb-inotify/native/flags.rb
_vendor/ruby/2.6.0/gems/rb-inotify-0.9.10/lib/rb-inotify/native/flags.rb
module INotify module Native # A module containing all the inotify flags # to be passed to {Notifier#watch}. # # @private module Flags # File was accessed. IN_ACCESS = 0x00000001 # Metadata changed. IN_ATTRIB = 0x00000004 # Writtable file was closed. IN_CLOSE_WRITE = 0x00000008 # File was modified. IN_MODIFY = 0x00000002 # Unwrittable file closed. IN_CLOSE_NOWRITE = 0x00000010 # File was opened. IN_OPEN = 0x00000020 # File was moved from X. IN_MOVED_FROM = 0x00000040 # File was moved to Y. IN_MOVED_TO = 0x00000080 # Subfile was created. IN_CREATE = 0x00000100 # Subfile was deleted. IN_DELETE = 0x00000200 # Self was deleted. IN_DELETE_SELF = 0x00000400 # Self was moved. IN_MOVE_SELF = 0x00000800 ## Helper events. # Close. IN_CLOSE = (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) # Moves. IN_MOVE = (IN_MOVED_FROM | IN_MOVED_TO) # All events which a program can wait on. IN_ALL_EVENTS = (IN_ACCESS | IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE | IN_CLOSE_NOWRITE | IN_OPEN | IN_MOVED_FROM | IN_MOVED_TO | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MOVE_SELF) ## Special flags. # Only watch the path if it is a directory. IN_ONLYDIR = 0x01000000 # Do not follow a sym link. IN_DONT_FOLLOW = 0x02000000 # Add to the mask of an already existing watch. IN_MASK_ADD = 0x20000000 # Only send event once. IN_ONESHOT = 0x80000000 ## Events sent by the kernel. # Backing fs was unmounted. IN_UNMOUNT = 0x00002000 # Event queued overflowed. IN_Q_OVERFLOW = 0x00004000 # File was ignored. IN_IGNORED = 0x00008000 # Event occurred against dir. IN_ISDIR = 0x40000000 ## fpathconf Macros # returns the maximum length of a filename in the directory path or fd that the process is allowed to create. The corresponding macro is _POSIX_NAME_MAX. PC_NAME_MAX = 3 # Converts a list of flags to the bitmask that the C API expects. # # @param flags [Array<Symbol>] # @return [Fixnum] def self.to_mask(flags) flags.map {|flag| const_get("IN_#{flag.to_s.upcase}")}. inject(0) {|mask, flag| mask | flag} end # Converts a bitmask from the C API into a list of flags. # # @param mask [Fixnum] # @return [Array<Symbol>] def self.from_mask(mask) constants.map {|c| c.to_s}.select do |c| next false unless c =~ /^IN_/ const_get(c) & mask != 0 end.map {|c| c.sub("IN_", "").downcase.to_sym} - [:all_events] 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/mercenary-0.3.6/spec/program_spec.rb
_vendor/ruby/2.6.0/gems/mercenary-0.3.6/spec/program_spec.rb
require "spec_helper" describe(Mercenary::Program) do context "a basic program" do let(:program) { Mercenary::Program.new(:my_name) } it "can be created with just a name" do expect(program.name).to eql(:my_name) end it "can set its version" do version = Mercenary::VERSION program.version version expect(program.version).to eq(version) 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/mercenary-0.3.6/spec/command_spec.rb
_vendor/ruby/2.6.0/gems/mercenary-0.3.6/spec/command_spec.rb
require "spec_helper" describe(Mercenary::Command) do context "a basic command" do let(:command) { Mercenary::Command.new(:my_name) } let(:parent) { Mercenary::Command.new(:my_parent) } let(:with_sub) do c = Mercenary::Command.new(:i_have_subcommand) add_sub.call(c) c end let(:command_with_parent) do Mercenary::Command.new( :i_have_parent, parent ) end let(:add_sub) do Proc.new do |c| c.command(:sub_command) { |p| } end end it "can be created with just a name" do expect(command.name).to eql(:my_name) end it "can hold a parent command" do expect(command_with_parent.parent).to eql(parent) end it "can create subcommands" do expect(add_sub.call(command)).to be_a(Mercenary::Command) expect(add_sub.call(command).parent).to eq(command) end it "can set its version" do version = "1.4.2" command.version version expect(command.version).to eq(version) end it "can set its syntax" do syntax_string = "my_name [options]" cmd = described_class.new(:my_name) cmd.syntax syntax_string expect(cmd.syntax).to eq(syntax_string) end it "can set its description" do desc = "run all the things" command.description desc expect(command.description).to eq(desc) end it "can set its options" do name = "show_drafts" opts = ['--drafts', 'Render posts in the _drafts folder'] option = Mercenary::Option.new(name, opts) command.option name, *opts expect(command.options).to eql([option]) expect(command.map.values).to include(name) end it "knows its full name" do expect(command_with_parent.full_name).to eql("my_parent i_have_parent") end it "knows its identity" do command_with_parent.version '1.8.7' expect(command_with_parent.identity).to eql("my_parent i_have_parent 1.8.7") end it "raises an ArgumentError if I specify a default_command that isn't there" do c = command # some weird NameError with the block below? expect { c.default_command(:nope) }.to raise_error(ArgumentError) end it "sets the default_command" do expect(with_sub.default_command(:sub_command).name).to eq(:sub_command) end context "with an alias" do before(:each) do command_with_parent.alias(:an_alias) end it "shows the alias in the summary" do expect(command_with_parent.summarize).to eql(" i_have_parent, an_alias ") end it "its names_and_aliases method reports both the name and alias" do expect(command_with_parent.names_and_aliases).to eql("i_have_parent, an_alias") 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/mercenary-0.3.6/spec/option_spec.rb
_vendor/ruby/2.6.0/gems/mercenary-0.3.6/spec/option_spec.rb
require 'spec_helper' describe(Mercenary::Option) do let(:config_key) { "largo" } let(:description) { "This is a description" } let(:switches) { ['-l', '--largo'] } let(:option) { described_class.new(config_key, [switches, description].flatten.reject(&:nil?)) } it "knows its config key" do expect(option.config_key).to eql(config_key) end it "knows its description" do expect(option.description).to eql(description) end it "knows its switches" do expect(option.switches).to eql(switches) end it "knows how to present itself" do expect(option.to_s).to eql(" -l, --largo #{description}") end it "has an OptionParser representation" do expect(option.for_option_parser).to eql([switches, description].flatten) end it "compares itself with other options well" do new_option = described_class.new(config_key, ['-l', '--largo', description]) expect(option.eql?(new_option)).to be(true) expect(option.hash.eql?(new_option.hash)).to be(true) end it "has a custom #hash" do expect(option.hash.to_s).to match(/\d+/) end context "with just the long switch" do let(:switches) { ['--largo'] } it "adds an empty string in place of the short switch" do expect(option.switches).to eql(['', '--largo']) end it "sets its description properly" do expect(option.description).to eql(description) end it "knows how to present the switch" do expect(option.formatted_switches).to eql(" --largo ") end end context "with just the short switch" do let(:switches) { ['-l'] } it "adds an empty string in place of the long switch" do expect(option.switches).to eql(['-l', '']) end it "sets its description properly" do expect(option.description).to eql(description) end it "knows how to present the switch" do expect(option.formatted_switches).to eql(" -l ") end end context "without a description" do let(:description) { nil } it "knows there is no description" do expect(option.description).to be(nil) end it "knows both inputs are switches" do expect(option.switches).to eql(switches) 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/mercenary-0.3.6/spec/presenter_spec.rb
_vendor/ruby/2.6.0/gems/mercenary-0.3.6/spec/presenter_spec.rb
require 'spec_helper' describe(Mercenary::Presenter) do let(:supercommand) { Mercenary::Command.new(:script_name) } let(:command) { Mercenary::Command.new(:subcommand, supercommand) } let(:presenter) { described_class.new(command) } before(:each) do command.version '1.4.2' command.description 'Do all the things.' command.option 'one', '-1', '--one', 'The first option' command.option 'two', '-2', '--two', 'The second option' command.alias :cmd supercommand.commands[command.name] = command end it "knows how to present the command" do expect(presenter.command_presentation).to eql("script_name subcommand 1.4.2 -- Do all the things.\n\nUsage:\n\n script_name subcommand\n\nOptions:\n -1, --one The first option\n -2, --two The second option") end it "knows how to present the subcommands, without duplicates for aliases" do expect(described_class.new(supercommand).subcommands_presentation).to eql(" subcommand, cmd Do all the things.") end it "knows how to present the usage" do expect(presenter.usage_presentation).to eql(" script_name subcommand") end it "knows how to present the options" do expect(presenter.options_presentation).to eql(" -1, --one The first option\n -2, --two The second option") end it "allows you to say print_* instead of *_presentation" do expect(presenter.print_usage).to eql(presenter.usage_presentation) expect(presenter.print_subcommands).to eql(presenter.subcommands_presentation) expect(presenter.print_options).to eql(presenter.options_presentation) expect(presenter.print_command).to eql(presenter.command_presentation) 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/mercenary-0.3.6/spec/spec_helper.rb
_vendor/ruby/2.6.0/gems/mercenary-0.3.6/spec/spec_helper.rb
lib = File.expand_path('../../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'mercenary' RSpec.configure do |config| config.run_all_when_everything_filtered = true config.filter_run :focus # 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' 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/mercenary-0.3.6/examples/help_dialogue.rb
_vendor/ruby/2.6.0/gems/mercenary-0.3.6/examples/help_dialogue.rb
#!/usr/bin/env ruby $:.unshift File.join(File.dirname(__FILE__), *%w{ .. lib }) require "mercenary" # This example sets the logging mode of mercenary to # debug. Logging messages from "p.logger.debug" will # be output to STDOUT. Mercenary.program(:help_dialogue) do |p| p.version "2.0.1" p.description 'An example of the help dialogue in Mercenary' p.syntax 'help_dialogue <subcommand>' p.command(:some_subcommand) do |c| c.version '1.4.2' c.syntax 'some_subcommand <subcommand> [options]' c.description 'Some subcommand to do something' c.option 'an_option', '-o', '--option', 'Some option' c.alias(:blah) c.command(:yet_another_sub) do |f| f.syntax 'yet_another_sub [options]' f.description 'Do amazing things' f.option 'blah', '-b', '--blah', 'Trigger blah flag' f.option 'heh', '-H ARG', '--heh ARG', 'Give a heh' f.action do |args, options| print "Args: " p args print "Opts: " p options end end end p.command(:another_subcommand) do |c| c.syntax 'another_subcommand <subcommand> [options]' c.description 'Another subcommand to do something different.' c.option 'an_option', '-O', '--option', 'Some option' c.option 'another_options', '--pluginzzz', 'Set where the plugins should be found from' 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/mercenary-0.3.6/examples/logging.rb
_vendor/ruby/2.6.0/gems/mercenary-0.3.6/examples/logging.rb
#!/usr/bin/env ruby $:.unshift File.join(File.dirname(__FILE__), *%w{ .. lib }) require "mercenary" # This example sets the logging mode of mercenary to # debug. Logging messages from "p.logger.debug" will # be output to STDOUT. Mercenary.program(:logger_output) do |p| p.version "5.2.6" p.description 'An example of turning on logging for Mercenary.' p.syntax 'logger_output' p.logger.info "The default log level is INFO. So this will output." p.logger.debug "Since DEBUG is below INFO, this will not output." p.logger(Logger::DEBUG) p.logger.debug "Logger level now set to DEBUG. So everything will output." p.logger.debug "Example of DEBUG level message." p.logger.info "Example of INFO level message." p.logger.warn "Example of WARN level message." p.logger.error "Example of ERROR level message." p.logger.fatal "Example of FATAL level message." p.logger.unknown "Example of UNKNOWN level message." p.action do |args, options| p.logger(Logger::INFO) p.logger.debug "Logger level back to INFO. This line will not output." p.logger.info "This INFO message will output." 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/mercenary-0.3.6/examples/trace.rb
_vendor/ruby/2.6.0/gems/mercenary-0.3.6/examples/trace.rb
#!/usr/bin/env ruby $:.unshift File.join(File.dirname(__FILE__), *%w{ .. lib }) require "mercenary" # This example sets the logging mode of mercenary to # debug. Logging messages from "p.logger.debug" will # be output to STDOUT. Mercenary.program(:trace) do |p| p.version "2.0.1" p.description 'An example of traces in Mercenary' p.syntax 'trace <subcommand>' p.action do |_, _| raise ArgumentError.new("YOU DID SOMETHING TERRIBLE YOU BUFFOON") 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/mercenary-0.3.6/lib/mercenary.rb
_vendor/ruby/2.6.0/gems/mercenary-0.3.6/lib/mercenary.rb
require File.expand_path("../mercenary/version", __FILE__) require "optparse" require "logger" module Mercenary autoload :Command, File.expand_path("../mercenary/command", __FILE__) autoload :Option, File.expand_path("../mercenary/option", __FILE__) autoload :Presenter, File.expand_path("../mercenary/presenter", __FILE__) autoload :Program, File.expand_path("../mercenary/program", __FILE__) # Public: Instantiate a new program and execute. # # name - the name of your program # # Returns nothing. def self.program(name) program = Program.new(name) yield program program.go(ARGV) 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/mercenary-0.3.6/lib/mercenary/command.rb
_vendor/ruby/2.6.0/gems/mercenary-0.3.6/lib/mercenary/command.rb
module Mercenary class Command attr_reader :name attr_reader :description attr_reader :syntax attr_accessor :options attr_accessor :commands attr_accessor :actions attr_reader :map attr_accessor :parent attr_reader :trace attr_reader :aliases # Public: Creates a new Command # # name - the name of the command # parent - (optional) the instancce of Mercenary::Command which you wish to # be the parent of this command # # Returns nothing def initialize(name, parent = nil) @name = name @options = [] @commands = {} @actions = [] @map = {} @parent = parent @trace = false @aliases = [] end # Public: Sets or gets the command version # # version - the command version (optional) # # Returns the version and sets it if an argument is non-nil def version(version = nil) @version = version if version @version end # Public: Sets or gets the syntax string # # syntax - the string which describes this command's usage syntax (optional) # # Returns the syntax string and sets it if an argument is present def syntax(syntax = nil) @syntax = syntax if syntax syntax_list = [] if parent syntax_list << parent.syntax.to_s.gsub(/<[\w\s-]+>/, '').gsub(/\[[\w\s-]+\]/, '').strip end syntax_list << (@syntax || name.to_s) syntax_list.join(" ") end # Public: Sets or gets the command description # # description - the description of what the command does (optional) # # Returns the description and sets it if an argument is present def description(desc = nil) @description = desc if desc @description end # Public: Sets the default command # # command_name - the command name to be executed in the event no args are # present # # Returns the default command if there is one, `nil` otherwise def default_command(command_name = nil) if command_name if commands.has_key?(command_name) @default_command = commands[command_name] if command_name @default_command else raise ArgumentError.new("'#{command_name}' couldn't be found in this command's list of commands.") end else @default_command end end # Public: Adds an option switch # # sym - the variable key which is used to identify the value of the switch # at runtime in the options hash # # Returns nothing def option(sym, *options) new_option = Option.new(sym, options) @options << new_option @map[new_option] = sym end # Public: Adds a subcommand # # cmd_name - the name of the command # block - a block accepting the new instance of Mercenary::Command to be # modified (optional) # # Returns nothing def command(cmd_name) cmd = Command.new(cmd_name, self) yield cmd @commands[cmd_name] = cmd end # Public: Add an alias for this command's name to be attached to the parent # # cmd_name - the name of the alias # # Returns nothing def alias(cmd_name) logger.debug "adding alias to parent for self: '#{cmd_name}'" aliases << cmd_name @parent.commands[cmd_name] = self end # Public: Add an action Proc to be executed at runtime # # block - the Proc to be executed at runtime # # Returns nothing def action(&block) @actions << block end # Public: Fetch a Logger (stdlib) # # level - the logger level (a Logger constant, see docs for more info) # # Returns the instance of Logger def logger(level = nil) unless @logger @logger = Logger.new(STDOUT) @logger.level = level || Logger::INFO @logger.formatter = proc do |severity, datetime, progname, msg| "#{identity} | " << "#{severity.downcase.capitalize}:".ljust(7) << " #{msg}\n" end end @logger.level = level unless level.nil? @logger end # Public: Run the command # # argv - an array of string args # opts - the instance of OptionParser # config - the output config hash # # Returns the command to be executed def go(argv, opts, config) opts.banner = "Usage: #{syntax}" process_options(opts, config) add_default_options(opts) if argv[0] && cmd = commands[argv[0].to_sym] logger.debug "Found subcommand '#{cmd.name}'" argv.shift cmd.go(argv, opts, config) else logger.debug "No additional command found, time to exec" self end end # Public: Add this command's options to OptionParser and set a default # action of setting the value of the option to the inputted hash # # opts - instance of OptionParser # config - the Hash in which the option values should be placed # # Returns nothing def process_options(opts, config) options.each do |option| opts.on(*option.for_option_parser) do |x| config[map[option]] = x end end end # Public: Add version and help options to the command # # opts - instance of OptionParser # # Returns nothing def add_default_options(opts) option 'show_help', '-h', '--help', 'Show this message' option 'show_version', '-v', '--version', 'Print the name and version' option 'show_backtrace', '-t', '--trace', 'Show the full backtrace when an error occurs' opts.on("-v", "--version", "Print the version") do puts "#{name} #{version}" exit(0) end opts.on('-t', '--trace', 'Show full backtrace if an error occurs') do @trace = true end opts.on_tail("-h", "--help", "Show this message") do puts self exit end end # Public: Execute all actions given the inputted args and options # # argv - (optional) command-line args (sans opts) # config - (optional) the Hash configuration of string key to value # # Returns nothing def execute(argv = [], config = {}) if actions.empty? && !default_command.nil? default_command.execute else actions.each { |a| a.call(argv, config) } end end # Public: Check if this command has a subcommand # # sub_command - the name of the subcommand # # Returns true if this command is the parent of a command of name # 'sub_command' and false otherwise def has_command?(sub_command) commands.keys.include?(sub_command) end # Public: Identify this command # # Returns a string which identifies this command def ident "<Command name=#{identity}>" end # Public: Get the full identity (name & version) of this command # # Returns a string containing the name and version if it exists def identity "#{full_name} #{version if version}".strip end # Public: Get the name of the current command plus that of # its parent commands # # Returns the full name of the command def full_name the_name = [] the_name << parent.full_name if parent && parent.full_name the_name << name the_name.join(" ") end # Public: Return all the names and aliases for this command. # # Returns a comma-separated String list of the name followed by its aliases def names_and_aliases ([name.to_s] + aliases).compact.join(", ") end # Public: Build a string containing a summary of the command # # Returns a one-line summary of the command. def summarize " #{names_and_aliases.ljust(20)} #{description}" end # Public: Build a string containing the command name, options and any subcommands # # Returns the string identifying this command, its options and its subcommands def to_s Presenter.new(self).print_command 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/mercenary-0.3.6/lib/mercenary/version.rb
_vendor/ruby/2.6.0/gems/mercenary-0.3.6/lib/mercenary/version.rb
module Mercenary VERSION = "0.3.6" 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/mercenary-0.3.6/lib/mercenary/presenter.rb
_vendor/ruby/2.6.0/gems/mercenary-0.3.6/lib/mercenary/presenter.rb
module Mercenary class Presenter attr_accessor :command # Public: Make a new Presenter # # command - a Mercenary::Command to present # # Returns nothing def initialize(command) @command = command end # Public: Builds a string representation of the command usage # # Returns the string representation of the command usage def usage_presentation " #{command.syntax}" end # Public: Builds a string representation of the options # # Returns the string representation of the options def options_presentation return nil unless command_options_presentation || parent_command_options_presentation [command_options_presentation, parent_command_options_presentation].compact.join("\n") end def command_options_presentation return nil unless command.options.size > 0 command.options.map(&:to_s).join("\n") end # Public: Builds a string representation of the options for parent # commands # # Returns the string representation of the options for parent commands def parent_command_options_presentation return nil unless command.parent Presenter.new(command.parent).options_presentation end # Public: Builds a string representation of the subcommands # # Returns the string representation of the subcommands def subcommands_presentation return nil unless command.commands.size > 0 command.commands.values.uniq.map(&:summarize).join("\n") end # Public: Builds the command header, including the command identity and description # # Returns the command header as a String def command_header header = "#{command.identity}" header << " -- #{command.description}" if command.description header end # Public: Builds a string representation of the whole command # # Returns the string representation of the whole command def command_presentation msg = [] msg << command_header msg << "Usage:" msg << usage_presentation if opts = options_presentation msg << "Options:\n#{opts}" end if subcommands = subcommands_presentation msg << "Subcommands:\n#{subcommands_presentation}" end msg.join("\n\n") end # Public: Turn a print_* into a *_presentation or freak out # # meth - the method being called # args - an array of arguments passed to the missing method # block - the block passed to the missing method # # Returns the value of whatever function is called def method_missing(meth, *args, &block) if meth.to_s =~ /^print_(.+)$/ send("#{$1.downcase}_presentation") else super # You *must* call super if you don't handle the method, # otherwise you'll mess up Ruby's method lookup. end end end end
ruby
MIT
d8026a4e9cc6348bf38951ee96c523f4ec19f3c4
2026-01-04T17:45:10.474201Z
false