Ignore unused transitive dependencies: tzinfo & zeitwerk
This commit is contained in:
parent
6f9aa98e52
commit
e16f4ef1c2
2
.gitignore
vendored
2
.gitignore
vendored
@ -184,12 +184,14 @@
|
||||
**/vendor/bundle/ruby/*/gems/strscan-*/
|
||||
**/vendor/bundle/ruby/*/gems/tapioca-*/
|
||||
**/vendor/bundle/ruby/*/gems/thor-*/
|
||||
**/vendor/bundle/ruby/*/gems/tzinfo-*/
|
||||
**/vendor/bundle/ruby/*/gems/unicode-display_width-*/
|
||||
**/vendor/bundle/ruby/*/gems/unparser-*/
|
||||
**/vendor/bundle/ruby/*/gems/uri_template-*/
|
||||
**/vendor/bundle/ruby/*/gems/webrobots-*/
|
||||
**/vendor/bundle/ruby/*/gems/yard-*/
|
||||
**/vendor/bundle/ruby/*/gems/yard-sorbet-*/
|
||||
**/vendor/bundle/ruby/*/gems/zeitwerk-*/
|
||||
**/vendor/cache/
|
||||
**/vendor/specifications/
|
||||
|
||||
|
||||
@ -1,81 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
# The top level module for TZInfo.
|
||||
module TZInfo
|
||||
class << self
|
||||
# Instructs the current {DataSource} to load all timezone and country data
|
||||
# into memory (initializing the {DataSource} first if not previously
|
||||
# accessed or set).
|
||||
#
|
||||
# This may be desirable in production environments to improve copy-on-write
|
||||
# performance and to avoid flushing the constant cache every time a new
|
||||
# timezone or country is loaded from {DataSources::RubyDataSource}.
|
||||
def eager_load!
|
||||
DataSource.get.eager_load!
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
require_relative 'tzinfo/ruby_core_support'
|
||||
|
||||
require_relative 'tzinfo/version'
|
||||
|
||||
require_relative 'tzinfo/string_deduper'
|
||||
|
||||
require_relative 'tzinfo/timestamp'
|
||||
|
||||
require_relative 'tzinfo/with_offset'
|
||||
require_relative 'tzinfo/datetime_with_offset'
|
||||
require_relative 'tzinfo/time_with_offset'
|
||||
require_relative 'tzinfo/timestamp_with_offset'
|
||||
|
||||
require_relative 'tzinfo/timezone_offset'
|
||||
require_relative 'tzinfo/timezone_transition'
|
||||
require_relative 'tzinfo/transition_rule'
|
||||
require_relative 'tzinfo/annual_rules'
|
||||
|
||||
require_relative 'tzinfo/data_sources'
|
||||
require_relative 'tzinfo/data_sources/timezone_info'
|
||||
require_relative 'tzinfo/data_sources/data_timezone_info'
|
||||
require_relative 'tzinfo/data_sources/linked_timezone_info'
|
||||
require_relative 'tzinfo/data_sources/constant_offset_data_timezone_info'
|
||||
require_relative 'tzinfo/data_sources/transitions_data_timezone_info'
|
||||
|
||||
require_relative 'tzinfo/data_sources/country_info'
|
||||
|
||||
require_relative 'tzinfo/data_sources/posix_time_zone_parser'
|
||||
require_relative 'tzinfo/data_sources/zoneinfo_reader'
|
||||
|
||||
require_relative 'tzinfo/data_source'
|
||||
require_relative 'tzinfo/data_sources/ruby_data_source'
|
||||
require_relative 'tzinfo/data_sources/zoneinfo_data_source'
|
||||
|
||||
require_relative 'tzinfo/timezone_period'
|
||||
require_relative 'tzinfo/offset_timezone_period'
|
||||
require_relative 'tzinfo/transitions_timezone_period'
|
||||
require_relative 'tzinfo/timezone'
|
||||
require_relative 'tzinfo/info_timezone'
|
||||
require_relative 'tzinfo/data_timezone'
|
||||
require_relative 'tzinfo/linked_timezone'
|
||||
require_relative 'tzinfo/timezone_proxy'
|
||||
|
||||
require_relative 'tzinfo/country'
|
||||
require_relative 'tzinfo/country_timezone'
|
||||
|
||||
require_relative 'tzinfo/format2'
|
||||
require_relative 'tzinfo/format2/country_definer'
|
||||
require_relative 'tzinfo/format2/country_index_definer'
|
||||
require_relative 'tzinfo/format2/country_index_definition'
|
||||
require_relative 'tzinfo/format2/timezone_definer'
|
||||
require_relative 'tzinfo/format2/timezone_definition'
|
||||
require_relative 'tzinfo/format2/timezone_index_definer'
|
||||
require_relative 'tzinfo/format2/timezone_index_definition'
|
||||
|
||||
require_relative 'tzinfo/format1'
|
||||
require_relative 'tzinfo/format1/country_definer'
|
||||
require_relative 'tzinfo/format1/country_index_definition'
|
||||
require_relative 'tzinfo/format1/timezone_definer'
|
||||
require_relative 'tzinfo/format1/timezone_definition'
|
||||
require_relative 'tzinfo/format1/timezone_index_definition'
|
||||
@ -1,71 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
# A set of rules that define when transitions occur in time zones with
|
||||
# annually occurring daylight savings time.
|
||||
#
|
||||
# @private
|
||||
class AnnualRules #:nodoc:
|
||||
# @return [TimezoneOffset] the standard offset that applies when daylight
|
||||
# savings time is not in force.
|
||||
attr_reader :std_offset
|
||||
|
||||
# @return [TimezoneOffset] the offset that applies when daylight savings
|
||||
# time is in force.
|
||||
attr_reader :dst_offset
|
||||
|
||||
# @return [TransitionRule] the rule that determines when daylight savings
|
||||
# time starts.
|
||||
attr_reader :dst_start_rule
|
||||
|
||||
# @return [TransitionRule] the rule that determines when daylight savings
|
||||
# time ends.
|
||||
attr_reader :dst_end_rule
|
||||
|
||||
# Initializes a new {AnnualRules} instance.
|
||||
#
|
||||
# @param std_offset [TimezoneOffset] the standard offset that applies when
|
||||
# daylight savings time is not in force.
|
||||
# @param dst_offset [TimezoneOffset] the offset that applies when daylight
|
||||
# savings time is in force.
|
||||
# @param dst_start_rule [TransitionRule] the rule that determines when
|
||||
# daylight savings time starts.
|
||||
# @param dst_end_rule [TransitionRule] the rule that determines when daylight
|
||||
# savings time ends.
|
||||
def initialize(std_offset, dst_offset, dst_start_rule, dst_end_rule)
|
||||
@std_offset = std_offset
|
||||
@dst_offset = dst_offset
|
||||
@dst_start_rule = dst_start_rule
|
||||
@dst_end_rule = dst_end_rule
|
||||
end
|
||||
|
||||
# Returns the transitions between standard and daylight savings time for a
|
||||
# given year. The results are ordered by time of occurrence (earliest to
|
||||
# latest).
|
||||
#
|
||||
# @param year [Integer] the year to calculate transitions for.
|
||||
# @return [Array<TimezoneTransition>] the transitions for the year.
|
||||
def transitions(year)
|
||||
start_dst = apply_rule(@dst_start_rule, @std_offset, @dst_offset, year)
|
||||
end_dst = apply_rule(@dst_end_rule, @dst_offset, @std_offset, year)
|
||||
|
||||
end_dst.timestamp_value < start_dst.timestamp_value ? [end_dst, start_dst] : [start_dst, end_dst]
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Applies a given rule between offsets on a year.
|
||||
#
|
||||
# @param rule [TransitionRule] the rule to apply.
|
||||
# @param from_offset [TimezoneOffset] the offset the rule transitions from.
|
||||
# @param to_offset [TimezoneOffset] the offset the rule transitions to.
|
||||
# @param year [Integer] the year when the transition occurs.
|
||||
# @return [TimezoneTransition] the transition determined by the rule.
|
||||
def apply_rule(rule, from_offset, to_offset, year)
|
||||
at = rule.at(from_offset, year)
|
||||
TimezoneTransition.new(to_offset, from_offset, at.value)
|
||||
end
|
||||
end
|
||||
private_constant :AnnualRules
|
||||
end
|
||||
@ -1,208 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
# {InvalidCountryCode} is raised by {Country#get} if the code given is not a
|
||||
# valid ISO 3166-1 alpha-2 code.
|
||||
class InvalidCountryCode < StandardError
|
||||
end
|
||||
|
||||
# The {Country} class represents an ISO 3166-1 country. It can be used to
|
||||
# obtain a list of time zones observed by a country. For example:
|
||||
#
|
||||
# united_states = Country.get('US')
|
||||
# united_states.zone_identifiers
|
||||
# united_states.zones
|
||||
# united_states.zone_info
|
||||
#
|
||||
# The {Country} class is thread-safe. It is safe to use class and instance
|
||||
# methods of {Country} in concurrently executing threads. Instances of
|
||||
# {Country} can be shared across thread boundaries.
|
||||
#
|
||||
# Country information available through TZInfo is intended as an aid for
|
||||
# users, to help them select time zone data appropriate for their practical
|
||||
# needs. It is not intended to take or endorse any position on legal or
|
||||
# territorial claims.
|
||||
class Country
|
||||
include Comparable
|
||||
|
||||
class << self
|
||||
# Gets a {Country} by its ISO 3166-1 alpha-2 code.
|
||||
#
|
||||
# The {Country.all_codes} method can be used to obtain a list of valid ISO
|
||||
# 3166-1 alpha-2 codes.
|
||||
#
|
||||
# @param code [String] An ISO 3166-1 alpha-2 code.
|
||||
# @return [Country] a {Country} instance representing the ISO-3166-1
|
||||
# country identified by the `code` parameter.
|
||||
# @raise [InvalidCountryCode] If {code} is not a valid ISO 3166-1 alpha-2
|
||||
# code it couldn't be found.
|
||||
def get(code)
|
||||
Country.new(data_source.get_country_info(code))
|
||||
end
|
||||
|
||||
# @return [Array<String>] an `Array` containing all the valid ISO 3166-1
|
||||
# alpha-2 country codes.
|
||||
def all_codes
|
||||
data_source.country_codes
|
||||
end
|
||||
|
||||
# @return [Array<Country>] an `Array` containing one {Country} instance
|
||||
# for each defined country.
|
||||
def all
|
||||
data_source.country_codes.collect {|code| get(code)}
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# @return [DataSource] the current DataSource.
|
||||
def data_source
|
||||
DataSource.get
|
||||
end
|
||||
end
|
||||
|
||||
# Initializes a new {Country} based upon a {DataSources::CountryInfo}
|
||||
# instance.
|
||||
#
|
||||
# {Country} instances should not normally be constructed directly. Use
|
||||
# the {Country.get} method to obtain instances instead.
|
||||
#
|
||||
# @param info [DataSources::CountryInfo] the data to base the new {Country}
|
||||
# instance upon.
|
||||
def initialize(info)
|
||||
@info = info
|
||||
end
|
||||
|
||||
# @return [String] the ISO 3166-1 alpha-2 country code.
|
||||
def code
|
||||
@info.code
|
||||
end
|
||||
|
||||
# @return [String] the name of the country.
|
||||
def name
|
||||
@info.name
|
||||
end
|
||||
|
||||
# @return [String] a `String` representation of this {Country} (the name of
|
||||
# the country).
|
||||
def to_s
|
||||
name
|
||||
end
|
||||
|
||||
# @return [String] the internal object state as a programmer-readable
|
||||
# `String`.
|
||||
def inspect
|
||||
"#<#{self.class}: #{@info.code}>"
|
||||
end
|
||||
|
||||
# Returns an `Array` containing the identifier for each time zone observed
|
||||
# by the country. These are in an order that
|
||||
#
|
||||
# 1. makes some geographical sense, and
|
||||
# 2. puts the most populous zones first, where that does not contradict 1.
|
||||
#
|
||||
# Returned zone identifiers may refer to cities and regions outside of the
|
||||
# country. This will occur if the zone covers multiple countries. Any zones
|
||||
# referring to a city or region in a different country will be listed after
|
||||
# those relating to this country.
|
||||
#
|
||||
# @return [Array<String>] an `Array` containing the identifier for each time
|
||||
# zone observed by the country
|
||||
def zone_identifiers
|
||||
zone_info.map(&:identifier)
|
||||
end
|
||||
alias zone_names zone_identifiers
|
||||
|
||||
# Returns An `Array` containing a {Timezone} instance for each time zone
|
||||
# observed by the country. These are in an order that
|
||||
#
|
||||
# 1. makes some geographical sense, and
|
||||
# 2. puts the most populous zones first, where that does not contradict 1.
|
||||
#
|
||||
# The identifiers of the time zones returned may refer to cities and regions
|
||||
# outside of the country. This will occur if the time zone covers multiple
|
||||
# countries. Any zones referring to a city or region in a different country
|
||||
# will be listed after those relating to this country.
|
||||
#
|
||||
# The results are actually instances of {TimezoneProxy} in order to defer
|
||||
# loading of the time zone transition data until it is first needed.
|
||||
#
|
||||
# @return [Array<Timezone>] an `Array` containing a {Timezone} instance for
|
||||
# each time zone observed by the country.
|
||||
def zones
|
||||
zone_info.map(&:timezone)
|
||||
end
|
||||
|
||||
# Returns a frozen `Array` containing a {CountryTimezone} instance for each
|
||||
# time zone observed by the country. These are in an order that
|
||||
#
|
||||
# 1. makes some geographical sense, and
|
||||
# 2. puts the most populous zones first, where that does not contradict 1.
|
||||
#
|
||||
# The {CountryTimezone} instances can be used to obtain the location and
|
||||
# descriptions of the observed time zones.
|
||||
#
|
||||
# Identifiers and descriptions of the time zones returned may refer to
|
||||
# cities and regions outside of the country. This will occur if the time
|
||||
# zone covers multiple countries. Any zones referring to a city or region in
|
||||
# a different country will be listed after those relating to this country.
|
||||
#
|
||||
# @return [Array<CountryTimezone>] a frozen `Array` containing a
|
||||
# {CountryTimezone} instance for each time zone observed by the country.
|
||||
def zone_info
|
||||
@info.zones
|
||||
end
|
||||
|
||||
# Compares this {Country} with another based on their {code}.
|
||||
#
|
||||
# @param c [Object] an `Object` to compare this {Country} with.
|
||||
# @return [Integer] -1 if `c` is less than `self`, 0 if `c` is equal to
|
||||
# `self` and +1 if `c` is greater than `self`, or `nil` if `c` is not an
|
||||
# instance of {Country}.
|
||||
def <=>(c)
|
||||
return nil unless c.is_a?(Country)
|
||||
code <=> c.code
|
||||
end
|
||||
|
||||
# @param c [Object] an `Object` to compare this {Country} with.
|
||||
# @return [Boolean] `true` if `c` is an instance of {Country} and has the
|
||||
# same code as `self`, otherwise `false`.
|
||||
def eql?(c)
|
||||
self == c
|
||||
end
|
||||
|
||||
# @return [Integer] a hash based on the {code}.
|
||||
def hash
|
||||
code.hash
|
||||
end
|
||||
|
||||
# Matches `regexp` against the {code} of this {Country}.
|
||||
#
|
||||
# @param regexp [Regexp] a `Regexp` to match against the {code} of
|
||||
# this {Country}.
|
||||
# @return [Integer] the position the match starts, or `nil` if there is no
|
||||
# match.
|
||||
def =~(regexp)
|
||||
regexp =~ code
|
||||
end
|
||||
|
||||
# Returns a serialized representation of this {Country}. This method is
|
||||
# called when using `Marshal.dump` with an instance of {Country}.
|
||||
#
|
||||
# @param limit [Integer] the maximum depth to dump - ignored.
|
||||
# @return [String] a serialized representation of this {Country}.
|
||||
def _dump(limit)
|
||||
code
|
||||
end
|
||||
|
||||
# Loads a {Country} from the serialized representation returned by {_dump}.
|
||||
# This is method is called when using `Marshal.load` or `Marshal.restore`
|
||||
# to restore a serialized {Country}.
|
||||
#
|
||||
# @param data [String] a serialized representation of a {Country}.
|
||||
# @return [Country] the result of converting `data` back into a {Country}.
|
||||
def self._load(data)
|
||||
Country.get(data)
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,93 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
|
||||
module TZInfo
|
||||
# Information about a time zone used by a {Country}.
|
||||
class CountryTimezone
|
||||
# @return [String] the identifier of the {Timezone} being described.
|
||||
attr_reader :identifier
|
||||
|
||||
# The latitude of this time zone in degrees. Positive numbers are degrees
|
||||
# north and negative numbers are degrees south.
|
||||
#
|
||||
# Note that depending on the data source, the position given by {#latitude}
|
||||
# and {#longitude} may not be within the country.
|
||||
#
|
||||
# @return [Rational] the latitude in degrees.
|
||||
attr_reader :latitude
|
||||
|
||||
# The longitude of this time zone in degrees. Positive numbers are degrees
|
||||
# east and negative numbers are degrees west.
|
||||
#
|
||||
# Note that depending on the data source, the position given by {#latitude}
|
||||
# and {#longitude} may not be within the country.
|
||||
#
|
||||
# @return [Rational] the longitude in degrees.
|
||||
attr_reader :longitude
|
||||
|
||||
# A description of this time zone in relation to the country, e.g. "Eastern
|
||||
# Time". This is usually `nil` for countries that have a single time zone.
|
||||
#
|
||||
# @return [String] an optional description of the time zone.
|
||||
attr_reader :description
|
||||
|
||||
# Creates a new {CountryTimezone}.
|
||||
#
|
||||
# The passed in identifier and description instances will be frozen.
|
||||
#
|
||||
# {CountryTimezone} instances should normally only be constructed
|
||||
# by implementations of {DataSource}.
|
||||
#
|
||||
# @param identifier [String] the {Timezone} identifier.
|
||||
# @param latitude [Rational] the latitude of the time zone.
|
||||
# @param longitude [Rational] the longitude of the time zone.
|
||||
# @param description [String] an optional description of the time zone.
|
||||
def initialize(identifier, latitude, longitude, description = nil)
|
||||
@identifier = identifier.freeze
|
||||
@latitude = latitude
|
||||
@longitude = longitude
|
||||
@description = description && description.freeze
|
||||
end
|
||||
|
||||
# Returns the associated {Timezone}.
|
||||
#
|
||||
# The result is actually an instance of {TimezoneProxy} in order to defer
|
||||
# loading of the time zone transition data until it is first needed.
|
||||
#
|
||||
# @return [Timezone] the associated {Timezone}.
|
||||
def timezone
|
||||
Timezone.get_proxy(@identifier)
|
||||
end
|
||||
|
||||
# @return [String] the {description} if present, otherwise a human-readable
|
||||
# representation of the identifier (using {Timezone#friendly_identifier}).
|
||||
def description_or_friendly_identifier
|
||||
description || timezone.friendly_identifier(true)
|
||||
end
|
||||
|
||||
# Tests if the given object is equal to the current instance (has the same
|
||||
# identifier, latitude, longitude and description).
|
||||
#
|
||||
# @param ct [Object] the object to be compared.
|
||||
# @return [TrueClass] `true` if `ct` is equal to the current instance.
|
||||
def ==(ct)
|
||||
ct.kind_of?(CountryTimezone) &&
|
||||
identifier == ct.identifier && latitude == ct.latitude &&
|
||||
longitude == ct.longitude && description == ct.description
|
||||
end
|
||||
|
||||
# Tests if the given object is equal to the current instance (has the same
|
||||
# identifier, latitude, longitude and description).
|
||||
#
|
||||
# @param ct [Object] the object to be compared.
|
||||
# @return [Boolean] `true` if `ct` is equal to the current instance.
|
||||
def eql?(ct)
|
||||
self == ct
|
||||
end
|
||||
|
||||
# @return [Integer] a hash based on the {identifier}, {latitude},
|
||||
# {longitude} and {description}.
|
||||
def hash
|
||||
[@identifier, @latitude, @longitude, @description].hash
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,446 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'concurrent'
|
||||
require 'thread'
|
||||
|
||||
module TZInfo
|
||||
# {InvalidDataSource} is raised if the selected {DataSource} doesn't implement
|
||||
# one of the required methods.
|
||||
class InvalidDataSource < StandardError
|
||||
end
|
||||
|
||||
# {DataSourceNotFound} is raised if no data source could be found (i.e. if
|
||||
# `'tzinfo/data'` cannot be found on the load path and no valid zoneinfo
|
||||
# directory can be found on the system).
|
||||
class DataSourceNotFound < StandardError
|
||||
end
|
||||
|
||||
# TZInfo can be used with different data sources for time zone and country
|
||||
# data. Each source of data is implemented as a subclass of {DataSource}.
|
||||
#
|
||||
# To choose a data source and override the default selection, use the
|
||||
# {DataSource.set} method.
|
||||
#
|
||||
# @abstract To create a custom data source, create a subclass of {DataSource}
|
||||
# and implement the {load_timezone_info}, {data_timezone_identifiers},
|
||||
# {linked_timezone_identifiers}, {load_country_info} and {country_codes}
|
||||
# methods.
|
||||
class DataSource
|
||||
# The currently selected data source.
|
||||
#
|
||||
# @private
|
||||
@@instance = nil
|
||||
|
||||
# A `Mutex` used to ensure the default data source is only created once.
|
||||
#
|
||||
# @private
|
||||
@@default_mutex = Mutex.new
|
||||
|
||||
class << self
|
||||
# @return [DataSource] the currently selected source of data.
|
||||
def get
|
||||
# If a DataSource hasn't been manually set when the first request is
|
||||
# made to obtain a DataSource, then a default data source is created.
|
||||
#
|
||||
# This is done at the first request rather than when TZInfo is loaded to
|
||||
# avoid unnecessary attempts to find a suitable DataSource.
|
||||
#
|
||||
# A `Mutex` is used to ensure that only a single default instance is
|
||||
# created (this avoiding the possibility of retaining two copies of the
|
||||
# same data in memory).
|
||||
|
||||
unless @@instance
|
||||
@@default_mutex.synchronize do
|
||||
set(create_default_data_source) unless @@instance
|
||||
end
|
||||
end
|
||||
|
||||
@@instance
|
||||
end
|
||||
|
||||
# Sets the currently selected data source for time zone and country data.
|
||||
#
|
||||
# This should usually be set to one of the two standard data source types:
|
||||
#
|
||||
# * `:ruby` - read data from the Ruby modules included in the TZInfo::Data
|
||||
# library (tzinfo-data gem).
|
||||
# * `:zoneinfo` - read data from the zoneinfo files included with most
|
||||
# Unix-like operating systems (e.g. in /usr/share/zoneinfo).
|
||||
#
|
||||
# To set TZInfo to use one of the standard data source types, call
|
||||
# `TZInfo::DataSource.set`` in one of the following ways:
|
||||
#
|
||||
# TZInfo::DataSource.set(:ruby)
|
||||
# TZInfo::DataSource.set(:zoneinfo)
|
||||
# TZInfo::DataSource.set(:zoneinfo, zoneinfo_dir)
|
||||
# TZInfo::DataSource.set(:zoneinfo, zoneinfo_dir, iso3166_tab_file)
|
||||
#
|
||||
# `DataSource.set(:zoneinfo)` will automatically search for the zoneinfo
|
||||
# directory by checking the paths specified in
|
||||
# {DataSources::ZoneinfoDataSource.search_path}.
|
||||
# {DataSources::ZoneinfoDirectoryNotFound} will be raised if no valid
|
||||
# zoneinfo directory could be found.
|
||||
#
|
||||
# `DataSource.set(:zoneinfo, zoneinfo_dir)` uses the specified
|
||||
# `zoneinfo_dir` directory as the data source. If the directory is not a
|
||||
# valid zoneinfo directory, a {DataSources::InvalidZoneinfoDirectory}
|
||||
# exception will be raised.
|
||||
#
|
||||
# `DataSource.set(:zoneinfo, zoneinfo_dir, iso3166_tab_file)` uses the
|
||||
# specified `zoneinfo_dir` directory as the data source, but loads the
|
||||
# `iso3166.tab` file from the path given by `iso3166_tab_file`. If the
|
||||
# directory is not a valid zoneinfo directory, a
|
||||
# {DataSources::InvalidZoneinfoDirectory} exception will be raised.
|
||||
#
|
||||
# Custom data sources can be created by subclassing TZInfo::DataSource and
|
||||
# implementing the following methods:
|
||||
#
|
||||
# * {load_timezone_info}
|
||||
# * {data_timezone_identifiers}
|
||||
# * {linked_timezone_identifiers}
|
||||
# * {load_country_info}
|
||||
# * {country_codes}
|
||||
#
|
||||
# To have TZInfo use the custom data source, call {DataSource.set},
|
||||
# passing an instance of the custom data source implementation as follows:
|
||||
#
|
||||
# TZInfo::DataSource.set(CustomDataSource.new)
|
||||
#
|
||||
# Calling {DataSource.set} will only affect instances of {Timezone} and
|
||||
# {Country} obtained with {Timezone.get} and {Country.get} subsequent to
|
||||
# the {DataSource.set} call. Existing {Timezone} and {Country} instances
|
||||
# will be unaffected.
|
||||
#
|
||||
# If {DataSource.set} is not called, TZInfo will by default attempt to use
|
||||
# TZInfo::Data as the data source. If TZInfo::Data is not available (i.e.
|
||||
# if `require 'tzinfo/data'` fails), then TZInfo will search for a
|
||||
# zoneinfo directory instead (using the search path specified by
|
||||
# {DataSources::ZoneinfoDataSource.search_path}).
|
||||
#
|
||||
# @param data_source_or_type [Object] either `:ruby`, `:zoneinfo` or an
|
||||
# instance of a {DataSource}.
|
||||
# @param args [Array<Object>] when `data_source_or_type` is a symbol,
|
||||
# optional arguments to use when initializing the data source.
|
||||
# @raise [ArgumentError] if `data_source_or_type` is not `:ruby`,
|
||||
# `:zoneinfo` or an instance of {DataSource}.
|
||||
def set(data_source_or_type, *args)
|
||||
if data_source_or_type.kind_of?(DataSource)
|
||||
@@instance = data_source_or_type
|
||||
elsif data_source_or_type == :ruby
|
||||
@@instance = DataSources::RubyDataSource.new
|
||||
elsif data_source_or_type == :zoneinfo
|
||||
@@instance = DataSources::ZoneinfoDataSource.new(*args)
|
||||
else
|
||||
raise ArgumentError, 'data_source_or_type must be a DataSource instance or a data source type (:ruby or :zoneinfo)'
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Creates a {DataSource} instance for use as the default. Used if no
|
||||
# preference has been specified manually.
|
||||
#
|
||||
# @return [DataSource] the newly created default {DataSource} instance.
|
||||
def create_default_data_source
|
||||
has_tzinfo_data = false
|
||||
|
||||
begin
|
||||
require 'tzinfo/data'
|
||||
has_tzinfo_data = true
|
||||
rescue LoadError
|
||||
end
|
||||
|
||||
return DataSources::RubyDataSource.new if has_tzinfo_data
|
||||
|
||||
begin
|
||||
return DataSources::ZoneinfoDataSource.new
|
||||
rescue DataSources::ZoneinfoDirectoryNotFound
|
||||
raise DataSourceNotFound, "No source of timezone data could be found.\nPlease refer to https://tzinfo.github.io/datasourcenotfound for help resolving this error."
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Initializes a new {DataSource} instance. Typically only called via
|
||||
# subclasses of {DataSource}.
|
||||
def initialize
|
||||
@timezones = Concurrent::Map.new
|
||||
end
|
||||
|
||||
# Returns a {DataSources::TimezoneInfo} instance for the given identifier.
|
||||
# The result will derive from either {DataSources::DataTimezoneInfo} for
|
||||
# time zones that define their own data or {DataSources::LinkedTimezoneInfo}
|
||||
# for links or aliases to other time zones.
|
||||
#
|
||||
# {get_timezone_info} calls {load_timezone_info} to create the
|
||||
# {DataSources::TimezoneInfo} instance. The returned instance is cached and
|
||||
# returned in subsequent calls to {get_timezone_info} for the identifier.
|
||||
#
|
||||
# @param identifier [String] A time zone identifier.
|
||||
# @return [DataSources::TimezoneInfo] a {DataSources::TimezoneInfo} instance
|
||||
# for a given identifier.
|
||||
# @raise [InvalidTimezoneIdentifier] if the time zone is not found or the
|
||||
# identifier is invalid.
|
||||
def get_timezone_info(identifier)
|
||||
result = @timezones[identifier]
|
||||
|
||||
unless result
|
||||
# Thread-safety: It is possible that multiple equivalent TimezoneInfo
|
||||
# instances could be created here in concurrently executing threads. The
|
||||
# consequences of this are that the data may be loaded more than once
|
||||
# (depending on the data source). The performance benefit of ensuring
|
||||
# that only a single instance is created is unlikely to be worth the
|
||||
# overhead of only allowing one TimezoneInfo to be loaded at a time.
|
||||
|
||||
result = load_timezone_info(identifier)
|
||||
@timezones[result.identifier] = result
|
||||
end
|
||||
|
||||
result
|
||||
end
|
||||
|
||||
# @return [Array<String>] a frozen `Array`` of all the available time zone
|
||||
# identifiers. The identifiers are sorted according to `String#<=>`.
|
||||
def timezone_identifiers
|
||||
# Thread-safety: It is possible that the value of @timezone_identifiers
|
||||
# may be calculated multiple times in concurrently executing threads. It
|
||||
# is not worth the overhead of locking to ensure that
|
||||
# @timezone_identifiers is only calculated once.
|
||||
@timezone_identifiers ||= build_timezone_identifiers
|
||||
end
|
||||
|
||||
# Returns a frozen `Array` of all the available time zone identifiers for
|
||||
# data time zones (i.e. those that actually contain definitions). The
|
||||
# identifiers are sorted according to `String#<=>`.
|
||||
#
|
||||
# @return [Array<String>] a frozen `Array` of all the available time zone
|
||||
# identifiers for data time zones.
|
||||
def data_timezone_identifiers
|
||||
raise_invalid_data_source('data_timezone_identifiers')
|
||||
end
|
||||
|
||||
# Returns a frozen `Array` of all the available time zone identifiers that
|
||||
# are links to other time zones. The identifiers are sorted according to
|
||||
# `String#<=>`.
|
||||
#
|
||||
# @return [Array<String>] a frozen `Array` of all the available time zone
|
||||
# identifiers that are links to other time zones.
|
||||
def linked_timezone_identifiers
|
||||
raise_invalid_data_source('linked_timezone_identifiers')
|
||||
end
|
||||
|
||||
# @param code [String] an ISO 3166-1 alpha-2 country code.
|
||||
# @return [DataSources::CountryInfo] a {DataSources::CountryInfo} instance
|
||||
# for the given ISO 3166-1 alpha-2 country code.
|
||||
# @raise [InvalidCountryCode] if the country could not be found or the code
|
||||
# is invalid.
|
||||
def get_country_info(code)
|
||||
load_country_info(code)
|
||||
end
|
||||
|
||||
# Returns a frozen `Array` of all the available ISO 3166-1 alpha-2 country
|
||||
# codes. The identifiers are sorted according to `String#<=>`.
|
||||
#
|
||||
# @return [Array<String>] a frozen `Array` of all the available ISO 3166-1
|
||||
# alpha-2 country codes.
|
||||
def country_codes
|
||||
raise_invalid_data_source('country_codes')
|
||||
end
|
||||
|
||||
# Loads all timezone and country data into memory.
|
||||
#
|
||||
# This may be desirable in production environments to improve copy-on-write
|
||||
# performance and to avoid flushing the constant cache every time a new
|
||||
# timezone or country is loaded from {DataSources::RubyDataSource}.
|
||||
def eager_load!
|
||||
timezone_identifiers.each {|identifier| load_timezone_info(identifier) }
|
||||
country_codes.each {|code| load_country_info(code) }
|
||||
nil
|
||||
end
|
||||
|
||||
# @return [String] a description of the {DataSource}.
|
||||
def to_s
|
||||
"Default DataSource"
|
||||
end
|
||||
|
||||
# @return [String] the internal object state as a programmer-readable
|
||||
# `String`.
|
||||
def inspect
|
||||
"#<#{self.class}>"
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
# Returns a {DataSources::TimezoneInfo} instance for the given time zone
|
||||
# identifier. The result should derive from either
|
||||
# {DataSources::DataTimezoneInfo} for time zones that define their own data
|
||||
# or {DataSources::LinkedTimezoneInfo} for links to or aliases for other
|
||||
# time zones.
|
||||
#
|
||||
# @param identifier [String] A time zone identifier.
|
||||
# @return [DataSources::TimezoneInfo] a {DataSources::TimezoneInfo} instance
|
||||
# for the given time zone identifier.
|
||||
# @raise [InvalidTimezoneIdentifier] if the time zone is not found or the
|
||||
# identifier is invalid.
|
||||
def load_timezone_info(identifier)
|
||||
raise_invalid_data_source('load_timezone_info')
|
||||
end
|
||||
|
||||
# @param code [String] an ISO 3166-1 alpha-2 country code.
|
||||
# @return [DataSources::CountryInfo] a {DataSources::CountryInfo} instance
|
||||
# for the given ISO 3166-1 alpha-2 country code.
|
||||
# @raise [InvalidCountryCode] if the country could not be found or the code
|
||||
# is invalid.
|
||||
def load_country_info(code)
|
||||
raise_invalid_data_source('load_country_info')
|
||||
end
|
||||
|
||||
# @return [Encoding] the `Encoding` used by the `String` instances returned
|
||||
# by {data_timezone_identifiers} and {linked_timezone_identifiers}.
|
||||
def timezone_identifier_encoding
|
||||
Encoding::UTF_8
|
||||
end
|
||||
|
||||
# Checks that the given identifier is a valid time zone identifier (can be
|
||||
# found in the {timezone_identifiers} `Array`). If the identifier is valid,
|
||||
# the `String` instance representing that identifier from
|
||||
# `timezone_identifiers` is returned. Otherwise an
|
||||
# {InvalidTimezoneIdentifier} exception is raised.
|
||||
#
|
||||
# @param identifier [String] a time zone identifier to be validated.
|
||||
# @return [String] the `String` instance equivalent to `identifier` from
|
||||
# {timezone_identifiers}.
|
||||
# @raise [InvalidTimezoneIdentifier] if `identifier` was not found in
|
||||
# {timezone_identifiers}.
|
||||
def validate_timezone_identifier(identifier)
|
||||
raise InvalidTimezoneIdentifier, "Invalid identifier: #{identifier.nil? ? 'nil' : identifier}" unless identifier.kind_of?(String)
|
||||
|
||||
valid_identifier = try_with_encoding(identifier, timezone_identifier_encoding) {|id| find_timezone_identifier(id) }
|
||||
return valid_identifier if valid_identifier
|
||||
|
||||
raise InvalidTimezoneIdentifier, "Invalid identifier: #{identifier.encode(Encoding::UTF_8)}"
|
||||
end
|
||||
|
||||
# Looks up a given code in the given hash of code to
|
||||
# {DataSources::CountryInfo} mappings. If the code is found the
|
||||
# {DataSources::CountryInfo} is returned. Otherwise an {InvalidCountryCode}
|
||||
# exception is raised.
|
||||
#
|
||||
# @param hash [String, DataSources::CountryInfo] a mapping from ISO 3166-1
|
||||
# alpha-2 country codes to {DataSources::CountryInfo} instances.
|
||||
# @param code [String] a country code to lookup.
|
||||
# @param encoding [Encoding] the encoding used for the country codes in
|
||||
# `hash`.
|
||||
# @return [DataSources::CountryInfo] the {DataSources::CountryInfo} instance
|
||||
# corresponding to `code`.
|
||||
# @raise [InvalidCountryCode] if `code` was not found in `hash`.
|
||||
def lookup_country_info(hash, code, encoding = Encoding::UTF_8)
|
||||
raise InvalidCountryCode, "Invalid country code: #{code.nil? ? 'nil' : code}" unless code.kind_of?(String)
|
||||
|
||||
info = try_with_encoding(code, encoding) {|c| hash[c] }
|
||||
return info if info
|
||||
|
||||
raise InvalidCountryCode, "Invalid country code: #{code.encode(Encoding::UTF_8)}"
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Raises {InvalidDataSource} to indicate that a method has not been
|
||||
# overridden by a particular data source implementation.
|
||||
#
|
||||
# @raise [InvalidDataSource] always.
|
||||
def raise_invalid_data_source(method_name)
|
||||
raise InvalidDataSource, "#{method_name} not defined"
|
||||
end
|
||||
|
||||
# Combines {data_timezone_identifiers} and {linked_timezone_identifiers}
|
||||
# to create an `Array` containing all valid time zone identifiers. If
|
||||
# {linked_timezone_identifiers} is empty, the {data_timezone_identifiers}
|
||||
# instance is returned.
|
||||
#
|
||||
# The returned `Array` is frozen. The identifiers are sorted according to
|
||||
# `String#<=>`.
|
||||
#
|
||||
# @return [Array<String>] an `Array` containing all valid time zone
|
||||
# identifiers.
|
||||
def build_timezone_identifiers
|
||||
data = data_timezone_identifiers
|
||||
linked = linked_timezone_identifiers
|
||||
linked.empty? ? data : (data + linked).sort!.freeze
|
||||
end
|
||||
|
||||
if [].respond_to?(:bsearch)
|
||||
# If the given `identifier` is contained within the {timezone_identifiers}
|
||||
# `Array`, the `String` instance representing that identifier from
|
||||
# {timezone_identifiers} is returned. Otherwise, `nil` is returned.
|
||||
#
|
||||
# @param identifier [String] A time zone identifier to search for.
|
||||
# @return [String] the `String` instance representing `identifier` from
|
||||
# {timezone_identifiers} if found, or `nil` if not found.
|
||||
#
|
||||
# :nocov_no_array_bsearch:
|
||||
def find_timezone_identifier(identifier)
|
||||
|
||||
result = timezone_identifiers.bsearch {|i| i >= identifier }
|
||||
result == identifier ? result : nil
|
||||
end
|
||||
# :nocov_no_array_bsearch:
|
||||
else
|
||||
# If the given `identifier` is contained within the {timezone_identifiers}
|
||||
# `Array`, the `String` instance representing that identifier from
|
||||
# {timezone_identifiers} is returned. Otherwise, `nil` is returned.
|
||||
#
|
||||
# @param identifier [String] A time zone identifier to search for.
|
||||
# @return [String] the `String` instance representing `identifier` from
|
||||
# {timezone_identifiers} if found, or `nil` if not found.
|
||||
#
|
||||
# :nocov_array_bsearch:
|
||||
def find_timezone_identifier(identifier)
|
||||
identifiers = timezone_identifiers
|
||||
low = 0
|
||||
high = identifiers.length
|
||||
|
||||
while low < high do
|
||||
mid = (low + high).div(2)
|
||||
mid_identifier = identifiers[mid]
|
||||
cmp = mid_identifier <=> identifier
|
||||
|
||||
return mid_identifier if cmp == 0
|
||||
|
||||
if cmp > 0
|
||||
high = mid
|
||||
else
|
||||
low = mid + 1
|
||||
end
|
||||
end
|
||||
|
||||
nil
|
||||
end
|
||||
# :nocov_array_bsearch:
|
||||
end
|
||||
|
||||
# Tries an operation using `string` directly. If the operation fails, the
|
||||
# string is copied and encoded with `encoding` and the operation is tried
|
||||
# again.
|
||||
#
|
||||
# @param string [String] The `String` to perform the operation on.
|
||||
# @param encoding [Encoding] The `Encoding` to use if the initial attempt
|
||||
# fails.
|
||||
# @yield [s] the caller will be yielded to once or twice to attempt the
|
||||
# operation.
|
||||
# @yieldparam s [String] either `string` or an encoded copy of `string`.
|
||||
# @yieldreturn [Object] The result of the operation. Must be truthy if
|
||||
# successful.
|
||||
# @return [Object] the result of the operation or `nil` if the first attempt
|
||||
# fails and `string` is already encoded with `encoding`.
|
||||
def try_with_encoding(string, encoding)
|
||||
result = yield string
|
||||
return result if result
|
||||
|
||||
unless encoding == string.encoding
|
||||
string = string.encode(encoding)
|
||||
yield string
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,8 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
|
||||
module TZInfo
|
||||
# {DataSource} implementations and classes used by {DataSource}
|
||||
# implementations.
|
||||
module DataSources
|
||||
end
|
||||
end
|
||||
@ -1,56 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
module DataSources
|
||||
# Represents a data time zone defined by a constantly observed offset.
|
||||
class ConstantOffsetDataTimezoneInfo < DataTimezoneInfo
|
||||
# @return [TimezoneOffset] the offset that is constantly observed.
|
||||
attr_reader :constant_offset
|
||||
|
||||
# Initializes a new {ConstantOffsetDataTimezoneInfo}.
|
||||
#
|
||||
# The passed in `identifier` instance will be frozen. A reference to the
|
||||
# passed in {TimezoneOffset} will be retained.
|
||||
#
|
||||
# @param identifier [String] the identifier of the time zone.
|
||||
# @param constant_offset [TimezoneOffset] the constantly observed offset.
|
||||
# @raise [ArgumentError] if `identifier` or `constant_offset` is `nil`.
|
||||
def initialize(identifier, constant_offset)
|
||||
super(identifier)
|
||||
raise ArgumentError, 'constant_offset must be specified' unless constant_offset
|
||||
@constant_offset = constant_offset
|
||||
end
|
||||
|
||||
# @param timestamp [Timestamp] ignored.
|
||||
# @return [TimezonePeriod] an unbounded {TimezonePeriod} for the time
|
||||
# zone's constantly observed offset.
|
||||
def period_for(timestamp)
|
||||
constant_period
|
||||
end
|
||||
|
||||
# @param local_timestamp [Timestamp] ignored.
|
||||
# @return [Array<TimezonePeriod>] an `Array` containing a single unbounded
|
||||
# {TimezonePeriod} for the time zone's constantly observed offset.
|
||||
def periods_for_local(local_timestamp)
|
||||
[constant_period]
|
||||
end
|
||||
|
||||
# @param to_timestamp [Timestamp] ignored.
|
||||
# @param from_timestamp [Timestamp] ignored.
|
||||
# @return [Array] an empty `Array`, since there are no transitions in time
|
||||
# zones that observe a constant offset.
|
||||
def transitions_up_to(to_timestamp, from_timestamp = nil)
|
||||
[]
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# @return [TimezonePeriod] an unbounded {TimezonePeriod} with the constant
|
||||
# offset of this timezone.
|
||||
def constant_period
|
||||
OffsetTimezonePeriod.new(@constant_offset)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,42 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
module DataSources
|
||||
# Represents a country and references to its time zones as returned by a
|
||||
# {DataSource}.
|
||||
class CountryInfo
|
||||
# @return [String] the ISO 3166-1 alpha-2 country code.
|
||||
attr_reader :code
|
||||
|
||||
# @return [String] the name of the country.
|
||||
attr_reader :name
|
||||
|
||||
# @return [Array<CountryTimezone>] the time zones observed in the country.
|
||||
attr_reader :zones
|
||||
|
||||
# Initializes a new {CountryInfo}. The passed in `code`, `name` and
|
||||
# `zones` instances will be frozen.
|
||||
#
|
||||
# @param code [String] an ISO 3166-1 alpha-2 country code.
|
||||
# @param name [String] the name of the country.
|
||||
# @param zones [Array<CountryTimezone>] the time zones observed in the
|
||||
# country.
|
||||
# @raise [ArgumentError] if `code`, `name` or `zones` is `nil`.
|
||||
def initialize(code, name, zones)
|
||||
raise ArgumentError, 'code must be specified' unless code
|
||||
raise ArgumentError, 'name must be specified' unless name
|
||||
raise ArgumentError, 'zones must be specified' unless zones
|
||||
@code = code.freeze
|
||||
@name = name.freeze
|
||||
@zones = zones.freeze
|
||||
end
|
||||
|
||||
# @return [String] the internal object state as a programmer-readable
|
||||
# `String`.
|
||||
def inspect
|
||||
"#<#{self.class}: #@code>"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,91 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
module DataSources
|
||||
# The base class for time zones defined as either a series of transitions
|
||||
# ({TransitionsDataTimezoneInfo}) or a constantly observed offset
|
||||
# ({ConstantOffsetDataTimezoneInfo}).
|
||||
#
|
||||
# @abstract Data sources return instances of {DataTimezoneInfo} subclasses.
|
||||
class DataTimezoneInfo < TimezoneInfo
|
||||
# @param timestamp [Timestamp] a {Timestamp} with a specified
|
||||
# {Timestamp#utc_offset utc_offset}.
|
||||
# @return [TimezonePeriod] the {TimezonePeriod} observed at the time
|
||||
# specified by `timestamp`.
|
||||
# @raise [ArgumentError] may be raised if `timestamp` is `nil` or does not
|
||||
# have a specified {Timestamp#utc_offset utc_offset}.
|
||||
def period_for(timestamp)
|
||||
raise_not_implemented('period_for')
|
||||
end
|
||||
|
||||
# Returns an `Array` containing the {TimezonePeriod TimezonePeriods} that
|
||||
# could be observed at the local time specified by `local_timestamp`. The
|
||||
# results are are ordered by increasing UTC start date. An empty `Array`
|
||||
# is returned if no periods are found for the given local time.
|
||||
#
|
||||
# @param local_timestamp [Timestamp] a {Timestamp} representing a local
|
||||
# time - must have an unspecified {Timestamp#utc_offset utc_offset}.
|
||||
# @return [Array<TimezonePeriod>] an `Array` containing the
|
||||
# {TimezonePeriod TimezonePeriods} that could be observed at the local
|
||||
# time specified by `local_timestamp`.
|
||||
# @raise [ArgumentError] may be raised if `local_timestamp` is `nil`, or
|
||||
# has a specified {Timestamp#utc_offset utc_offset}.
|
||||
def periods_for_local(local_timestamp)
|
||||
raise_not_implemented('periods_for_local')
|
||||
end
|
||||
|
||||
# Returns an `Array` of {TimezoneTransition} instances representing the
|
||||
# times where the UTC offset of the time zone changes.
|
||||
#
|
||||
# Transitions are returned up to a given {Timestamp} (`to_timestamp`).
|
||||
#
|
||||
# A from {Timestamp} may also be supplied using the `from_timestamp`
|
||||
# parameter. If `from_timestamp` is specified, only transitions from that
|
||||
# time onwards will be returned.
|
||||
#
|
||||
# Comparisons with `to_timestamp` are exclusive. Comparisons with
|
||||
# `from_timestamp` are inclusive. If a transition falls precisely on
|
||||
# `to_timestamp`, it will be excluded. If a transition falls on
|
||||
# `from_timestamp`, it will be included.
|
||||
#
|
||||
# Transitions returned are ordered by when they occur, from earliest to
|
||||
# latest.
|
||||
#
|
||||
# @param to_timestamp [Timestamp] a {Timestamp} with a specified
|
||||
# {Timestamp#utc_offset utc_offset}. Transitions are returned if they
|
||||
# occur before this time.
|
||||
# @param from_timestamp [Timestamp] an optional {Timestamp} with a
|
||||
# specified {Timestamp#utc_offset utc_offset}. If specified, transitions
|
||||
# are returned if they occur at or after this time.
|
||||
# @return [Array<TimezoneTransition>] an `Array` of {TimezoneTransition}
|
||||
# instances representing the times where the UTC offset of the time zone
|
||||
# changes.
|
||||
# @raise [ArgumentError] may be raised if `to_timestamp` is `nil` or does
|
||||
# not have a specified {Timestamp#utc_offset utc_offset}.
|
||||
# @raise [ArgumentError] may be raised if `from_timestamp` is specified
|
||||
# but does not have a specified {Timestamp#utc_offset utc_offset}.
|
||||
# @raise [ArgumentError] may be raised if `from_timestamp` is specified
|
||||
# but is not earlier than or at the same time as `to_timestamp`.
|
||||
def transitions_up_to(to_timestamp, from_timestamp = nil)
|
||||
raise_not_implemented('transitions_up_to')
|
||||
end
|
||||
|
||||
# @return [DataTimezone] a new {DataTimezone} instance for the time zone
|
||||
# represented by this {DataTimezoneInfo}.
|
||||
def create_timezone
|
||||
DataTimezone.new(self)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Raises a {NotImplementedError} to indicate that the base class is
|
||||
# incorrectly being used directly.
|
||||
#
|
||||
# raise [NotImplementedError] always.
|
||||
def raise_not_implemented(method_name)
|
||||
raise NotImplementedError, "Subclasses must override #{method_name}"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,33 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
|
||||
module TZInfo
|
||||
module DataSources
|
||||
# Represents a time zone that is defined as a link to or alias of another
|
||||
# zone.
|
||||
class LinkedTimezoneInfo < TimezoneInfo
|
||||
# @return [String] the identifier of the time zone that provides the data
|
||||
# (that this zone links to or is an alias for).
|
||||
attr_reader :link_to_identifier
|
||||
|
||||
# Initializes a new {LinkedTimezoneInfo}. The passed in `identifier` and
|
||||
# `link_to_identifier` instances will be frozen.
|
||||
#
|
||||
# @param identifier [String] the identifier of the time zone.
|
||||
# @param link_to_identifier [String] the identifier of the time zone that
|
||||
# this zone link to.
|
||||
# @raise [ArgumentError] if `identifier` or `link_to_identifier` are
|
||||
# `nil`.
|
||||
def initialize(identifier, link_to_identifier)
|
||||
super(identifier)
|
||||
raise ArgumentError, 'link_to_identifier must be specified' unless link_to_identifier
|
||||
@link_to_identifier = link_to_identifier.freeze
|
||||
end
|
||||
|
||||
# @return [LinkedTimezone] a new {LinkedTimezone} instance for the time
|
||||
# zone represented by this {LinkedTimezoneInfo}.
|
||||
def create_timezone
|
||||
LinkedTimezone.new(self)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,177 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'strscan'
|
||||
|
||||
module TZInfo
|
||||
module DataSources
|
||||
# An {InvalidPosixTimeZone} exception is raised if an invalid POSIX-style
|
||||
# time zone string is encountered.
|
||||
#
|
||||
# @private
|
||||
class InvalidPosixTimeZone < StandardError #:nodoc:
|
||||
end
|
||||
private_constant :InvalidPosixTimeZone
|
||||
|
||||
# A parser for POSIX-style TZ strings used in zoneinfo files and specified
|
||||
# by tzfile.5 and tzset.3.
|
||||
#
|
||||
# @private
|
||||
class PosixTimeZoneParser #:nodoc:
|
||||
# Initializes a new {PosixTimeZoneParser}.
|
||||
#
|
||||
# @param string_deduper [StringDeduper] a {StringDeduper} instance to use
|
||||
# to dedupe abbreviations.
|
||||
def initialize(string_deduper)
|
||||
@string_deduper = string_deduper
|
||||
end
|
||||
|
||||
# Parses a POSIX-style TZ string.
|
||||
#
|
||||
# @param tz_string [String] the string to parse.
|
||||
# @return [Object] either a {TimezoneOffset} for a constantly applied
|
||||
# offset or an {AnnualRules} instance representing the rules.
|
||||
# @raise [InvalidPosixTimeZone] if `tz_string` is not a `String`.
|
||||
# @raise [InvalidPosixTimeZone] if `tz_string` is is not valid.
|
||||
def parse(tz_string)
|
||||
raise InvalidPosixTimeZone unless tz_string.kind_of?(String)
|
||||
return nil if tz_string.empty?
|
||||
|
||||
s = StringScanner.new(tz_string)
|
||||
check_scan(s, /([^-+,\d<][^-+,\d]*) | <([^>]+)>/x)
|
||||
std_abbrev = @string_deduper.dedupe(RubyCoreSupport.untaint(s[1] || s[2]))
|
||||
check_scan(s, /([-+]?\d+)(?::(\d+)(?::(\d+))?)?/)
|
||||
std_offset = get_offset_from_hms(s[1], s[2], s[3])
|
||||
|
||||
if s.scan(/([^-+,\d<][^-+,\d]*) | <([^>]+)>/x)
|
||||
dst_abbrev = @string_deduper.dedupe(RubyCoreSupport.untaint(s[1] || s[2]))
|
||||
|
||||
if s.scan(/([-+]?\d+)(?::(\d+)(?::(\d+))?)?/)
|
||||
dst_offset = get_offset_from_hms(s[1], s[2], s[3])
|
||||
else
|
||||
# POSIX is negative for ahead of UTC.
|
||||
dst_offset = std_offset - 3600
|
||||
end
|
||||
|
||||
dst_difference = std_offset - dst_offset
|
||||
|
||||
start_rule = parse_rule(s, 'start')
|
||||
end_rule = parse_rule(s, 'end')
|
||||
|
||||
raise InvalidPosixTimeZone, "Expected the end of a POSIX-style time zone string but found '#{s.rest}'." if s.rest?
|
||||
|
||||
if start_rule.is_always_first_day_of_year? && start_rule.transition_at == 0 &&
|
||||
end_rule.is_always_last_day_of_year? && end_rule.transition_at == 86400 + dst_difference
|
||||
# Constant daylight savings time.
|
||||
# POSIX is negative for ahead of UTC.
|
||||
TimezoneOffset.new(-std_offset, dst_difference, dst_abbrev)
|
||||
else
|
||||
AnnualRules.new(
|
||||
TimezoneOffset.new(-std_offset, 0, std_abbrev),
|
||||
TimezoneOffset.new(-std_offset, dst_difference, dst_abbrev),
|
||||
start_rule,
|
||||
end_rule)
|
||||
end
|
||||
elsif !s.rest?
|
||||
# Constant standard time.
|
||||
# POSIX is negative for ahead of UTC.
|
||||
TimezoneOffset.new(-std_offset, 0, std_abbrev)
|
||||
else
|
||||
raise InvalidPosixTimeZone, "Expected the end of a POSIX-style time zone string but found '#{s.rest}'."
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Parses a rule.
|
||||
#
|
||||
# @param s [StringScanner] the `StringScanner` to read the rule from.
|
||||
# @param type [String] the type of rule (either `'start'` or `'end'`).
|
||||
# @raise [InvalidPosixTimeZone] if the rule is not valid.
|
||||
# @return [TransitionRule] the parsed rule.
|
||||
def parse_rule(s, type)
|
||||
check_scan(s, /,(?: (?: J(\d+) ) | (\d+) | (?: M(\d+)\.(\d)\.(\d) ) )/x)
|
||||
julian_day_of_year = s[1]
|
||||
absolute_day_of_year = s[2]
|
||||
month = s[3]
|
||||
week = s[4]
|
||||
day_of_week = s[5]
|
||||
|
||||
if s.scan(/\//)
|
||||
check_scan(s, /([-+]?\d+)(?::(\d+)(?::(\d+))?)?/)
|
||||
transition_at = get_seconds_after_midnight_from_hms(s[1], s[2], s[3])
|
||||
else
|
||||
transition_at = 7200
|
||||
end
|
||||
|
||||
begin
|
||||
if julian_day_of_year
|
||||
JulianDayOfYearTransitionRule.new(julian_day_of_year.to_i, transition_at)
|
||||
elsif absolute_day_of_year
|
||||
AbsoluteDayOfYearTransitionRule.new(absolute_day_of_year.to_i, transition_at)
|
||||
elsif week == '5'
|
||||
LastDayOfMonthTransitionRule.new(month.to_i, day_of_week.to_i, transition_at)
|
||||
else
|
||||
DayOfMonthTransitionRule.new(month.to_i, week.to_i, day_of_week.to_i, transition_at)
|
||||
end
|
||||
rescue ArgumentError => e
|
||||
raise InvalidPosixTimeZone, "Invalid #{type} rule in POSIX-style time zone string: #{e}"
|
||||
end
|
||||
end
|
||||
|
||||
# Returns an offset in seconds from hh:mm:ss values. The value can be
|
||||
# negative. -02:33:12 would represent 2 hours, 33 minutes and 12 seconds
|
||||
# ahead of UTC.
|
||||
#
|
||||
# @param h [String] the hours.
|
||||
# @param m [String] the minutes.
|
||||
# @param s [String] the seconds.
|
||||
# @return [Integer] the offset.
|
||||
# @raise [InvalidPosixTimeZone] if the mm and ss values are greater than
|
||||
# 59.
|
||||
def get_offset_from_hms(h, m, s)
|
||||
h = h.to_i
|
||||
m = m.to_i
|
||||
s = s.to_i
|
||||
raise InvalidPosixTimeZone, "Invalid minute #{m} in offset for POSIX-style time zone string." if m > 59
|
||||
raise InvalidPosixTimeZone, "Invalid second #{s} in offset for POSIX-style time zone string." if s > 59
|
||||
magnitude = (h.abs * 60 + m) * 60 + s
|
||||
h < 0 ? -magnitude : magnitude
|
||||
end
|
||||
|
||||
# Returns the seconds from midnight from hh:mm:ss values. Hours can exceed
|
||||
# 24 for a time on the following day. Hours can be negative to subtract
|
||||
# hours from midnight on the given day. -02:33:12 represents 22:33:12 on
|
||||
# the prior day.
|
||||
#
|
||||
# @param h [String] the hour.
|
||||
# @param m [String] the minutes past the hour.
|
||||
# @param s [String] the seconds past the minute.
|
||||
# @return [Integer] the number of seconds after midnight.
|
||||
# @raise [InvalidPosixTimeZone] if the mm and ss values are greater than
|
||||
# 59.
|
||||
def get_seconds_after_midnight_from_hms(h, m, s)
|
||||
h = h.to_i
|
||||
m = m.to_i
|
||||
s = s.to_i
|
||||
raise InvalidPosixTimeZone, "Invalid minute #{m} in time for POSIX-style time zone string." if m > 59
|
||||
raise InvalidPosixTimeZone, "Invalid second #{s} in time for POSIX-style time zone string." if s > 59
|
||||
(h * 3600) + m * 60 + s
|
||||
end
|
||||
|
||||
# Scans for a pattern and raises an exception if the pattern does not
|
||||
# match the input.
|
||||
#
|
||||
# @param s [StringScanner] the `StringScanner` to scan.
|
||||
# @param pattern [Regexp] the pattern to match.
|
||||
# @return [String] the result of the scan.
|
||||
# @raise [InvalidPosixTimeZone] if the pattern does not match the input.
|
||||
def check_scan(s, pattern)
|
||||
result = s.scan(pattern)
|
||||
raise InvalidPosixTimeZone, "Expected '#{s.rest}' to match #{pattern} in POSIX-style time zone string." unless result
|
||||
result
|
||||
end
|
||||
end
|
||||
private_constant :PosixTimeZoneParser
|
||||
end
|
||||
end
|
||||
@ -1,141 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
module DataSources
|
||||
# A {TZInfoDataNotFound} exception is raised if the tzinfo-data gem could
|
||||
# not be found (i.e. `require 'tzinfo/data'` failed) when selecting the Ruby
|
||||
# data source.
|
||||
class TZInfoDataNotFound < StandardError
|
||||
end
|
||||
|
||||
# A DataSource implementation that loads data from the set of Ruby modules
|
||||
# included in the tzinfo-data gem.
|
||||
#
|
||||
# TZInfo will use {RubyDataSource} by default if the tzinfo-data gem
|
||||
# is available on the load path. It can also be selected by calling
|
||||
# {DataSource.set} as follows:
|
||||
#
|
||||
# TZInfo::DataSource.set(:ruby)
|
||||
class RubyDataSource < DataSource
|
||||
# (see DataSource#data_timezone_identifiers)
|
||||
attr_reader :data_timezone_identifiers
|
||||
|
||||
# (see DataSource#linked_timezone_identifiers)
|
||||
attr_reader :linked_timezone_identifiers
|
||||
|
||||
# (see DataSource#country_codes)
|
||||
attr_reader :country_codes
|
||||
|
||||
# Initializes a new {RubyDataSource} instance.
|
||||
#
|
||||
# @raise [TZInfoDataNotFound] if the tzinfo-data gem could not be found
|
||||
# (i.e. `require 'tzinfo/data'` failed).
|
||||
def initialize
|
||||
super
|
||||
|
||||
begin
|
||||
require('tzinfo/data')
|
||||
rescue LoadError
|
||||
raise TZInfoDataNotFound, "The tzinfo-data gem could not be found (require 'tzinfo/data' failed)."
|
||||
end
|
||||
|
||||
if TZInfo::Data.const_defined?(:LOCATION)
|
||||
# Format 2
|
||||
@base_path = File.join(TZInfo::Data::LOCATION, 'tzinfo', 'data')
|
||||
else
|
||||
# Format 1
|
||||
data_file = File.join('', 'tzinfo', 'data.rb')
|
||||
path = $".reverse_each.detect {|p| p.end_with?(data_file) }
|
||||
if path
|
||||
@base_path = RubyCoreSupport.untaint(File.join(File.dirname(path), 'data'))
|
||||
else
|
||||
@base_path = 'tzinfo/data'
|
||||
end
|
||||
end
|
||||
|
||||
require_index('timezones')
|
||||
require_index('countries')
|
||||
|
||||
@data_timezone_identifiers = Data::Indexes::Timezones.data_timezones
|
||||
@linked_timezone_identifiers = Data::Indexes::Timezones.linked_timezones
|
||||
@countries = Data::Indexes::Countries.countries
|
||||
@country_codes = @countries.keys.sort!.freeze
|
||||
end
|
||||
|
||||
# (see DataSource#to_s)
|
||||
def to_s
|
||||
"Ruby DataSource: #{version_info}"
|
||||
end
|
||||
|
||||
# (see DataSource#inspect)
|
||||
def inspect
|
||||
"#<TZInfo::DataSources::RubyDataSource: #{version_info}>"
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
# Returns a {TimezoneInfo} instance for the given time zone identifier.
|
||||
# The result will either be a {ConstantOffsetDataTimezoneInfo}, a
|
||||
# {TransitionsDataTimezoneInfo} or a {LinkedTimezoneInfo} depending on the
|
||||
# type of time zone.
|
||||
#
|
||||
# @param identifier [String] A time zone identifier.
|
||||
# @return [TimezoneInfo] a {TimezoneInfo} instance for the given time zone
|
||||
# identifier.
|
||||
# @raise [InvalidTimezoneIdentifier] if the time zone is not found or the
|
||||
# identifier is invalid.
|
||||
def load_timezone_info(identifier)
|
||||
valid_identifier = validate_timezone_identifier(identifier)
|
||||
split_identifier = valid_identifier.gsub(/-/, '__m__').gsub(/\+/, '__p__').split('/')
|
||||
|
||||
begin
|
||||
require_definition(split_identifier)
|
||||
|
||||
m = Data::Definitions
|
||||
split_identifier.each {|part| m = m.const_get(part) }
|
||||
m.get
|
||||
rescue LoadError, NameError => e
|
||||
raise InvalidTimezoneIdentifier, "#{e.message.encode(Encoding::UTF_8)} (loading #{valid_identifier})"
|
||||
end
|
||||
end
|
||||
|
||||
# (see DataSource#load_country_info)
|
||||
def load_country_info(code)
|
||||
lookup_country_info(@countries, code)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Requires a zone definition by its identifier (split on /).
|
||||
#
|
||||
# @param identifier [Array<string>] the component parts of a time zone
|
||||
# identifier (split on /). This must have already been validated.
|
||||
def require_definition(identifier)
|
||||
require_data('definitions', *identifier)
|
||||
end
|
||||
|
||||
# Requires an index by its name.
|
||||
#
|
||||
# @param name [String] an index name.
|
||||
def require_index(name)
|
||||
require_data('indexes', name)
|
||||
end
|
||||
|
||||
# Requires a file from tzinfo/data.
|
||||
#
|
||||
# @param file [Array<String>] a relative path to a file to be required.
|
||||
def require_data(*file)
|
||||
require(File.join(@base_path, *file))
|
||||
end
|
||||
|
||||
# @return [String] a `String` containing TZInfo::Data version infomation
|
||||
# for inclusion in the #to_s and #inspect output.
|
||||
def version_info
|
||||
# The TZInfo::Data::VERSION constant is only available from v1.2014.8
|
||||
# onwards.
|
||||
"tzdb v#{TZInfo::Data::Version::TZDATA}#{TZInfo::Data.const_defined?(:VERSION) ? ", tzinfo-data v#{TZInfo::Data::VERSION}" : ''}"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,47 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
module DataSources
|
||||
# Represents a time zone defined by a data source.
|
||||
#
|
||||
# @abstract Data sources return instances of {TimezoneInfo} subclasses.
|
||||
class TimezoneInfo
|
||||
# @return [String] the identifier of the time zone.
|
||||
attr_reader :identifier
|
||||
|
||||
# Initializes a new TimezoneInfo. The passed in `identifier` instance will
|
||||
# be frozen.
|
||||
#
|
||||
# @param identifier [String] the identifier of the time zone.
|
||||
# @raise [ArgumentError] if `identifier` is `nil`.
|
||||
def initialize(identifier)
|
||||
raise ArgumentError, 'identifier must be specified' unless identifier
|
||||
@identifier = identifier.freeze
|
||||
end
|
||||
|
||||
# @return [String] the internal object state as a programmer-readable
|
||||
# `String`.
|
||||
def inspect
|
||||
"#<#{self.class}: #@identifier>"
|
||||
end
|
||||
|
||||
# @return [Timezone] a new {Timezone} instance for the time zone
|
||||
# represented by this {TimezoneInfo}.
|
||||
def create_timezone
|
||||
raise_not_implemented('create_timezone')
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Raises a {NotImplementedError}.
|
||||
#
|
||||
# @param method_name [String] the name of the method that must be
|
||||
# overridden.
|
||||
# @raise NotImplementedError always.
|
||||
def raise_not_implemented(method_name)
|
||||
raise NotImplementedError, "Subclasses must override #{method_name}"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,214 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
module DataSources
|
||||
# Represents a data time zone defined by a list of transitions that change
|
||||
# the locally observed time.
|
||||
class TransitionsDataTimezoneInfo < DataTimezoneInfo
|
||||
# @return [Array<TimezoneTransition>] the transitions that define this
|
||||
# time zone in order of ascending timestamp.
|
||||
attr_reader :transitions
|
||||
|
||||
# Initializes a new {TransitionsDataTimezoneInfo}.
|
||||
#
|
||||
# The passed in `identifier` instance will be frozen. A reference to the
|
||||
# passed in `Array` will be retained.
|
||||
#
|
||||
# The `transitions` `Array` must be sorted in order of ascending
|
||||
# timestamp. Each transition must have a
|
||||
# {TimezoneTransition#timestamp_value timestamp_value} that is greater
|
||||
# than the {TimezoneTransition#timestamp_value timestamp_value} of the
|
||||
# prior transition.
|
||||
#
|
||||
# @param identifier [String] the identifier of the time zone.
|
||||
# @param transitions [Array<TimezoneTransitions>] an `Array` of
|
||||
# transitions that each indicate when a change occurs in the locally
|
||||
# observed time.
|
||||
# @raise [ArgumentError] if `identifier` is `nil`.
|
||||
# @raise [ArgumentError] if `transitions` is `nil`.
|
||||
# @raise [ArgumentError] if `transitions` is an empty `Array`.
|
||||
def initialize(identifier, transitions)
|
||||
super(identifier)
|
||||
raise ArgumentError, 'transitions must be specified' unless transitions
|
||||
raise ArgumentError, 'transitions must not be an empty Array' if transitions.empty?
|
||||
@transitions = transitions.freeze
|
||||
end
|
||||
|
||||
# (see DataTimezoneInfo#period_for)
|
||||
def period_for(timestamp)
|
||||
raise ArgumentError, 'timestamp must be specified' unless timestamp
|
||||
raise ArgumentError, 'timestamp must have a specified utc_offset' unless timestamp.utc_offset
|
||||
|
||||
timestamp_value = timestamp.value
|
||||
|
||||
index = find_minimum_transition {|t| t.timestamp_value >= timestamp_value }
|
||||
|
||||
if index
|
||||
transition = @transitions[index]
|
||||
|
||||
if transition.timestamp_value == timestamp_value
|
||||
# timestamp occurs within the second of the found transition, so is
|
||||
# the transition that starts the period.
|
||||
start_transition = transition
|
||||
end_transition = @transitions[index + 1]
|
||||
else
|
||||
# timestamp occurs before the second of the found transition, so is
|
||||
# the transition that ends the period.
|
||||
start_transition = index == 0 ? nil : @transitions[index - 1]
|
||||
end_transition = transition
|
||||
end
|
||||
else
|
||||
start_transition = @transitions.last
|
||||
end_transition = nil
|
||||
end
|
||||
|
||||
TransitionsTimezonePeriod.new(start_transition, end_transition)
|
||||
end
|
||||
|
||||
# (see DataTimezoneInfo#periods_for_local)
|
||||
def periods_for_local(local_timestamp)
|
||||
raise ArgumentError, 'local_timestamp must be specified' unless local_timestamp
|
||||
raise ArgumentError, 'local_timestamp must have an unspecified utc_offset' if local_timestamp.utc_offset
|
||||
|
||||
local_timestamp_value = local_timestamp.value
|
||||
latest_possible_utc_value = local_timestamp_value + 86400
|
||||
earliest_possible_utc_value = local_timestamp_value - 86400
|
||||
|
||||
# Find the index of the first transition that occurs after a latest
|
||||
# possible UTC representation of the local timestamp and then search
|
||||
# backwards until an earliest possible UTC representation.
|
||||
|
||||
index = find_minimum_transition {|t| t.timestamp_value >= latest_possible_utc_value }
|
||||
|
||||
# No transitions after latest_possible_utc_value, set to max index + 1
|
||||
# to search backwards including the period after the last transition
|
||||
index = @transitions.length unless index
|
||||
|
||||
result = []
|
||||
|
||||
index.downto(0) do |i|
|
||||
start_transition = i > 0 ? @transitions[i - 1] : nil
|
||||
end_transition = @transitions[i]
|
||||
offset = start_transition ? start_transition.offset : end_transition.previous_offset
|
||||
utc_timestamp_value = local_timestamp_value - offset.observed_utc_offset
|
||||
|
||||
# It is not necessary to compare the sub-seconds because a timestamp
|
||||
# is in the period if is >= the start transition (sub-seconds would
|
||||
# make == become >) and if it is < the end transition (which
|
||||
# sub-seconds cannot affect).
|
||||
if (!start_transition || utc_timestamp_value >= start_transition.timestamp_value) && (!end_transition || utc_timestamp_value < end_transition.timestamp_value)
|
||||
result << TransitionsTimezonePeriod.new(start_transition, end_transition)
|
||||
elsif end_transition && end_transition.timestamp_value < earliest_possible_utc_value
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
result.reverse!
|
||||
end
|
||||
|
||||
# (see DataTimezoneInfo#transitions_up_to)
|
||||
def transitions_up_to(to_timestamp, from_timestamp = nil)
|
||||
raise ArgumentError, 'to_timestamp must be specified' unless to_timestamp
|
||||
raise ArgumentError, 'to_timestamp must have a specified utc_offset' unless to_timestamp.utc_offset
|
||||
|
||||
if from_timestamp
|
||||
raise ArgumentError, 'from_timestamp must have a specified utc_offset' unless from_timestamp.utc_offset
|
||||
raise ArgumentError, 'to_timestamp must be greater than from_timestamp' if to_timestamp <= from_timestamp
|
||||
end
|
||||
|
||||
if from_timestamp
|
||||
from_index = find_minimum_transition {|t| transition_on_or_after_timestamp?(t, from_timestamp) }
|
||||
return [] unless from_index
|
||||
else
|
||||
from_index = 0
|
||||
end
|
||||
|
||||
to_index = find_minimum_transition {|t| transition_on_or_after_timestamp?(t, to_timestamp) }
|
||||
|
||||
if to_index
|
||||
return [] if to_index < 1
|
||||
to_index -= 1
|
||||
else
|
||||
to_index = -1
|
||||
end
|
||||
|
||||
@transitions[from_index..to_index]
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Array#bsearch_index was added in Ruby 2.3.0. Use bsearch_index to find
|
||||
# transitions if it is available, otherwise use a Ruby implementation.
|
||||
if [].respond_to?(:bsearch_index)
|
||||
# Performs a binary search on {transitions} to find the index of the
|
||||
# earliest transition satisfying a condition.
|
||||
#
|
||||
# @yield [transition] the caller will be yielded to to test the search
|
||||
# condition.
|
||||
# @yieldparam transition [TimezoneTransition] a {TimezoneTransition}
|
||||
# instance from {transitions}.
|
||||
# @yieldreturn [Boolean] `true` for the earliest transition that
|
||||
# satisfies the condition and return `true` for all subsequent
|
||||
# transitions. In all other cases, the result of the block must be
|
||||
# `false`.
|
||||
# @return [Integer] the index of the earliest transition safisfying
|
||||
# the condition or `nil` if there are no such transitions.
|
||||
#
|
||||
# :nocov_no_array_bsearch_index:
|
||||
def find_minimum_transition(&block)
|
||||
@transitions.bsearch_index(&block)
|
||||
end
|
||||
# :nocov_no_array_bsearch_index:
|
||||
else
|
||||
# Performs a binary search on {transitions} to find the index of the
|
||||
# earliest transition satisfying a condition.
|
||||
#
|
||||
# @yield [transition] the caller will be yielded to to test the search
|
||||
# condition.
|
||||
# @yieldparam transition [TimezoneTransition] a {TimezoneTransition}
|
||||
# instance from {transitions}.
|
||||
# @yieldreturn [Boolean] `true` for the earliest transition that
|
||||
# satisfies the condition and return `true` for all subsequent
|
||||
# transitions. In all other cases, the result of the block must be
|
||||
# `false`.
|
||||
# @return [Integer] the index of the earliest transition safisfying
|
||||
# the condition or `nil` if there are no such transitions.
|
||||
#
|
||||
# :nocov_array_bsearch_index:
|
||||
def find_minimum_transition
|
||||
# A Ruby implementation of the find-minimum mode of Array#bsearch_index.
|
||||
low = 0
|
||||
high = @transitions.length
|
||||
satisfied = false
|
||||
|
||||
while low < high do
|
||||
mid = (low + high).div(2)
|
||||
if yield @transitions[mid]
|
||||
satisfied = true
|
||||
high = mid
|
||||
else
|
||||
low = mid + 1
|
||||
end
|
||||
end
|
||||
|
||||
satisfied ? low : nil
|
||||
end
|
||||
# :nocov_array_bsearch_index:
|
||||
end
|
||||
|
||||
# Determines if a transition occurs at or after a given {Timestamp},
|
||||
# taking the {Timestamp#sub_second sub_second} into consideration.
|
||||
#
|
||||
# @param transition [TimezoneTransition] the transition to compare.
|
||||
# @param timestamp [Timestamp] the timestamp to compare.
|
||||
# @return [Boolean] `true` if `transition` occurs at or after `timestamp`,
|
||||
# otherwise `false`.
|
||||
def transition_on_or_after_timestamp?(transition, timestamp)
|
||||
transition_timestamp_value = transition.timestamp_value
|
||||
timestamp_value = timestamp.value
|
||||
transition_timestamp_value > timestamp_value || transition_timestamp_value == timestamp_value && timestamp.sub_second == 0
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,592 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
module DataSources
|
||||
# An {InvalidZoneinfoDirectory} exception is raised if {ZoneinfoDataSource}
|
||||
# is initialized with a specific zoneinfo path that is not a valid zoneinfo
|
||||
# directory. A valid zoneinfo directory is one that contains time zone
|
||||
# files, a country code index file named iso3166.tab and a time zone index
|
||||
# file named zone1970.tab or zone.tab.
|
||||
class InvalidZoneinfoDirectory < StandardError
|
||||
end
|
||||
|
||||
# A {ZoneinfoDirectoryNotFound} exception is raised if no valid zoneinfo
|
||||
# directory could be found when checking the paths listed in
|
||||
# {ZoneinfoDataSource.search_path}. A valid zoneinfo directory is one that
|
||||
# contains time zone files, a country code index file named iso3166.tab and
|
||||
# a time zone index file named zone1970.tab or zone.tab.
|
||||
class ZoneinfoDirectoryNotFound < StandardError
|
||||
end
|
||||
|
||||
# A DataSource implementation that loads data from a 'zoneinfo' directory
|
||||
# containing compiled "TZif" version 3 (or earlier) files in addition to
|
||||
# iso3166.tab and zone1970.tab or zone.tab index files.
|
||||
#
|
||||
# To have TZInfo load the system zoneinfo files, call
|
||||
# {TZInfo::DataSource.set} as follows:
|
||||
#
|
||||
# TZInfo::DataSource.set(:zoneinfo)
|
||||
#
|
||||
# To load zoneinfo files from a particular directory, pass the directory to
|
||||
# {TZInfo::DataSource.set}:
|
||||
#
|
||||
# TZInfo::DataSource.set(:zoneinfo, directory)
|
||||
#
|
||||
# To load zoneinfo files from a particular directory, but load the
|
||||
# iso3166.tab index file from a separate location, pass the directory and
|
||||
# path to the iso3166.tab file to {TZInfo::DataSource.set}:
|
||||
#
|
||||
# TZInfo::DataSource.set(:zoneinfo, directory, iso3166_path)
|
||||
#
|
||||
# Please note that versions of the 'zic' tool (used to build zoneinfo files)
|
||||
# that were released prior to February 2006 created zoneinfo files that used
|
||||
# 32-bit integers for transition timestamps. Later versions of zic produce
|
||||
# zoneinfo files that use 64-bit integers. If you have 32-bit zoneinfo files
|
||||
# on your system, then any queries falling outside of the range 1901-12-13
|
||||
# 20:45:52 to 2038-01-19 03:14:07 may be inaccurate.
|
||||
#
|
||||
# Most modern platforms include 64-bit zoneinfo files. However, Mac OS X (up
|
||||
# to at least 10.8.4) still uses 32-bit zoneinfo files.
|
||||
#
|
||||
# To check whether your zoneinfo files contain 32-bit or 64-bit transition
|
||||
# data, you can run the following code (substituting the identifier of the
|
||||
# zone you want to test for `zone_identifier`):
|
||||
#
|
||||
# TZInfo::DataSource.set(:zoneinfo)
|
||||
# dir = TZInfo::DataSource.get.zoneinfo_dir
|
||||
# File.open(File.join(dir, zone_identifier), 'r') {|f| f.read(5) }
|
||||
#
|
||||
# If the last line returns `"TZif\\x00"`, then you have a 32-bit zoneinfo
|
||||
# file. If it returns `"TZif2"` or `"TZif3"` then you have a 64-bit zoneinfo
|
||||
# file.
|
||||
#
|
||||
# It is also worth noting that as of the 2017c release of the IANA Time Zone
|
||||
# Database, 64-bit zoneinfo files only include future transitions up to
|
||||
# 2038-01-19 03:14:07. Any queries falling after this time may be
|
||||
# inaccurate.
|
||||
class ZoneinfoDataSource < DataSource
|
||||
# The default value of {ZoneinfoDataSource.search_path}.
|
||||
DEFAULT_SEARCH_PATH = ['/usr/share/zoneinfo', '/usr/share/lib/zoneinfo', '/etc/zoneinfo'].freeze
|
||||
private_constant :DEFAULT_SEARCH_PATH
|
||||
|
||||
# The default value of {ZoneinfoDataSource.alternate_iso3166_tab_search_path}.
|
||||
DEFAULT_ALTERNATE_ISO3166_TAB_SEARCH_PATH = ['/usr/share/misc/iso3166.tab', '/usr/share/misc/iso3166'].freeze
|
||||
private_constant :DEFAULT_ALTERNATE_ISO3166_TAB_SEARCH_PATH
|
||||
|
||||
# Files and directories in the top level zoneinfo directory that will be
|
||||
# excluded from the list of available time zones:
|
||||
#
|
||||
# - +VERSION is included on Mac OS X.
|
||||
# - leapseconds is a list of leap seconds.
|
||||
# - localtime is the current local timezone (may be a link).
|
||||
# - posix, posixrules and right are directories containing other
|
||||
# versions of the zoneinfo files.
|
||||
# - SECURITY is included in the Arch Linux tzdata package.
|
||||
# - src is a directory containing the tzdata source included on Solaris.
|
||||
# - timeconfig is a symlink included on Slackware.
|
||||
EXCLUDED_FILENAMES = [
|
||||
'+VERSION',
|
||||
'leapseconds',
|
||||
'localtime',
|
||||
'posix',
|
||||
'posixrules',
|
||||
'right',
|
||||
'SECURITY',
|
||||
'src',
|
||||
'timeconfig'
|
||||
].freeze
|
||||
private_constant :EXCLUDED_FILENAMES
|
||||
|
||||
# Paths to be checked to find the system zoneinfo directory.
|
||||
#
|
||||
# @private
|
||||
@@search_path = DEFAULT_SEARCH_PATH.dup
|
||||
|
||||
# Paths to possible alternate iso3166.tab files (used to locate the
|
||||
# system-wide iso3166.tab files on FreeBSD and OpenBSD).
|
||||
#
|
||||
# @private
|
||||
@@alternate_iso3166_tab_search_path = DEFAULT_ALTERNATE_ISO3166_TAB_SEARCH_PATH.dup
|
||||
|
||||
class << self
|
||||
# An `Array` of directories that will be checked to find the system
|
||||
# zoneinfo directory.
|
||||
#
|
||||
# Directories are checked in the order they appear in the `Array`.
|
||||
#
|
||||
# The default value is `['/usr/share/zoneinfo',
|
||||
# '/usr/share/lib/zoneinfo', '/etc/zoneinfo']`.
|
||||
#
|
||||
# @return [Array<String>] an `Array` of directories to check in order to
|
||||
# find the system zoneinfo directory.
|
||||
def search_path
|
||||
@@search_path
|
||||
end
|
||||
|
||||
# Sets the directories to be checked when locating the system zoneinfo
|
||||
# directory.
|
||||
#
|
||||
# Can be set to an `Array` of directories or a `String` containing
|
||||
# directories separated with `File::PATH_SEPARATOR`.
|
||||
#
|
||||
# Directories are checked in the order they appear in the `Array` or
|
||||
# `String`.
|
||||
#
|
||||
# Set to `nil` to revert to the default paths.
|
||||
#
|
||||
# @param search_path [Object] either `nil` or a list of directories to
|
||||
# check as either an `Array` of `String` or a `File::PATH_SEPARATOR`
|
||||
# separated `String`.
|
||||
def search_path=(search_path)
|
||||
@@search_path = process_search_path(search_path, DEFAULT_SEARCH_PATH)
|
||||
end
|
||||
|
||||
# An `Array` of paths that will be checked to find an alternate
|
||||
# iso3166.tab file if one was not included in the zoneinfo directory
|
||||
# (for example, on FreeBSD and OpenBSD systems).
|
||||
#
|
||||
# Paths are checked in the order they appear in the `Array`.
|
||||
#
|
||||
# The default value is `['/usr/share/misc/iso3166.tab',
|
||||
# '/usr/share/misc/iso3166']`.
|
||||
#
|
||||
# @return [Array<String>] an `Array` of paths to check in order to
|
||||
# locate an iso3166.tab file.
|
||||
def alternate_iso3166_tab_search_path
|
||||
@@alternate_iso3166_tab_search_path
|
||||
end
|
||||
|
||||
# Sets the paths to check to locate an alternate iso3166.tab file if one
|
||||
# was not included in the zoneinfo directory.
|
||||
#
|
||||
# Can be set to an `Array` of paths or a `String` containing paths
|
||||
# separated with `File::PATH_SEPARATOR`.
|
||||
#
|
||||
# Paths are checked in the order they appear in the array.
|
||||
#
|
||||
# Set to `nil` to revert to the default paths.
|
||||
#
|
||||
# @param alternate_iso3166_tab_search_path [Object] either `nil` or a
|
||||
# list of paths to check as either an `Array` of `String` or a
|
||||
# `File::PATH_SEPARATOR` separated `String`.
|
||||
def alternate_iso3166_tab_search_path=(alternate_iso3166_tab_search_path)
|
||||
@@alternate_iso3166_tab_search_path = process_search_path(alternate_iso3166_tab_search_path, DEFAULT_ALTERNATE_ISO3166_TAB_SEARCH_PATH)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Processes a path for use as the {search_path} or
|
||||
# {alternate_iso3166_tab_search_path}.
|
||||
#
|
||||
# @param path [Object] either `nil` or a list of paths to check as
|
||||
# either an `Array` of `String` or a `File::PATH_SEPARATOR` separated
|
||||
# `String`.
|
||||
# @param default [Array<String>] the default value.
|
||||
# @return [Array<String>] the processed path.
|
||||
def process_search_path(path, default)
|
||||
if path
|
||||
if path.kind_of?(String)
|
||||
path.split(File::PATH_SEPARATOR)
|
||||
else
|
||||
path.collect(&:to_s)
|
||||
end
|
||||
else
|
||||
default.dup
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# @return [String] the zoneinfo directory being used.
|
||||
attr_reader :zoneinfo_dir
|
||||
|
||||
# (see DataSource#country_codes)
|
||||
attr_reader :country_codes
|
||||
|
||||
# Initializes a new {ZoneinfoDataSource}.
|
||||
#
|
||||
# If `zoneinfo_dir` is specified, it will be checked and used as the
|
||||
# source of zoneinfo files.
|
||||
#
|
||||
# The directory must contain a file named iso3166.tab and a file named
|
||||
# either zone1970.tab or zone.tab. These may either be included in the
|
||||
# root of the directory or in a 'tab' sub-directory and named country.tab
|
||||
# and zone_sun.tab respectively (as is the case on Solaris).
|
||||
#
|
||||
# Additionally, the path to iso3166.tab can be overridden using the
|
||||
# `alternate_iso3166_tab_path` parameter.
|
||||
#
|
||||
# If `zoneinfo_dir` is not specified or `nil`, the paths referenced in
|
||||
# {search_path} are searched in order to find a valid zoneinfo directory
|
||||
# (one that contains zone1970.tab or zone.tab and iso3166.tab files as
|
||||
# above).
|
||||
#
|
||||
# The paths referenced in {alternate_iso3166_tab_search_path} are also
|
||||
# searched to find an iso3166.tab file if one of the searched zoneinfo
|
||||
# directories doesn't contain an iso3166.tab file.
|
||||
#
|
||||
# @param zoneinfo_dir [String] an optional path to a directory to use as
|
||||
# the source of zoneinfo files.
|
||||
# @param alternate_iso3166_tab_path [String] an optional path to the
|
||||
# iso3166.tab file.
|
||||
# @raise [InvalidZoneinfoDirectory] if the iso3166.tab and zone1970.tab or
|
||||
# zone.tab files cannot be found using the `zoneinfo_dir` and
|
||||
# `alternate_iso3166_tab_path` parameters.
|
||||
# @raise [ZoneinfoDirectoryNotFound] if no valid directory can be found
|
||||
# by searching.
|
||||
def initialize(zoneinfo_dir = nil, alternate_iso3166_tab_path = nil)
|
||||
super()
|
||||
|
||||
if zoneinfo_dir
|
||||
iso3166_tab_path, zone_tab_path = validate_zoneinfo_dir(zoneinfo_dir, alternate_iso3166_tab_path)
|
||||
|
||||
unless iso3166_tab_path && zone_tab_path
|
||||
raise InvalidZoneinfoDirectory, "#{zoneinfo_dir} is not a directory or doesn't contain a iso3166.tab file and a zone1970.tab or zone.tab file."
|
||||
end
|
||||
|
||||
@zoneinfo_dir = zoneinfo_dir
|
||||
else
|
||||
@zoneinfo_dir, iso3166_tab_path, zone_tab_path = find_zoneinfo_dir
|
||||
|
||||
unless @zoneinfo_dir && iso3166_tab_path && zone_tab_path
|
||||
raise ZoneinfoDirectoryNotFound, "None of the paths included in #{self.class.name}.search_path are valid zoneinfo directories."
|
||||
end
|
||||
end
|
||||
|
||||
@zoneinfo_dir = File.expand_path(@zoneinfo_dir).freeze
|
||||
@timezone_identifiers = load_timezone_identifiers.freeze
|
||||
@countries = load_countries(iso3166_tab_path, zone_tab_path).freeze
|
||||
@country_codes = @countries.keys.sort!.freeze
|
||||
|
||||
string_deduper = ConcurrentStringDeduper.new
|
||||
posix_tz_parser = PosixTimeZoneParser.new(string_deduper)
|
||||
@zoneinfo_reader = ZoneinfoReader.new(posix_tz_parser, string_deduper)
|
||||
end
|
||||
|
||||
# Returns a frozen `Array` of all the available time zone identifiers. The
|
||||
# identifiers are sorted according to `String#<=>`.
|
||||
#
|
||||
# @return [Array<String>] a frozen `Array` of all the available time zone
|
||||
# identifiers.
|
||||
def data_timezone_identifiers
|
||||
@timezone_identifiers
|
||||
end
|
||||
|
||||
# Returns an empty `Array`. There is no information about linked/aliased
|
||||
# time zones in the zoneinfo files. When using {ZoneinfoDataSource}, every
|
||||
# time zone will be returned as a {DataTimezone}.
|
||||
#
|
||||
# @return [Array<String>] an empty `Array`.
|
||||
def linked_timezone_identifiers
|
||||
[].freeze
|
||||
end
|
||||
|
||||
# (see DataSource#to_s)
|
||||
def to_s
|
||||
"Zoneinfo DataSource: #{@zoneinfo_dir}"
|
||||
end
|
||||
|
||||
# (see DataSource#inspect)
|
||||
def inspect
|
||||
"#<#{self.class}: #{@zoneinfo_dir}>"
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
# Returns a {TimezoneInfo} instance for the given time zone identifier.
|
||||
# The result will either be a {ConstantOffsetDataTimezoneInfo} or a
|
||||
# {TransitionsDataTimezoneInfo}.
|
||||
#
|
||||
# @param identifier [String] A time zone identifier.
|
||||
# @return [TimezoneInfo] a {TimezoneInfo} instance for the given time zone
|
||||
# identifier.
|
||||
# @raise [InvalidTimezoneIdentifier] if the time zone is not found, the
|
||||
# identifier is invalid, the zoneinfo file cannot be opened or the
|
||||
# zoneinfo file is not valid.
|
||||
def load_timezone_info(identifier)
|
||||
valid_identifier = validate_timezone_identifier(identifier)
|
||||
path = File.join(@zoneinfo_dir, valid_identifier)
|
||||
|
||||
zoneinfo = begin
|
||||
@zoneinfo_reader.read(path)
|
||||
rescue Errno::EACCES, InvalidZoneinfoFile => e
|
||||
raise InvalidTimezoneIdentifier, "#{e.message.encode(Encoding::UTF_8)} (loading #{valid_identifier})"
|
||||
rescue Errno::EISDIR, Errno::ENAMETOOLONG, Errno::ENOENT, Errno::ENOTDIR
|
||||
raise InvalidTimezoneIdentifier, "Invalid identifier: #{valid_identifier}"
|
||||
end
|
||||
|
||||
if zoneinfo.kind_of?(TimezoneOffset)
|
||||
ConstantOffsetDataTimezoneInfo.new(valid_identifier, zoneinfo)
|
||||
else
|
||||
TransitionsDataTimezoneInfo.new(valid_identifier, zoneinfo)
|
||||
end
|
||||
end
|
||||
|
||||
# (see DataSource#load_country_info)
|
||||
def load_country_info(code)
|
||||
lookup_country_info(@countries, code)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Validates a zoneinfo directory and returns the paths to the iso3166.tab
|
||||
# and zone1970.tab or zone.tab files if valid. If the directory is not
|
||||
# valid, returns `nil`.
|
||||
#
|
||||
# The path to the iso3166.tab file may be overridden by passing in a path.
|
||||
# This is treated as either absolute or relative to the current working
|
||||
# directory.
|
||||
#
|
||||
# @param path [String] the path to a possible zoneinfo directory.
|
||||
# @param iso3166_tab_path [String] an optional path to an external
|
||||
# iso3166.tab file.
|
||||
# @return [Array<String>] an `Array` containing the iso3166.tab and
|
||||
# zone.tab paths if the directory is valid, otherwise `nil`.
|
||||
def validate_zoneinfo_dir(path, iso3166_tab_path = nil)
|
||||
if File.directory?(path)
|
||||
if iso3166_tab_path
|
||||
return nil unless File.file?(iso3166_tab_path)
|
||||
else
|
||||
iso3166_tab_path = resolve_tab_path(path, ['iso3166.tab'], 'country.tab')
|
||||
return nil unless iso3166_tab_path
|
||||
end
|
||||
|
||||
zone_tab_path = resolve_tab_path(path, ['zone1970.tab', 'zone.tab'], 'zone_sun.tab')
|
||||
return nil unless zone_tab_path
|
||||
|
||||
[iso3166_tab_path, zone_tab_path]
|
||||
else
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
# Attempts to resolve the path to a tab file given its standard names and
|
||||
# tab sub-directory name (as used on Solaris).
|
||||
#
|
||||
# @param zoneinfo_path [String] the path to a zoneinfo directory.
|
||||
# @param standard_names [Array<String>] the standard names for the tab
|
||||
# file.
|
||||
# @param tab_name [String] the alternate name for the tab file to check in
|
||||
# the tab sub-directory.
|
||||
# @return [String] the path to the tab file.
|
||||
def resolve_tab_path(zoneinfo_path, standard_names, tab_name)
|
||||
standard_names.each do |standard_name|
|
||||
path = File.join(zoneinfo_path, standard_name)
|
||||
return path if File.file?(path)
|
||||
end
|
||||
|
||||
path = File.join(zoneinfo_path, 'tab', tab_name)
|
||||
return path if File.file?(path)
|
||||
|
||||
nil
|
||||
end
|
||||
|
||||
# Finds a zoneinfo directory using {search_path} and
|
||||
# {alternate_iso3166_tab_search_path}.
|
||||
#
|
||||
# @return [Array<String>] an `Array` containing the iso3166.tab and
|
||||
# zone.tab paths if a zoneinfo directory was found, otherwise `nil`.
|
||||
def find_zoneinfo_dir
|
||||
alternate_iso3166_tab_path = self.class.alternate_iso3166_tab_search_path.detect do |path|
|
||||
File.file?(path)
|
||||
end
|
||||
|
||||
self.class.search_path.each do |path|
|
||||
# Try without the alternate_iso3166_tab_path first.
|
||||
iso3166_tab_path, zone_tab_path = validate_zoneinfo_dir(path)
|
||||
return path, iso3166_tab_path, zone_tab_path if iso3166_tab_path && zone_tab_path
|
||||
|
||||
if alternate_iso3166_tab_path
|
||||
iso3166_tab_path, zone_tab_path = validate_zoneinfo_dir(path, alternate_iso3166_tab_path)
|
||||
return path, iso3166_tab_path, zone_tab_path if iso3166_tab_path && zone_tab_path
|
||||
end
|
||||
end
|
||||
|
||||
# Not found.
|
||||
nil
|
||||
end
|
||||
|
||||
# Scans @zoneinfo_dir and returns an `Array` of available time zone
|
||||
# identifiers. The result is sorted according to `String#<=>`.
|
||||
#
|
||||
# @return [Array<String>] an `Array` containing all the time zone
|
||||
# identifiers found.
|
||||
def load_timezone_identifiers
|
||||
index = []
|
||||
|
||||
enum_timezones([], EXCLUDED_FILENAMES) do |identifier|
|
||||
index << identifier.join('/').freeze
|
||||
end
|
||||
|
||||
index.sort!
|
||||
end
|
||||
|
||||
# Recursively enumerate a directory of time zones.
|
||||
#
|
||||
# @param dir [Array<String>] the directory to enumerate as an `Array` of
|
||||
# path components.
|
||||
# @param exclude [Array<String>] file names to exclude when scanning
|
||||
# `dir`.
|
||||
# @yield [path] the path of each time zone file found is passed to
|
||||
# the block.
|
||||
# @yieldparam path [Array<String>] the path of a time zone file as an
|
||||
# `Array` of path components.
|
||||
def enum_timezones(dir, exclude = [], &block)
|
||||
Dir.foreach(File.join(@zoneinfo_dir, *dir)) do |entry|
|
||||
begin
|
||||
entry.encode!(Encoding::UTF_8)
|
||||
rescue EncodingError
|
||||
next
|
||||
end
|
||||
|
||||
unless entry =~ /\./ || exclude.include?(entry)
|
||||
RubyCoreSupport.untaint(entry)
|
||||
path = dir + [entry]
|
||||
full_path = File.join(@zoneinfo_dir, *path)
|
||||
|
||||
if File.directory?(full_path)
|
||||
enum_timezones(path, [], &block)
|
||||
elsif File.file?(full_path)
|
||||
yield path
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Uses the iso3166.tab and zone1970.tab or zone.tab files to return a Hash
|
||||
# mapping country codes to CountryInfo instances.
|
||||
#
|
||||
# @param iso3166_tab_path [String] the path to the iso3166.tab file.
|
||||
# @param zone_tab_path [String] the path to the zone.tab file.
|
||||
# @return [Hash<String, CountryInfo>] a mapping from ISO 3166-1 alpha-2
|
||||
# country codes to {CountryInfo} instances.
|
||||
def load_countries(iso3166_tab_path, zone_tab_path)
|
||||
|
||||
# Handle standard 3 to 4 column zone.tab files as well as the 4 to 5
|
||||
# column format used by Solaris.
|
||||
#
|
||||
# On Solaris, an extra column before the comment gives an optional
|
||||
# linked/alternate timezone identifier (or '-' if not set).
|
||||
#
|
||||
# Additionally, there is a section at the end of the file for timezones
|
||||
# covering regions. These are given lower-case "country" codes. The timezone
|
||||
# identifier column refers to a continent instead of an identifier. These
|
||||
# lines will be ignored by TZInfo.
|
||||
#
|
||||
# Since the last column is optional in both formats, testing for the
|
||||
# Solaris format is done in two passes. The first pass identifies if there
|
||||
# are any lines using 5 columns.
|
||||
|
||||
|
||||
# The first column is allowed to be a comma separated list of country
|
||||
# codes, as used in zone1970.tab (introduced in tzdata 2014f).
|
||||
#
|
||||
# The first country code in the comma-separated list is the country that
|
||||
# contains the city the zone identifier is based on. The first country
|
||||
# code on each line is considered to be primary with the others
|
||||
# secondary.
|
||||
#
|
||||
# The zones for each country are ordered primary first, then secondary.
|
||||
# Within the primary and secondary groups, the zones are ordered by their
|
||||
# order in the file.
|
||||
|
||||
file_is_5_column = false
|
||||
zone_tab = []
|
||||
|
||||
file = File.read(zone_tab_path, external_encoding: Encoding::UTF_8, internal_encoding: Encoding::UTF_8)
|
||||
file.each_line do |line|
|
||||
line.chomp!
|
||||
|
||||
if line =~ /\A([A-Z]{2}(?:,[A-Z]{2})*)\t(?:([+\-])(\d{2})(\d{2})([+\-])(\d{3})(\d{2})|([+\-])(\d{2})(\d{2})(\d{2})([+\-])(\d{3})(\d{2})(\d{2}))\t([^\t]+)(?:\t([^\t]+))?(?:\t([^\t]+))?\z/
|
||||
codes = $1
|
||||
|
||||
if $2
|
||||
latitude = dms_to_rational($2, $3, $4)
|
||||
longitude = dms_to_rational($5, $6, $7)
|
||||
else
|
||||
latitude = dms_to_rational($8, $9, $10, $11)
|
||||
longitude = dms_to_rational($12, $13, $14, $15)
|
||||
end
|
||||
|
||||
zone_identifier = $16
|
||||
column4 = $17
|
||||
column5 = $18
|
||||
|
||||
file_is_5_column = true if column5
|
||||
|
||||
zone_tab << [codes.split(','.freeze), zone_identifier, latitude, longitude, column4, column5]
|
||||
end
|
||||
end
|
||||
|
||||
string_deduper = StringDeduper.new
|
||||
primary_zones = {}
|
||||
secondary_zones = {}
|
||||
|
||||
zone_tab.each do |codes, zone_identifier, latitude, longitude, column4, column5|
|
||||
description = file_is_5_column ? column5 : column4
|
||||
description = string_deduper.dedupe(description) if description
|
||||
|
||||
# Lookup the identifier in the timezone index, so that the same
|
||||
# String instance can be used (saving memory).
|
||||
begin
|
||||
zone_identifier = validate_timezone_identifier(zone_identifier)
|
||||
rescue InvalidTimezoneIdentifier
|
||||
# zone_identifier is not valid, dedupe and allow anyway.
|
||||
zone_identifier = string_deduper.dedupe(zone_identifier)
|
||||
end
|
||||
|
||||
country_timezone = CountryTimezone.new(zone_identifier, latitude, longitude, description)
|
||||
|
||||
# codes will always have at least one element
|
||||
|
||||
(primary_zones[codes.first.freeze] ||= []) << country_timezone
|
||||
|
||||
codes[1..-1].each do |code|
|
||||
(secondary_zones[code.freeze] ||= []) << country_timezone
|
||||
end
|
||||
end
|
||||
|
||||
countries = {}
|
||||
|
||||
file = File.read(iso3166_tab_path, external_encoding: Encoding::UTF_8, internal_encoding: Encoding::UTF_8)
|
||||
file.each_line do |line|
|
||||
line.chomp!
|
||||
|
||||
# Handle both the two column alpha-2 and name format used in the tz
|
||||
# database as well as the 4 column alpha-2, alpha-3, numeric-3 and
|
||||
# name format used by FreeBSD and OpenBSD.
|
||||
|
||||
if line =~ /\A([A-Z]{2})(?:\t[A-Z]{3}\t[0-9]{3})?\t(.+)\z/
|
||||
code = $1
|
||||
name = $2
|
||||
zones = (primary_zones[code] || []) + (secondary_zones[code] || [])
|
||||
|
||||
countries[code] = CountryInfo.new(code, name, zones)
|
||||
end
|
||||
end
|
||||
|
||||
countries
|
||||
end
|
||||
|
||||
# Converts degrees, minutes and seconds to a Rational.
|
||||
#
|
||||
# @param sign [String] `'-'` or `'+'`.
|
||||
# @param degrees [String] the number of degrees.
|
||||
# @param minutes [String] the number of minutes.
|
||||
# @param seconds [String] the number of seconds (optional).
|
||||
# @return [Rational] the result of converting from degrees, minutes and
|
||||
# seconds to a `Rational`.
|
||||
def dms_to_rational(sign, degrees, minutes, seconds = nil)
|
||||
degrees = degrees.to_i
|
||||
minutes = minutes.to_i
|
||||
sign = sign == '-'.freeze ? -1 : 1
|
||||
|
||||
if seconds
|
||||
Rational(sign * (degrees * 3600 + minutes * 60 + seconds.to_i), 3600)
|
||||
else
|
||||
Rational(sign * (degrees * 60 + minutes), 60)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,482 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
module DataSources
|
||||
# An {InvalidZoneinfoFile} exception is raised if an attempt is made to load
|
||||
# an invalid zoneinfo file.
|
||||
class InvalidZoneinfoFile < StandardError
|
||||
end
|
||||
|
||||
# Reads compiled zoneinfo TZif (\0, 2 or 3) files.
|
||||
class ZoneinfoReader #:nodoc:
|
||||
# The year to generate transitions up to.
|
||||
#
|
||||
# @private
|
||||
GENERATE_UP_TO = Time.now.utc.year + 100
|
||||
private_constant :GENERATE_UP_TO
|
||||
|
||||
# Initializes a new {ZoneinfoReader}.
|
||||
#
|
||||
# @param posix_tz_parser [PosixTimeZoneParser] a {PosixTimeZoneParser}
|
||||
# instance to use to parse POSIX-style TZ strings.
|
||||
# @param string_deduper [StringDeduper] a {StringDeduper} instance to use
|
||||
# to dedupe abbreviations.
|
||||
def initialize(posix_tz_parser, string_deduper)
|
||||
@posix_tz_parser = posix_tz_parser
|
||||
@string_deduper = string_deduper
|
||||
end
|
||||
|
||||
# Reads a zoneinfo structure from the given path. Returns either a
|
||||
# {TimezoneOffset} that is constantly observed or an `Array`
|
||||
# {TimezoneTransition}s.
|
||||
#
|
||||
# @param file_path [String] the path of a zoneinfo file.
|
||||
# @return [Object] either a {TimezoneOffset} or an `Array` of
|
||||
# {TimezoneTransition}s.
|
||||
# @raise [SecurityError] if safe mode is enabled and `file_path` is
|
||||
# tainted.
|
||||
# @raise [InvalidZoneinfoFile] if `file_path`` does not refer to a valid
|
||||
# zoneinfo file.
|
||||
def read(file_path)
|
||||
File.open(file_path, 'rb') { |file| parse(file) }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Translates an unsigned 32-bit integer (as returned by unpack) to signed
|
||||
# 32-bit.
|
||||
#
|
||||
# @param long [Integer] an unsigned 32-bit integer.
|
||||
# @return [Integer] {long} translated to signed 32-bit.
|
||||
def make_signed_int32(long)
|
||||
long >= 0x80000000 ? long - 0x100000000 : long
|
||||
end
|
||||
|
||||
# Translates a pair of unsigned 32-bit integers (as returned by unpack,
|
||||
# most significant first) to a signed 64-bit integer.
|
||||
#
|
||||
# @param high [Integer] the most significant 32-bits.
|
||||
# @param low [Integer] the least significant 32-bits.
|
||||
# @return [Integer] {high} and {low} combined and translated to signed
|
||||
# 64-bit.
|
||||
def make_signed_int64(high, low)
|
||||
unsigned = (high << 32) | low
|
||||
unsigned >= 0x8000000000000000 ? unsigned - 0x10000000000000000 : unsigned
|
||||
end
|
||||
|
||||
# Reads the given number of bytes from the given file and checks that the
|
||||
# correct number of bytes could be read.
|
||||
#
|
||||
# @param file [IO] the file to read from.
|
||||
# @param bytes [Integer] the number of bytes to read.
|
||||
# @return [String] the bytes that were read.
|
||||
# @raise [InvalidZoneinfoFile] if the number of bytes available didn't
|
||||
# match the number requested.
|
||||
def check_read(file, bytes)
|
||||
result = file.read(bytes)
|
||||
|
||||
unless result && result.length == bytes
|
||||
raise InvalidZoneinfoFile, "Expected #{bytes} bytes reading '#{file.path}', but got #{result ? result.length : 0} bytes"
|
||||
end
|
||||
|
||||
result
|
||||
end
|
||||
|
||||
# Zoneinfo files don't include the offset from standard time (std_offset)
|
||||
# for DST periods. Derive the base offset (base_utc_offset) where DST is
|
||||
# observed from either the previous or next non-DST period.
|
||||
#
|
||||
# @param transitions [Array<Hash>] an `Array` of transition hashes.
|
||||
# @param offsets [Array<Hash>] an `Array` of offset hashes.
|
||||
# @return [Integer] the index of the offset to be used prior to the first
|
||||
# transition.
|
||||
def derive_offsets(transitions, offsets)
|
||||
# The first non-DST offset (if there is one) is the offset observed
|
||||
# before the first transition. Fall back to the first DST offset if
|
||||
# there are no non-DST offsets.
|
||||
first_non_dst_offset_index = offsets.index {|o| !o[:is_dst] }
|
||||
first_offset_index = first_non_dst_offset_index || 0
|
||||
return first_offset_index if transitions.empty?
|
||||
|
||||
# Determine the base_utc_offset of the next non-dst offset at each transition.
|
||||
base_utc_offset_from_next = nil
|
||||
|
||||
transitions.reverse_each do |transition|
|
||||
offset = offsets[transition[:offset]]
|
||||
if offset[:is_dst]
|
||||
transition[:base_utc_offset_from_next] = base_utc_offset_from_next if base_utc_offset_from_next
|
||||
else
|
||||
base_utc_offset_from_next = offset[:observed_utc_offset]
|
||||
end
|
||||
end
|
||||
|
||||
base_utc_offset_from_previous = first_non_dst_offset_index ? offsets[first_non_dst_offset_index][:observed_utc_offset] : nil
|
||||
defined_offsets = {}
|
||||
|
||||
transitions.each do |transition|
|
||||
offset_index = transition[:offset]
|
||||
offset = offsets[offset_index]
|
||||
observed_utc_offset = offset[:observed_utc_offset]
|
||||
|
||||
if offset[:is_dst]
|
||||
base_utc_offset_from_next = transition[:base_utc_offset_from_next]
|
||||
|
||||
difference_to_previous = (observed_utc_offset - (base_utc_offset_from_previous || observed_utc_offset)).abs
|
||||
difference_to_next = (observed_utc_offset - (base_utc_offset_from_next || observed_utc_offset)).abs
|
||||
|
||||
base_utc_offset = if difference_to_previous == 3600
|
||||
base_utc_offset_from_previous
|
||||
elsif difference_to_next == 3600
|
||||
base_utc_offset_from_next
|
||||
elsif difference_to_previous > 0 && difference_to_next > 0
|
||||
difference_to_previous < difference_to_next ? base_utc_offset_from_previous : base_utc_offset_from_next
|
||||
elsif difference_to_previous > 0
|
||||
base_utc_offset_from_previous
|
||||
elsif difference_to_next > 0
|
||||
base_utc_offset_from_next
|
||||
else
|
||||
# No difference, assume a 1 hour offset from standard time.
|
||||
observed_utc_offset - 3600
|
||||
end
|
||||
|
||||
if !offset[:base_utc_offset]
|
||||
offset[:base_utc_offset] = base_utc_offset
|
||||
defined_offsets[offset] = offset_index
|
||||
elsif offset[:base_utc_offset] != base_utc_offset
|
||||
# An earlier transition has already derived a different
|
||||
# base_utc_offset. Define a new offset or reuse an existing identically
|
||||
# defined offset.
|
||||
new_offset = offset.dup
|
||||
new_offset[:base_utc_offset] = base_utc_offset
|
||||
|
||||
offset_index = defined_offsets[new_offset]
|
||||
|
||||
unless offset_index
|
||||
offsets << new_offset
|
||||
offset_index = offsets.length - 1
|
||||
defined_offsets[new_offset] = offset_index
|
||||
end
|
||||
|
||||
transition[:offset] = offset_index
|
||||
end
|
||||
else
|
||||
base_utc_offset_from_previous = observed_utc_offset
|
||||
end
|
||||
end
|
||||
|
||||
first_offset_index
|
||||
end
|
||||
|
||||
# Determines if the offset from a transition matches the offset from a
|
||||
# rule. This is a looser match than equality, not requiring that the
|
||||
# base_utc_offset and std_offset both match (which have to be derived for
|
||||
# transitions, but are known for rules.
|
||||
#
|
||||
# @param offset [TimezoneOffset] an offset from a transition.
|
||||
# @param rule_offset [TimezoneOffset] an offset from a rule.
|
||||
# @return [Boolean] whether the offsets match.
|
||||
def offset_matches_rule?(offset, rule_offset)
|
||||
offset.observed_utc_offset == rule_offset.observed_utc_offset &&
|
||||
offset.dst? == rule_offset.dst? &&
|
||||
offset.abbreviation == rule_offset.abbreviation
|
||||
end
|
||||
|
||||
# Apply the rules from the TZ string when there were no defined
|
||||
# transitions. Checks for a matching offset. Returns the rules-based
|
||||
# constant offset or generates transitions from 1970 until 100 years into
|
||||
# the future (at the time of loading zoneinfo_reader.rb).
|
||||
#
|
||||
# @param file [IO] the file being processed.
|
||||
# @param first_offset [TimezoneOffset] the first offset included in the
|
||||
# file that would normally apply without the rules.
|
||||
# @param rules [Object] a {TimezoneOffset} specifying a constant offset or
|
||||
# {AnnualRules} instance specfying transitions.
|
||||
# @return [Object] either a {TimezoneOffset} or an `Array` of
|
||||
# {TimezoneTransition}s.
|
||||
# @raise [InvalidZoneinfoFile] if the first offset does not match the
|
||||
# rules.
|
||||
def apply_rules_without_transitions(file, first_offset, rules)
|
||||
if rules.kind_of?(TimezoneOffset)
|
||||
unless offset_matches_rule?(first_offset, rules)
|
||||
raise InvalidZoneinfoFile, "Constant offset POSIX-style TZ string does not match constant offset in file '#{file.path}'."
|
||||
end
|
||||
rules
|
||||
else
|
||||
transitions = 1970.upto(GENERATE_UP_TO).flat_map {|y| rules.transitions(y) }
|
||||
first_transition = transitions[0]
|
||||
|
||||
unless offset_matches_rule?(first_offset, first_transition.previous_offset)
|
||||
# Not transitioning from the designated first offset.
|
||||
|
||||
if offset_matches_rule?(first_offset, first_transition.offset)
|
||||
# Skip an unnecessary transition to the first offset.
|
||||
transitions.shift
|
||||
else
|
||||
# The initial offset doesn't match the ongoing rules. Replace the
|
||||
# previous offset of the first transition.
|
||||
transitions[0] = TimezoneTransition.new(first_transition.offset, first_offset, first_transition.timestamp_value)
|
||||
end
|
||||
end
|
||||
|
||||
transitions
|
||||
end
|
||||
end
|
||||
|
||||
# Finds an offset that is equivalent to the one specified in the given
|
||||
# `Array`. Matching is performed with {TimezoneOffset#==}.
|
||||
#
|
||||
# @param offsets [Array<TimezoneOffset>] an `Array` to search.
|
||||
# @param offset [TimezoneOffset] the offset to search for.
|
||||
# @return [TimezoneOffset] the matching offset from `offsets` or `nil`
|
||||
# if not found.
|
||||
def find_existing_offset(offsets, offset)
|
||||
offsets.find {|o| o == offset }
|
||||
end
|
||||
|
||||
# Returns a new AnnualRules instance with standard and daylight savings
|
||||
# offsets replaced with equivalents from an array. This reduces the memory
|
||||
# requirement for loaded time zones by reusing offsets for rule-generated
|
||||
# transitions.
|
||||
#
|
||||
# @param offsets [Array<TimezoneOffset>] an `Array` to search for
|
||||
# equivalent offsets.
|
||||
# @param annual_rules [AnnualRules] the {AnnualRules} instance to check.
|
||||
# @return [AnnualRules] either a new {AnnualRules} instance with either
|
||||
# the {AnnualRules#std_offset std_offset} or {AnnualRules#dst_offset
|
||||
# dst_offset} replaced, or the original instance if no equivalent for
|
||||
# either {AnnualRules#std_offset std_offset} or {AnnualRules#dst_offset
|
||||
# dst_offset} could be found.
|
||||
def replace_with_existing_offsets(offsets, annual_rules)
|
||||
existing_std_offset = find_existing_offset(offsets, annual_rules.std_offset)
|
||||
existing_dst_offset = find_existing_offset(offsets, annual_rules.dst_offset)
|
||||
if existing_std_offset || existing_dst_offset
|
||||
AnnualRules.new(existing_std_offset || annual_rules.std_offset, existing_dst_offset || annual_rules.dst_offset,
|
||||
annual_rules.dst_start_rule, annual_rules.dst_end_rule)
|
||||
else
|
||||
annual_rules
|
||||
end
|
||||
end
|
||||
|
||||
# Validates the offset indicated to be observed by the rules before the
|
||||
# first generated transition against the offset of the last defined
|
||||
# transition.
|
||||
#
|
||||
# Fix the last defined transition if it differ on just base/std offsets
|
||||
# (which are derived). Raise an error if the observed UTC offset or
|
||||
# abbreviations differ.
|
||||
#
|
||||
# @param file [IO] the file being processed.
|
||||
# @param last_defined [TimezoneTransition] the last defined transition in
|
||||
# the file.
|
||||
# @param first_rule_offset [TimezoneOffset] the offset the rules indicate
|
||||
# is observed prior to the first rules generated transition.
|
||||
# @return [TimezoneTransition] the last defined transition (either the
|
||||
# original instance or a replacement).
|
||||
# @raise [InvalidZoneinfoFile] if the offset of {last_defined} and
|
||||
# {first_rule_offset} do not match.
|
||||
def validate_and_fix_last_defined_transition_offset(file, last_defined, first_rule_offset)
|
||||
offset_of_last_defined = last_defined.offset
|
||||
|
||||
if offset_of_last_defined == first_rule_offset
|
||||
last_defined
|
||||
else
|
||||
if offset_matches_rule?(offset_of_last_defined, first_rule_offset)
|
||||
# The same overall offset, but differing in the base or std
|
||||
# offset (which are derived). Correct by using the rule.
|
||||
TimezoneTransition.new(first_rule_offset, last_defined.previous_offset, last_defined.timestamp_value)
|
||||
else
|
||||
raise InvalidZoneinfoFile, "The first offset indicated by the POSIX-style TZ string did not match the final defined offset in file '#{file.path}'."
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Apply the rules from the TZ string when there were defined
|
||||
# transitions. Checks for a matching offset with the last transition.
|
||||
# Redefines the last transition if required and if the rules don't
|
||||
# specific a constant offset, generates transitions until 100 years into
|
||||
# the future (at the time of loading zoneinfo_reader.rb).
|
||||
#
|
||||
# @param file [IO] the file being processed.
|
||||
# @param transitions [Array<TimezoneTransition>] the defined transitions.
|
||||
# @param offsets [Array<TimezoneOffset>] the offsets used by the defined
|
||||
# transitions.
|
||||
# @param rules [Object] a {TimezoneOffset} specifying a constant offset or
|
||||
# {AnnualRules} instance specfying transitions.
|
||||
# @raise [InvalidZoneinfoFile] if the first offset does not match the
|
||||
# rules.
|
||||
# @raise [InvalidZoneinfoFile] if the previous offset of the first
|
||||
# generated transition does not match the offset of the last defined
|
||||
# transition.
|
||||
def apply_rules_with_transitions(file, transitions, offsets, rules)
|
||||
last_defined = transitions[-1]
|
||||
|
||||
if rules.kind_of?(TimezoneOffset)
|
||||
transitions[-1] = validate_and_fix_last_defined_transition_offset(file, last_defined, rules)
|
||||
else
|
||||
last_year = last_defined.local_end_at.to_time.year
|
||||
|
||||
if last_year <= GENERATE_UP_TO
|
||||
rules = replace_with_existing_offsets(offsets, rules)
|
||||
|
||||
generated = rules.transitions(last_year).find_all do |t|
|
||||
t.timestamp_value > last_defined.timestamp_value && !offset_matches_rule?(last_defined.offset, t.offset)
|
||||
end
|
||||
|
||||
generated += (last_year + 1).upto(GENERATE_UP_TO).flat_map {|y| rules.transitions(y) }
|
||||
|
||||
unless generated.empty?
|
||||
transitions[-1] = validate_and_fix_last_defined_transition_offset(file, last_defined, generated[0].previous_offset)
|
||||
transitions.concat(generated)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Parses a zoneinfo file and returns either a {TimezoneOffset} that is
|
||||
# constantly observed or an `Array` of {TimezoneTransition}s.
|
||||
#
|
||||
# @param file [IO] the file to be read.
|
||||
# @return [Object] either a {TimezoneOffset} or an `Array` of
|
||||
# {TimezoneTransition}s.
|
||||
# @raise [InvalidZoneinfoFile] if the file is not a valid zoneinfo file.
|
||||
def parse(file)
|
||||
magic, version, ttisutccnt, ttisstdcnt, leapcnt, timecnt, typecnt, charcnt =
|
||||
check_read(file, 44).unpack('a4 a x15 NNNNNN')
|
||||
|
||||
if magic != 'TZif'
|
||||
raise InvalidZoneinfoFile, "The file '#{file.path}' does not start with the expected header."
|
||||
end
|
||||
|
||||
if version == '2' || version == '3'
|
||||
# Skip the first 32-bit section and read the header of the second 64-bit section
|
||||
file.seek(timecnt * 5 + typecnt * 6 + charcnt + leapcnt * 8 + ttisstdcnt + ttisutccnt, IO::SEEK_CUR)
|
||||
|
||||
prev_version = version
|
||||
|
||||
magic, version, ttisutccnt, ttisstdcnt, leapcnt, timecnt, typecnt, charcnt =
|
||||
check_read(file, 44).unpack('a4 a x15 NNNNNN')
|
||||
|
||||
unless magic == 'TZif' && (version == prev_version)
|
||||
raise InvalidZoneinfoFile, "The file '#{file.path}' contains an invalid 64-bit section header."
|
||||
end
|
||||
|
||||
using_64bit = true
|
||||
elsif version != '3' && version != '2' && version != "\0"
|
||||
raise InvalidZoneinfoFile, "The file '#{file.path}' contains a version of the zoneinfo format that is not currently supported."
|
||||
else
|
||||
using_64bit = false
|
||||
end
|
||||
|
||||
unless leapcnt == 0
|
||||
raise InvalidZoneinfoFile, "The file '#{file.path}' contains leap second data. TZInfo requires zoneinfo files that omit leap seconds."
|
||||
end
|
||||
|
||||
transitions = if using_64bit
|
||||
timecnt.times.map do |i|
|
||||
high, low = check_read(file, 8).unpack('NN'.freeze)
|
||||
transition_time = make_signed_int64(high, low)
|
||||
{at: transition_time}
|
||||
end
|
||||
else
|
||||
timecnt.times.map do |i|
|
||||
transition_time = make_signed_int32(check_read(file, 4).unpack('N'.freeze)[0])
|
||||
{at: transition_time}
|
||||
end
|
||||
end
|
||||
|
||||
check_read(file, timecnt).unpack('C*'.freeze).each_with_index do |localtime_type, i|
|
||||
raise InvalidZoneinfoFile, "Invalid offset referenced by transition in file '#{file.path}'." if localtime_type >= typecnt
|
||||
transitions[i][:offset] = localtime_type
|
||||
end
|
||||
|
||||
offsets = typecnt.times.map do |i|
|
||||
gmtoff, isdst, abbrind = check_read(file, 6).unpack('NCC'.freeze)
|
||||
gmtoff = make_signed_int32(gmtoff)
|
||||
isdst = isdst == 1
|
||||
{observed_utc_offset: gmtoff, is_dst: isdst, abbr_index: abbrind}
|
||||
end
|
||||
|
||||
abbrev = check_read(file, charcnt)
|
||||
|
||||
if using_64bit
|
||||
# Skip to the POSIX-style TZ string.
|
||||
file.seek(ttisstdcnt + ttisutccnt, IO::SEEK_CUR) # + leapcnt * 8, but leapcnt is checked above and guaranteed to be 0.
|
||||
tz_string_start = check_read(file, 1)
|
||||
raise InvalidZoneinfoFile, "Expected newline starting POSIX-style TZ string in file '#{file.path}'." unless tz_string_start == "\n"
|
||||
tz_string = file.readline("\n").force_encoding(Encoding::UTF_8)
|
||||
raise InvalidZoneinfoFile, "Expected newline ending POSIX-style TZ string in file '#{file.path}'." unless tz_string.chomp!("\n")
|
||||
|
||||
begin
|
||||
rules = @posix_tz_parser.parse(tz_string)
|
||||
rescue InvalidPosixTimeZone => e
|
||||
raise InvalidZoneinfoFile, "Failed to parse POSIX-style TZ string in file '#{file.path}': #{e}"
|
||||
end
|
||||
else
|
||||
rules = nil
|
||||
end
|
||||
|
||||
# Derive the offsets from standard time (std_offset).
|
||||
first_offset_index = derive_offsets(transitions, offsets)
|
||||
|
||||
offsets = offsets.map do |o|
|
||||
observed_utc_offset = o[:observed_utc_offset]
|
||||
base_utc_offset = o[:base_utc_offset]
|
||||
|
||||
if base_utc_offset
|
||||
# DST offset with base_utc_offset derived by derive_offsets.
|
||||
std_offset = observed_utc_offset - base_utc_offset
|
||||
elsif o[:is_dst]
|
||||
# DST offset unreferenced by a transition (offset in use before the
|
||||
# first transition). No derived base UTC offset, so assume 1 hour
|
||||
# DST.
|
||||
base_utc_offset = observed_utc_offset - 3600
|
||||
std_offset = 3600
|
||||
else
|
||||
# Non-DST offset.
|
||||
base_utc_offset = observed_utc_offset
|
||||
std_offset = 0
|
||||
end
|
||||
|
||||
abbrev_start = o[:abbr_index]
|
||||
raise InvalidZoneinfoFile, "Abbreviation index is out of range in file '#{file.path}'." unless abbrev_start < abbrev.length
|
||||
|
||||
abbrev_end = abbrev.index("\0", abbrev_start)
|
||||
raise InvalidZoneinfoFile, "Missing abbreviation null terminator in file '#{file.path}'." unless abbrev_end
|
||||
|
||||
abbr = @string_deduper.dedupe(RubyCoreSupport.untaint(abbrev[abbrev_start...abbrev_end].force_encoding(Encoding::UTF_8)))
|
||||
|
||||
TimezoneOffset.new(base_utc_offset, std_offset, abbr)
|
||||
end
|
||||
|
||||
first_offset = offsets[first_offset_index]
|
||||
|
||||
|
||||
if transitions.empty?
|
||||
if rules
|
||||
apply_rules_without_transitions(file, first_offset, rules)
|
||||
else
|
||||
first_offset
|
||||
end
|
||||
else
|
||||
previous_offset = first_offset
|
||||
previous_at = nil
|
||||
|
||||
transitions = transitions.map do |t|
|
||||
offset = offsets[t[:offset]]
|
||||
at = t[:at]
|
||||
raise InvalidZoneinfoFile, "Transition at #{at} is not later than the previous transition at #{previous_at} in file '#{file.path}'." if previous_at && previous_at >= at
|
||||
tt = TimezoneTransition.new(offset, previous_offset, at)
|
||||
previous_offset = offset
|
||||
previous_at = at
|
||||
tt
|
||||
end
|
||||
|
||||
apply_rules_with_transitions(file, transitions, offsets, rules) if rules
|
||||
transitions
|
||||
end
|
||||
end
|
||||
end
|
||||
private_constant :ZoneinfoReader
|
||||
end
|
||||
end
|
||||
@ -1,44 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
# Represents time zones that are defined by rules that set out when
|
||||
# transitions occur.
|
||||
class DataTimezone < InfoTimezone
|
||||
# (see Timezone#period_for)
|
||||
def period_for(time)
|
||||
raise ArgumentError, 'time must be specified' unless time
|
||||
timestamp = Timestamp.for(time)
|
||||
raise ArgumentError, 'time must have a specified utc_offset' unless timestamp.utc_offset
|
||||
info.period_for(timestamp)
|
||||
end
|
||||
|
||||
# (see Timezone#periods_for_local)
|
||||
def periods_for_local(local_time)
|
||||
raise ArgumentError, 'local_time must be specified' unless local_time
|
||||
info.periods_for_local(Timestamp.for(local_time, :ignore))
|
||||
end
|
||||
|
||||
# (see Timezone#transitions_up_to)
|
||||
def transitions_up_to(to, from = nil)
|
||||
raise ArgumentError, 'to must be specified' unless to
|
||||
to_timestamp = Timestamp.for(to)
|
||||
from_timestamp = from && Timestamp.for(from)
|
||||
|
||||
begin
|
||||
info.transitions_up_to(to_timestamp, from_timestamp)
|
||||
rescue ArgumentError => e
|
||||
raise ArgumentError, e.message.gsub('_timestamp', '')
|
||||
end
|
||||
end
|
||||
|
||||
# Returns the canonical {Timezone} instance for this {DataTimezone}.
|
||||
#
|
||||
# For a {DataTimezone}, this is always `self`.
|
||||
#
|
||||
# @return [Timezone] `self`.
|
||||
def canonical_zone
|
||||
self
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,153 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'date'
|
||||
|
||||
module TZInfo
|
||||
# A subclass of `DateTime` used to represent local times. {DateTimeWithOffset}
|
||||
# holds a reference to the related {TimezoneOffset} and overrides various
|
||||
# methods to return results appropriate for the {TimezoneOffset}. Certain
|
||||
# operations will clear the associated {TimezoneOffset} (if the
|
||||
# {TimezoneOffset} would not necessarily be valid for the result). Once the
|
||||
# {TimezoneOffset} has been cleared, {DateTimeWithOffset} behaves identically
|
||||
# to `DateTime`.
|
||||
#
|
||||
# Arithmetic performed on {DateTimeWithOffset} instances is _not_ time
|
||||
# zone-aware. Regardless of whether transitions in the time zone are crossed,
|
||||
# results of arithmetic operations will always maintain the same offset from
|
||||
# UTC (`offset`). The associated {TimezoneOffset} will aways be cleared.
|
||||
class DateTimeWithOffset < DateTime
|
||||
include WithOffset
|
||||
|
||||
# @return [TimezoneOffset] the {TimezoneOffset} associated with this
|
||||
# instance.
|
||||
attr_reader :timezone_offset
|
||||
|
||||
# Sets the associated {TimezoneOffset}.
|
||||
#
|
||||
# @param timezone_offset [TimezoneOffset] a {TimezoneOffset} valid at the
|
||||
# time and for the offset of this {DateTimeWithOffset}.
|
||||
# @return [DateTimeWithOffset] `self`.
|
||||
# @raise [ArgumentError] if `timezone_offset` is `nil`.
|
||||
# @raise [ArgumentError] if `timezone_offset.observed_utc_offset` does not
|
||||
# equal `self.offset * 86400`.
|
||||
def set_timezone_offset(timezone_offset)
|
||||
raise ArgumentError, 'timezone_offset must be specified' unless timezone_offset
|
||||
raise ArgumentError, 'timezone_offset.observed_utc_offset does not match self.utc_offset' if offset * 86400 != timezone_offset.observed_utc_offset
|
||||
@timezone_offset = timezone_offset
|
||||
self
|
||||
end
|
||||
|
||||
# An overridden version of `DateTime#to_time` that, if there is an
|
||||
# associated {TimezoneOffset}, returns a {DateTimeWithOffset} with that
|
||||
# offset.
|
||||
#
|
||||
# @return [Time] if there is an associated {TimezoneOffset}, a
|
||||
# {TimeWithOffset} representation of this {DateTimeWithOffset}, otherwise
|
||||
# a `Time` representation.
|
||||
def to_time
|
||||
if_timezone_offset(super) do |o,t|
|
||||
# Ruby 2.4.0 changed the behaviour of to_time so that it preserves the
|
||||
# offset instead of converting to the system local timezone.
|
||||
#
|
||||
# When self has an associated TimezonePeriod, this implementation will
|
||||
# preserve the offset on all versions of Ruby.
|
||||
TimeWithOffset.at(t.to_i, t.subsec * 1_000_000).set_timezone_offset(o)
|
||||
end
|
||||
end
|
||||
|
||||
# An overridden version of `DateTime#downto` that clears the associated
|
||||
# {TimezoneOffset} of the returned or yielded instances.
|
||||
def downto(min)
|
||||
if block_given?
|
||||
super {|dt| yield dt.clear_timezone_offset }
|
||||
else
|
||||
enum = super
|
||||
enum.each {|dt| dt.clear_timezone_offset }
|
||||
enum
|
||||
end
|
||||
end
|
||||
|
||||
# An overridden version of `DateTime#england` that preserves the associated
|
||||
# {TimezoneOffset}.
|
||||
#
|
||||
# @return [DateTime]
|
||||
def england
|
||||
# super doesn't call #new_start on MRI, so each method has to be
|
||||
# individually overridden.
|
||||
if_timezone_offset(super) {|o,dt| dt.set_timezone_offset(o) }
|
||||
end
|
||||
|
||||
# An overridden version of `DateTime#gregorian` that preserves the
|
||||
# associated {TimezoneOffset}.
|
||||
#
|
||||
# @return [DateTime]
|
||||
def gregorian
|
||||
# super doesn't call #new_start on MRI, so each method has to be
|
||||
# individually overridden.
|
||||
if_timezone_offset(super) {|o,dt| dt.set_timezone_offset(o) }
|
||||
end
|
||||
|
||||
# An overridden version of `DateTime#italy` that preserves the associated
|
||||
# {TimezoneOffset}.
|
||||
#
|
||||
# @return [DateTime]
|
||||
def italy
|
||||
# super doesn't call #new_start on MRI, so each method has to be
|
||||
# individually overridden.
|
||||
if_timezone_offset(super) {|o,dt| dt.set_timezone_offset(o) }
|
||||
end
|
||||
|
||||
# An overridden version of `DateTime#julian` that preserves the associated
|
||||
# {TimezoneOffset}.
|
||||
#
|
||||
# @return [DateTime]
|
||||
def julian
|
||||
# super doesn't call #new_start on MRI, so each method has to be
|
||||
# individually overridden.
|
||||
if_timezone_offset(super) {|o,dt| dt.set_timezone_offset(o) }
|
||||
end
|
||||
|
||||
# An overridden version of `DateTime#new_start` that preserves the
|
||||
# associated {TimezoneOffset}.
|
||||
#
|
||||
# @return [DateTime]
|
||||
def new_start(start = Date::ITALY)
|
||||
if_timezone_offset(super) {|o,dt| dt.set_timezone_offset(o) }
|
||||
end
|
||||
|
||||
# An overridden version of `DateTime#step` that clears the associated
|
||||
# {TimezoneOffset} of the returned or yielded instances.
|
||||
def step(limit, step = 1)
|
||||
if block_given?
|
||||
super {|dt| yield dt.clear_timezone_offset }
|
||||
else
|
||||
enum = super
|
||||
enum.each {|dt| dt.clear_timezone_offset }
|
||||
enum
|
||||
end
|
||||
end
|
||||
|
||||
# An overridden version of `DateTime#upto` that clears the associated
|
||||
# {TimezoneOffset} of the returned or yielded instances.
|
||||
def upto(max)
|
||||
if block_given?
|
||||
super {|dt| yield dt.clear_timezone_offset }
|
||||
else
|
||||
enum = super
|
||||
enum.each {|dt| dt.clear_timezone_offset }
|
||||
enum
|
||||
end
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
# Clears the associated {TimezoneOffset}.
|
||||
#
|
||||
# @return [DateTimeWithOffset] `self`.
|
||||
def clear_timezone_offset
|
||||
@timezone_offset = nil
|
||||
self
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,10 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
|
||||
module TZInfo
|
||||
# Modules and classes used by the format 1 version of TZInfo::Data.
|
||||
#
|
||||
# @private
|
||||
module Format1 #:nodoc:
|
||||
end
|
||||
private_constant :Format1
|
||||
end
|
||||
@ -1,17 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
|
||||
module TZInfo
|
||||
module Format1
|
||||
# Instances of {Format1::CountryDefiner} are yielded to the format 1 version
|
||||
# of `TZInfo::Data::Indexes::Countries` by {CountryIndexDefinition} to allow
|
||||
# the zones of a country to be specified.
|
||||
#
|
||||
# @private
|
||||
class CountryDefiner < Format2::CountryDefiner #:nodoc:
|
||||
# Initializes a new {CountryDefiner}.
|
||||
def initialize(identifier_deduper, description_deduper)
|
||||
super(nil, identifier_deduper, description_deduper)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,64 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
|
||||
module TZInfo
|
||||
module Format1
|
||||
# The format 1 TZInfo::Data country index file includes
|
||||
# {Format1::CountryIndexDefinition}, which provides a
|
||||
# {CountryIndexDefinition::ClassMethods#country country} method used to
|
||||
# define each country in the index.
|
||||
#
|
||||
# @private
|
||||
module CountryIndexDefinition #:nodoc:
|
||||
# Adds class methods to the includee and initializes class instance
|
||||
# variables.
|
||||
#
|
||||
# @param base [Module] the includee.
|
||||
def self.append_features(base)
|
||||
super
|
||||
base.extend(ClassMethods)
|
||||
base.instance_eval { @countries = {} }
|
||||
end
|
||||
|
||||
# Class methods for inclusion.
|
||||
#
|
||||
# @private
|
||||
module ClassMethods #:nodoc:
|
||||
# @return [Hash<String, DataSources::CountryInfo>] a frozen `Hash`
|
||||
# of all the countries that have been defined in the index keyed by
|
||||
# their codes.
|
||||
def countries
|
||||
@description_deduper = nil
|
||||
@countries.freeze
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Defines a country with an ISO 3166-1 alpha-2 country code and name.
|
||||
#
|
||||
# @param code [String] the ISO 3166-1 alpha-2 country code.
|
||||
# @param name [String] the name of the country.
|
||||
# @yield [definer] (optional) to obtain the time zones for the country.
|
||||
# @yieldparam definer [CountryDefiner] a {CountryDefiner} instance.
|
||||
def country(code, name)
|
||||
@description_deduper ||= StringDeduper.new
|
||||
|
||||
zones = if block_given?
|
||||
definer = CountryDefiner.new(StringDeduper.global, @description_deduper)
|
||||
yield definer
|
||||
definer.timezones
|
||||
else
|
||||
[]
|
||||
end
|
||||
|
||||
@countries[code.freeze] = DataSources::CountryInfo.new(code, name, zones)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Alias used by TZInfo::Data format1 releases.
|
||||
#
|
||||
# @private
|
||||
CountryIndexDefinition = Format1::CountryIndexDefinition #:nodoc:
|
||||
private_constant :CountryIndexDefinition
|
||||
end
|
||||
@ -1,64 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
module Format1
|
||||
# Instances of {Format1::TimezoneDefiner} are yielded to TZInfo::Data
|
||||
# format 1 modules by {TimezoneDefinition} to allow the offsets and
|
||||
# transitions of the time zone to be specified.
|
||||
#
|
||||
# @private
|
||||
class TimezoneDefiner < Format2::TimezoneDefiner #:nodoc:
|
||||
undef_method :subsequent_rules
|
||||
|
||||
# Defines an offset.
|
||||
#
|
||||
# @param id [Symbol] an arbitrary value used identify the offset in
|
||||
# subsequent calls to transition. It must be unique.
|
||||
# @param utc_offset [Integer] the base offset from UTC of the zone in
|
||||
# seconds. This does not include daylight savings time.
|
||||
# @param std_offset [Integer] the daylight savings offset from the base
|
||||
# offset in seconds. Typically either 0 or 3600.
|
||||
# @param abbreviation [Symbol] an abbreviation for the offset, for
|
||||
# example, `:EST` or `:EDT`.
|
||||
# @raise [ArgumentError] if another offset has already been defined with
|
||||
# the given id.
|
||||
def offset(id, utc_offset, std_offset, abbreviation)
|
||||
super(id, utc_offset, std_offset, abbreviation.to_s)
|
||||
end
|
||||
|
||||
# Defines a transition to a given offset.
|
||||
#
|
||||
# Transitions must be defined in increasing time order.
|
||||
#
|
||||
# @param year [Integer] the UTC year in which the transition occurs. Used
|
||||
# in earlier versions of TZInfo, but now ignored.
|
||||
# @param month [Integer] the UTC month in which the transition occurs.
|
||||
# Used in earlier versions of TZInfo, but now ignored.
|
||||
# @param offset_id [Symbol] references the id of a previously defined
|
||||
# offset (see #offset).
|
||||
# @param timestamp_value [Integer] the time the transition occurs as an
|
||||
# Integer number of seconds since 1970-01-01 00:00:00 UTC ignoring leap
|
||||
# seconds (i.e. each day is treated as if it were 86,400 seconds long).
|
||||
# @param datetime_numerator [Integer] the time of the transition as the
|
||||
# numerator of the `Rational` returned by `DateTime#ajd`. Used in
|
||||
# earlier versions of TZInfo, but now ignored.
|
||||
# @param datetime_denominator [Integer] the time of the transition as the
|
||||
# denominator of the `Rational` returned by `DateTime#ajd`. Used in
|
||||
# earlier versions of TZInfo, but now ignored.
|
||||
# @raise [ArgumentError] if `offset_id` does not reference a defined
|
||||
# offset.
|
||||
# @raise [ArgumentError] if `timestamp_value` is not greater than the
|
||||
# `timestamp_value` of the previously defined transition.
|
||||
# @raise [ArgumentError] if `datetime_numerator` is specified, but
|
||||
# `datetime_denominator` is not. In older versions of TZInfo, it was
|
||||
# possible to define a transition with the `DateTime` numerator as the
|
||||
# 4th parameter and the denominator as the 5th parameter. This style of
|
||||
# definition is not used in released versions of TZInfo::Data.
|
||||
def transition(year, month, offset_id, timestamp_value, datetime_numerator = nil, datetime_denominator = nil)
|
||||
raise ArgumentError, 'DateTime-only transitions are not supported' if datetime_numerator && !datetime_denominator
|
||||
super(offset_id, timestamp_value)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,39 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
|
||||
module TZInfo
|
||||
module Format1
|
||||
# {Format1::TimezoneDefinition} is included into format 1 time zone
|
||||
# definition modules and provides the methods for defining time zones.
|
||||
#
|
||||
# @private
|
||||
module TimezoneDefinition #:nodoc:
|
||||
# Adds class methods to the includee.
|
||||
#
|
||||
# @param base [Module] the includee.
|
||||
def self.append_features(base)
|
||||
super
|
||||
base.extend(Format2::TimezoneDefinition::ClassMethods)
|
||||
base.extend(ClassMethods)
|
||||
end
|
||||
|
||||
# Class methods for inclusion.
|
||||
#
|
||||
# @private
|
||||
module ClassMethods #:nodoc:
|
||||
private
|
||||
|
||||
# @return the class to be instantiated and yielded by
|
||||
# {Format2::TimezoneDefinition::ClassMethods#timezone}.
|
||||
def timezone_definer_class
|
||||
TimezoneDefiner
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Alias used by TZInfo::Data format1 releases.
|
||||
#
|
||||
# @private
|
||||
TimezoneDefinition = Format1::TimezoneDefinition #:nodoc:
|
||||
private_constant :TimezoneDefinition
|
||||
end
|
||||
@ -1,77 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
|
||||
module TZInfo
|
||||
module Format1
|
||||
# The format 1 TZInfo::Data time zone index file includes
|
||||
# {Format1::TimezoneIndexDefinition}, which provides methods used to define
|
||||
# time zones in the index.
|
||||
#
|
||||
# @private
|
||||
module TimezoneIndexDefinition #:nodoc:
|
||||
# Adds class methods to the includee and initializes class instance
|
||||
# variables.
|
||||
#
|
||||
# @param base [Module] the includee.
|
||||
def self.append_features(base)
|
||||
super
|
||||
base.extend(ClassMethods)
|
||||
base.instance_eval do
|
||||
@timezones = []
|
||||
@data_timezones = []
|
||||
@linked_timezones = []
|
||||
end
|
||||
end
|
||||
|
||||
# Class methods for inclusion.
|
||||
#
|
||||
# @private
|
||||
module ClassMethods #:nodoc:
|
||||
# @return [Array<String>] a frozen `Array` containing the identifiers of
|
||||
# all data time zones. Identifiers are sorted according to
|
||||
# `String#<=>`.
|
||||
def data_timezones
|
||||
unless @data_timezones.frozen?
|
||||
@data_timezones = @data_timezones.sort.freeze
|
||||
end
|
||||
@data_timezones
|
||||
end
|
||||
|
||||
# @return [Array<String>] a frozen `Array` containing the identifiers of
|
||||
# all linked time zones. Identifiers are sorted according to
|
||||
# `String#<=>`.
|
||||
def linked_timezones
|
||||
unless @linked_timezones.frozen?
|
||||
@linked_timezones = @linked_timezones.sort.freeze
|
||||
end
|
||||
@linked_timezones
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Adds a data time zone to the index.
|
||||
#
|
||||
# @param identifier [String] the time zone identifier.
|
||||
def timezone(identifier)
|
||||
identifier = StringDeduper.global.dedupe(identifier)
|
||||
@timezones << identifier
|
||||
@data_timezones << identifier
|
||||
end
|
||||
|
||||
# Adds a linked time zone to the index.
|
||||
#
|
||||
# @param identifier [String] the time zone identifier.
|
||||
def linked_timezone(identifier)
|
||||
identifier = StringDeduper.global.dedupe(identifier)
|
||||
@timezones << identifier
|
||||
@linked_timezones << identifier
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Alias used by TZInfo::Data format 1 releases.
|
||||
#
|
||||
# @private
|
||||
TimezoneIndexDefinition = Format1::TimezoneIndexDefinition #:nodoc:
|
||||
private_constant :TimezoneIndexDefinition
|
||||
end
|
||||
@ -1,10 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
|
||||
module TZInfo
|
||||
# Modules and classes used by the format 2 version of TZInfo::Data.
|
||||
#
|
||||
# @private
|
||||
module Format2 #:nodoc:
|
||||
end
|
||||
private_constant :Format2
|
||||
end
|
||||
@ -1,68 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
module Format2
|
||||
# Instances of {Format2::CountryDefiner} are yielded to the format 2 version
|
||||
# of `TZInfo::Data::Indexes::Countries` by {CountryIndexDefiner} to allow
|
||||
# the zones of a country to be specified.
|
||||
#
|
||||
# @private
|
||||
class CountryDefiner #:nodoc:
|
||||
# @return [Array<CountryTimezone>] the time zones observed in the country.
|
||||
attr_reader :timezones
|
||||
|
||||
# Initializes a new {CountryDefiner}.
|
||||
#
|
||||
# @param shared_timezones [Hash<Symbol, CountryTimezone>] a `Hash`
|
||||
# containing time zones shared by more than one country, keyed by a
|
||||
# unique reference.
|
||||
# @param identifier_deduper [StringDeduper] a {StringDeduper} instance to
|
||||
# use when deduping time zone identifiers.
|
||||
# @param description_deduper [StringDeduper] a {StringDeduper} instance to
|
||||
# use when deduping time zone descriptions.
|
||||
def initialize(shared_timezones, identifier_deduper, description_deduper)
|
||||
@shared_timezones = shared_timezones
|
||||
@identifier_deduper = identifier_deduper
|
||||
@description_deduper = description_deduper
|
||||
@timezones = []
|
||||
end
|
||||
|
||||
# @overload timezone(reference)
|
||||
# Defines a time zone of a country as a reference to a pre-defined
|
||||
# shared time zone.
|
||||
# @param reference [Symbol] a reference for a pre-defined shared time
|
||||
# zone.
|
||||
# @overload timezone(identifier, latitude_numerator, latitude_denominator, longitude_numerator, longitude_denominator, description)
|
||||
# Defines a (non-shared) time zone of a country. The latitude and
|
||||
# longitude are given as the numerator and denominator of a `Rational`.
|
||||
# @param identifier [String] the time zone identifier.
|
||||
# @param latitude_numerator [Integer] the numerator of the latitude.
|
||||
# @param latitude_denominator [Integer] the denominator of the latitude.
|
||||
# @param longitude_numerator [Integer] the numerator of the longitude.
|
||||
# @param longitude_denominator [Integer] the denominator of the
|
||||
# longitude.
|
||||
# @param description [String] an optional description for the time zone.
|
||||
def timezone(identifier_or_reference, latitude_numerator = nil,
|
||||
latitude_denominator = nil, longitude_numerator = nil,
|
||||
longitude_denominator = nil, description = nil)
|
||||
if latitude_numerator
|
||||
unless latitude_denominator && longitude_numerator && longitude_denominator
|
||||
raise ArgumentError, 'Either just a reference should be supplied, or the identifier, latitude and longitude must all be specified'
|
||||
end
|
||||
|
||||
# Dedupe non-frozen literals from format 1 on all Ruby versions and
|
||||
# format 2 on Ruby < 2.3 (without frozen_string_literal support).
|
||||
|
||||
@timezones << CountryTimezone.new(@identifier_deduper.dedupe(identifier_or_reference),
|
||||
Rational(latitude_numerator, latitude_denominator),
|
||||
Rational(longitude_numerator, longitude_denominator), description && @description_deduper.dedupe(description))
|
||||
else
|
||||
shared_timezone = @shared_timezones[identifier_or_reference]
|
||||
raise ArgumentError, "Unknown shared timezone: #{identifier_or_reference}" unless shared_timezone
|
||||
@timezones << shared_timezone
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,68 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
|
||||
module TZInfo
|
||||
module Format2
|
||||
# Instances of {Format2::CountryIndexDefiner} are yielded to the format 2
|
||||
# version of `TZInfo::Data::Indexes::Countries` by {CountryIndexDefinition}
|
||||
# to allow countries and their time zones to be specified.
|
||||
#
|
||||
# @private
|
||||
class CountryIndexDefiner #:nodoc:
|
||||
# @return [Hash<String, CountryInfo>] a `Hash` of all the countries that
|
||||
# have been defined in the index keyed by their codes.
|
||||
attr_reader :countries
|
||||
|
||||
# Initializes a new {CountryIndexDefiner}.
|
||||
#
|
||||
# @param identifier_deduper [StringDeduper] a {StringDeduper} instance to
|
||||
# use when deduping time zone identifiers.
|
||||
# @param description_deduper [StringDeduper] a {StringDeduper} instance to
|
||||
# use when deduping time zone descriptions.
|
||||
def initialize(identifier_deduper, description_deduper)
|
||||
@identifier_deduper = identifier_deduper
|
||||
@description_deduper = description_deduper
|
||||
@shared_timezones = {}
|
||||
@countries = {}
|
||||
end
|
||||
|
||||
# Defines a time zone shared by many countries with an reference for
|
||||
# subsequent use in country definitions. The latitude and longitude are
|
||||
# given as the numerator and denominator of a `Rational`.
|
||||
#
|
||||
# @param reference [Symbol] a unique reference for the time zone.
|
||||
# @param identifier [String] the time zone identifier.
|
||||
# @param latitude_numerator [Integer] the numerator of the latitude.
|
||||
# @param latitude_denominator [Integer] the denominator of the latitude.
|
||||
# @param longitude_numerator [Integer] the numerator of the longitude.
|
||||
# @param longitude_denominator [Integer] the denominator of the longitude.
|
||||
# @param description [String] an optional description for the time zone.
|
||||
def timezone(reference, identifier, latitude_numerator, latitude_denominator,
|
||||
longitude_numerator, longitude_denominator, description = nil)
|
||||
# Dedupe non-frozen literals from format 1 on all Ruby versions and
|
||||
# format 2 on Ruby < 2.3 (without frozen_string_literal support).
|
||||
@shared_timezones[reference] = CountryTimezone.new(@identifier_deduper.dedupe(identifier),
|
||||
Rational(latitude_numerator, latitude_denominator),
|
||||
Rational(longitude_numerator, longitude_denominator), description && @description_deduper.dedupe(description))
|
||||
end
|
||||
|
||||
# Defines a country.
|
||||
#
|
||||
# @param code [String] The ISO 3166-1 alpha-2 code of the country.
|
||||
# @param name [String] Then name of the country.
|
||||
# @yield [definer] yields (optional) to obtain the time zones for the
|
||||
# country.
|
||||
# @yieldparam definer [CountryDefiner] a {CountryDefiner}
|
||||
# instance that should be used to specify the time zones of the country.
|
||||
def country(code, name)
|
||||
timezones = if block_given?
|
||||
definer = CountryDefiner.new(@shared_timezones, @identifier_deduper, @description_deduper)
|
||||
yield definer
|
||||
definer.timezones
|
||||
else
|
||||
[]
|
||||
end
|
||||
@countries[code.freeze] = DataSources::CountryInfo.new(code, name, timezones)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,46 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
|
||||
module TZInfo
|
||||
module Format2
|
||||
# The format 2 country index file includes
|
||||
# {Format2::CountryIndexDefinition}, which provides a
|
||||
# {CountryIndexDefinition::ClassMethods#country_index country_index} method
|
||||
# used to define the country index.
|
||||
#
|
||||
# @private
|
||||
module CountryIndexDefinition #:nodoc:
|
||||
# Adds class methods to the includee and initializes class instance
|
||||
# variables.
|
||||
#
|
||||
# @param base [Module] the includee.
|
||||
def self.append_features(base)
|
||||
super
|
||||
base.extend(ClassMethods)
|
||||
base.instance_eval { @countries = {}.freeze }
|
||||
end
|
||||
|
||||
# Class methods for inclusion.
|
||||
#
|
||||
# @private
|
||||
module ClassMethods #:nodoc:
|
||||
# @return [Hash<String, DataSources::CountryInfo>] a frozen `Hash`
|
||||
# of all the countries that have been defined in the index keyed by
|
||||
# their codes.
|
||||
attr_reader :countries
|
||||
|
||||
private
|
||||
|
||||
# Defines the index.
|
||||
#
|
||||
# @yield [definer] yields to allow the index to be defined.
|
||||
# @yieldparam definer [CountryIndexDefiner] a {CountryIndexDefiner}
|
||||
# instance that should be used to define the index.
|
||||
def country_index
|
||||
definer = CountryIndexDefiner.new(StringDeduper.global, StringDeduper.new)
|
||||
yield definer
|
||||
@countries = definer.countries.freeze
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,94 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
module Format2
|
||||
# Instances of {TimezoneDefiner} are yielded to TZInfo::Data modules by
|
||||
# {TimezoneDefinition} to allow the offsets and transitions of the time zone
|
||||
# to be specified.
|
||||
#
|
||||
# @private
|
||||
class TimezoneDefiner #:nodoc:
|
||||
# @return [Array<TimezoneTransition>] the defined transitions of the time
|
||||
# zone.
|
||||
attr_reader :transitions
|
||||
|
||||
# Initializes a new TimezoneDefiner.
|
||||
#
|
||||
# @param string_deduper [StringDeduper] a {StringDeduper} instance to use
|
||||
# when deduping abbreviations.
|
||||
def initialize(string_deduper)
|
||||
@string_deduper = string_deduper
|
||||
@offsets = {}
|
||||
@transitions = []
|
||||
end
|
||||
|
||||
# Returns the first offset to be defined or `nil` if no offsets have been
|
||||
# defined. The first offset is observed before the time of the first
|
||||
# transition.
|
||||
#
|
||||
# @return [TimezoneOffset] the first offset to be defined or `nil` if no
|
||||
# offsets have been defined.
|
||||
def first_offset
|
||||
first = @offsets.first
|
||||
first && first.last
|
||||
end
|
||||
|
||||
# Defines an offset.
|
||||
#
|
||||
# @param id [Symbol] an arbitrary value used identify the offset in
|
||||
# subsequent calls to transition. It must be unique.
|
||||
# @param base_utc_offset [Integer] the base offset from UTC of the zone in
|
||||
# seconds. This does not include daylight savings time.
|
||||
# @param std_offset [Integer] the daylight savings offset from the base
|
||||
# offset in seconds. Typically either 0 or 3600.
|
||||
# @param abbreviation [String] an abbreviation for the offset, for
|
||||
# example, EST or EDT.
|
||||
# @raise [ArgumentError] if another offset has already been defined with
|
||||
# the given id.
|
||||
def offset(id, base_utc_offset, std_offset, abbreviation)
|
||||
raise ArgumentError, 'An offset has already been defined with the given id' if @offsets.has_key?(id)
|
||||
|
||||
# Dedupe non-frozen literals from format 1 on all Ruby versions and
|
||||
# format 2 on Ruby < 2.3 (without frozen_string_literal support).
|
||||
abbreviation = @string_deduper.dedupe(abbreviation)
|
||||
|
||||
offset = TimezoneOffset.new(base_utc_offset, std_offset, abbreviation)
|
||||
@offsets[id] = offset
|
||||
@previous_offset ||= offset
|
||||
end
|
||||
|
||||
# Defines a transition to a given offset.
|
||||
#
|
||||
# Transitions must be defined in increasing time order.
|
||||
#
|
||||
# @param offset_id [Symbol] references the id of a previously defined
|
||||
# offset.
|
||||
# @param timestamp_value [Integer] the time the transition occurs as a
|
||||
# number of seconds since 1970-01-01 00:00:00 UTC ignoring leap seconds
|
||||
# (i.e. each day is treated as if it were 86,400 seconds long).
|
||||
# @raise [ArgumentError] if `offset_id` does not reference a defined
|
||||
# offset.
|
||||
# @raise [ArgumentError] if `timestamp_value` is not greater than the
|
||||
# `timestamp_value` of the previously defined transition.
|
||||
def transition(offset_id, timestamp_value)
|
||||
offset = @offsets[offset_id]
|
||||
raise ArgumentError, 'offset_id has not been defined' unless offset
|
||||
raise ArgumentError, 'timestamp is not greater than the timestamp of the previously defined transition' if !@transitions.empty? && @transitions.last.timestamp_value >= timestamp_value
|
||||
@transitions << TimezoneTransition.new(offset, @previous_offset, timestamp_value)
|
||||
@previous_offset = offset
|
||||
end
|
||||
|
||||
# Defines the rules that will be used for handling instants after the last
|
||||
# transition.
|
||||
#
|
||||
# This method is currently just a placeholder for forward compatibility
|
||||
# that accepts and ignores any arguments passed.
|
||||
#
|
||||
# Support for subsequent rules will be added in a future version of TZInfo
|
||||
# and the rules will be included in format 2 releases of TZInfo::Data.
|
||||
def subsequent_rules(*args)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,73 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
|
||||
module TZInfo
|
||||
module Format2
|
||||
# {Format2::TimezoneDefinition} is included into format 2 time zone
|
||||
# definition modules and provides methods for defining time zones.
|
||||
#
|
||||
# @private
|
||||
module TimezoneDefinition #:nodoc:
|
||||
# Adds class methods to the includee.
|
||||
#
|
||||
# @param base [Module] the includee.
|
||||
def self.append_features(base)
|
||||
super
|
||||
base.extend(ClassMethods)
|
||||
end
|
||||
|
||||
# Class methods for inclusion.
|
||||
#
|
||||
# @private
|
||||
module ClassMethods #:nodoc:
|
||||
# @return [TimezoneInfo] the last time zone to be defined.
|
||||
def get
|
||||
@timezone
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# @return [Class] the class to be instantiated and yielded by
|
||||
# {#timezone}.
|
||||
def timezone_definer_class
|
||||
TimezoneDefiner
|
||||
end
|
||||
|
||||
# Defines a data time zone.
|
||||
#
|
||||
# @param identifier [String] the identifier of the time zone.
|
||||
# @yield [definer] yields to the caller to define the time zone.
|
||||
# @yieldparam definer [Object] an instance of the class returned by
|
||||
# {#timezone_definer_class}, typically {TimezoneDefiner}.
|
||||
def timezone(identifier)
|
||||
# Dedupe non-frozen literals from format 1 on all Ruby versions and
|
||||
# format 2 on Ruby < 2.3 (without frozen_string_literal support).
|
||||
string_deduper = StringDeduper.global
|
||||
identifier = string_deduper.dedupe(identifier)
|
||||
|
||||
definer = timezone_definer_class.new(string_deduper)
|
||||
yield definer
|
||||
transitions = definer.transitions
|
||||
|
||||
@timezone = if transitions.empty?
|
||||
DataSources::ConstantOffsetDataTimezoneInfo.new(identifier, definer.first_offset)
|
||||
else
|
||||
DataSources::TransitionsDataTimezoneInfo.new(identifier, transitions)
|
||||
end
|
||||
end
|
||||
|
||||
# Defines a linked time zone.
|
||||
#
|
||||
# @param identifier [String] the identifier of the time zone being
|
||||
# defined.
|
||||
# @param link_to_identifier [String] the identifier the new time zone
|
||||
# links to (is an alias for).
|
||||
def linked_timezone(identifier, link_to_identifier)
|
||||
# Dedupe non-frozen literals from format 1 on all Ruby versions and
|
||||
# format 2 on Ruby < 2.3 (without frozen_string_literal support).
|
||||
string_deduper = StringDeduper.global
|
||||
@timezone = DataSources::LinkedTimezoneInfo.new(string_deduper.dedupe(identifier), string_deduper.dedupe(link_to_identifier))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,45 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
|
||||
module TZInfo
|
||||
module Format2
|
||||
# Instances of {TimezoneIndexDefiner} are yielded by
|
||||
# {TimezoneIndexDefinition} to allow the time zone index to be defined.
|
||||
#
|
||||
# @private
|
||||
class TimezoneIndexDefiner #:nodoc:
|
||||
# @return [Array<String>] the identifiers of all data time zones.
|
||||
attr_reader :data_timezones
|
||||
|
||||
# @return [Array<String>] the identifiers of all linked time zones.
|
||||
attr_reader :linked_timezones
|
||||
|
||||
# Initializes a new TimezoneDefiner.
|
||||
#
|
||||
# @param string_deduper [StringDeduper] a {StringDeduper} instance to use
|
||||
# when deduping identifiers.
|
||||
def initialize(string_deduper)
|
||||
@string_deduper = string_deduper
|
||||
@data_timezones = []
|
||||
@linked_timezones = []
|
||||
end
|
||||
|
||||
# Adds a data time zone to the index.
|
||||
#
|
||||
# @param identifier [String] the time zone identifier.
|
||||
def data_timezone(identifier)
|
||||
# Dedupe non-frozen literals from format 1 on all Ruby versions and
|
||||
# format 2 on Ruby < 2.3 (without frozen_string_literal support).
|
||||
@data_timezones << @string_deduper.dedupe(identifier)
|
||||
end
|
||||
|
||||
# Adds a linked time zone to the index.
|
||||
#
|
||||
# @param identifier [String] the time zone identifier.
|
||||
def linked_timezone(identifier)
|
||||
# Dedupe non-frozen literals from format 1 on all Ruby versions and
|
||||
# format 2 on Ruby < 2.3 (without frozen_string_literal support).
|
||||
@linked_timezones << @string_deduper.dedupe(identifier)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,55 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
|
||||
module TZInfo
|
||||
module Format2
|
||||
# The format 2 time zone index file includes {TimezoneIndexDefinition},
|
||||
# which provides the {TimezoneIndexDefinition::ClassMethods#timezone_index
|
||||
# timezone_index} method used to define the index.
|
||||
#
|
||||
# @private
|
||||
module TimezoneIndexDefinition #:nodoc:
|
||||
# Adds class methods to the includee and initializes class instance
|
||||
# variables.
|
||||
#
|
||||
# @param base [Module] the includee.
|
||||
def self.append_features(base)
|
||||
super
|
||||
base.extend(ClassMethods)
|
||||
base.instance_eval do
|
||||
empty = [].freeze
|
||||
@timezones = empty
|
||||
@data_timezones = empty
|
||||
@linked_timezones = empty
|
||||
end
|
||||
end
|
||||
|
||||
# Class methods for inclusion.
|
||||
#
|
||||
# @private
|
||||
module ClassMethods #:nodoc:
|
||||
# @return [Array<String>] a frozen `Array` containing the identifiers of
|
||||
# all data time zones. Identifiers are sorted according to
|
||||
# `String#<=>`.
|
||||
attr_reader :data_timezones
|
||||
|
||||
# @return [Array<String>] a frozen `Array` containing the identifiers of
|
||||
# all linked time zones. Identifiers are sorted according to
|
||||
# `String#<=>`.
|
||||
attr_reader :linked_timezones
|
||||
|
||||
# Defines the index.
|
||||
#
|
||||
# @yield [definer] yields to the caller to allow the index to be
|
||||
# defined.
|
||||
# @yieldparam definer [TimezoneIndexDefiner] a {TimezoneIndexDefiner}
|
||||
# instance that should be used to define the index.
|
||||
def timezone_index
|
||||
definer = TimezoneIndexDefiner.new(StringDeduper.global)
|
||||
yield definer
|
||||
@data_timezones = definer.data_timezones.sort!.freeze
|
||||
@linked_timezones = definer.linked_timezones.sort!.freeze
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,35 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
|
||||
module TZInfo
|
||||
|
||||
# A {Timezone} based on a {DataSources::TimezoneInfo}.
|
||||
#
|
||||
# @abstract
|
||||
class InfoTimezone < Timezone
|
||||
# Initializes a new {InfoTimezone}.
|
||||
#
|
||||
# {InfoTimezone} instances should not normally be created directly. Use
|
||||
# the {Timezone.get} method to obtain {Timezone} instances.
|
||||
#
|
||||
# @param info [DataSources::TimezoneInfo] a {DataSources::TimezoneInfo}
|
||||
# instance supplied by a {DataSource} that will be used as the source of
|
||||
# data for this {InfoTimezone}.
|
||||
def initialize(info)
|
||||
super()
|
||||
@info = info
|
||||
end
|
||||
|
||||
# (see Timezone#identifier)
|
||||
def identifier
|
||||
@info.identifier
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
# @return [DataSources::TimezoneInfo] the {DataSources::TimezoneInfo} this
|
||||
# {InfoTimezone} is based on.
|
||||
def info
|
||||
@info
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,44 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
|
||||
module TZInfo
|
||||
# Represents time zones that are defined as a link to or alias for another
|
||||
# time zone.
|
||||
class LinkedTimezone < InfoTimezone
|
||||
# Initializes a new {LinkedTimezone}.
|
||||
#
|
||||
# {LinkedTimezone} instances should not normally be created directly. Use
|
||||
# the {Timezone.get} method to obtain {Timezone} instances.
|
||||
#
|
||||
# @param info [DataSources::LinkedTimezoneInfo] a
|
||||
# {DataSources::LinkedTimezoneInfo} instance supplied by a {DataSource}
|
||||
# that will be used as the source of data for this {LinkedTimezone}.
|
||||
def initialize(info)
|
||||
super
|
||||
@linked_timezone = Timezone.get(info.link_to_identifier)
|
||||
end
|
||||
|
||||
# (see Timezone#period_for)
|
||||
def period_for(time)
|
||||
@linked_timezone.period_for(time)
|
||||
end
|
||||
|
||||
# (see Timezone#periods_for_local)
|
||||
def periods_for_local(local_time)
|
||||
@linked_timezone.periods_for_local(local_time)
|
||||
end
|
||||
|
||||
# (see Timezone#transitions_up_to)
|
||||
def transitions_up_to(to, from = nil)
|
||||
@linked_timezone.transitions_up_to(to, from)
|
||||
end
|
||||
|
||||
# Returns the canonical {Timezone} instance for this {LinkedTimezone}.
|
||||
#
|
||||
# For a {LinkedTimezone}, this is the canonical zone of the link target.
|
||||
#
|
||||
# @return [Timezone] the canonical {Timezone} instance for this {Timezone}.
|
||||
def canonical_zone
|
||||
@linked_timezone.canonical_zone
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,42 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
|
||||
module TZInfo
|
||||
# Represents the infinite period of time in a time zone that constantly
|
||||
# observes the same offset from UTC (has an unbounded start and end).
|
||||
class OffsetTimezonePeriod < TimezonePeriod
|
||||
# Initializes an {OffsetTimezonePeriod}.
|
||||
#
|
||||
# @param offset [TimezoneOffset] the offset that is constantly observed.
|
||||
# @raise [ArgumentError] if `offset` is `nil`.
|
||||
def initialize(offset)
|
||||
super
|
||||
end
|
||||
|
||||
# @return [TimezoneTransition] the transition that defines the start of this
|
||||
# {TimezonePeriod}, always `nil` for {OffsetTimezonePeriod}.
|
||||
def start_transition
|
||||
nil
|
||||
end
|
||||
|
||||
# @return [TimezoneTransition] the transition that defines the end of this
|
||||
# {TimezonePeriod}, always `nil` for {OffsetTimezonePeriod}.
|
||||
def end_transition
|
||||
nil
|
||||
end
|
||||
|
||||
# Determines if this {OffsetTimezonePeriod} is equal to another instance.
|
||||
#
|
||||
# @param p [Object] the instance to test for equality.
|
||||
# @return [Boolean] `true` if `p` is a {OffsetTimezonePeriod} with the same
|
||||
# {offset}, otherwise `false`.
|
||||
def ==(p)
|
||||
p.kind_of?(OffsetTimezonePeriod) && offset == p.offset
|
||||
end
|
||||
alias eql? ==
|
||||
|
||||
# @return [Integer] a hash based on {offset}.
|
||||
def hash
|
||||
offset.hash
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,38 +0,0 @@
|
||||
module TZInfo
|
||||
|
||||
# Methods to support different versions of Ruby.
|
||||
#
|
||||
# @private
|
||||
module RubyCoreSupport #:nodoc:
|
||||
class << self
|
||||
# Object#untaint is deprecated and becomes a no-op in Ruby >= 2.7. It has
|
||||
# been removed from Ruby 3.2.
|
||||
if !Object.new.respond_to?(:untaint) || RUBY_VERSION =~ /\A(\d+)\.(\d+)(?:\.|\z)/ && ($1 == '2' && $2.to_i >= 7 || $1.to_i >= 3)
|
||||
# :nocov_functional_untaint:
|
||||
|
||||
# Returns the supplied `Object`
|
||||
#
|
||||
# @param o [Object] the `Object` to untaint.
|
||||
# @return [Object] `o`.
|
||||
def untaint(o)
|
||||
o
|
||||
end
|
||||
|
||||
# :nocov_functional_untaint:
|
||||
else
|
||||
# :nocov_no_functional_untaint:
|
||||
|
||||
# Untaints and returns the supplied `Object`.
|
||||
#
|
||||
# @param o [Object] the `Object` to untaint.
|
||||
# @return [Object] `o`.
|
||||
def untaint(o)
|
||||
o.untaint
|
||||
end
|
||||
|
||||
# :nocov_no_functional_untaint:
|
||||
end
|
||||
end
|
||||
end
|
||||
private_constant :RubyCoreSupport
|
||||
end
|
||||
@ -1,118 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'concurrent'
|
||||
|
||||
module TZInfo
|
||||
# Maintains a pool of `String` instances. The {#dedupe} method will return
|
||||
# either a pooled copy of a given `String` or add the instance to the pool.
|
||||
#
|
||||
# @private
|
||||
class StringDeduper #:nodoc:
|
||||
class << self
|
||||
# @return [StringDeduper] a globally available singleton instance of
|
||||
# {StringDeduper}. This instance is safe for use in concurrently
|
||||
# executing threads.
|
||||
attr_reader :global
|
||||
end
|
||||
|
||||
# Initializes a new {StringDeduper}.
|
||||
def initialize
|
||||
@strings = create_hash do |h, k|
|
||||
v = k.dup.freeze
|
||||
h[v] = v
|
||||
end
|
||||
end
|
||||
|
||||
# @param string [String] the string to deduplicate.
|
||||
# @return [bool] `string` if it is frozen, otherwise a frozen, possibly
|
||||
# pre-existing copy of `string`.
|
||||
def dedupe(string)
|
||||
return string if string.frozen?
|
||||
@strings[string]
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
# Creates a `Hash` to store pooled `String` instances.
|
||||
#
|
||||
# @param block [Proc] Default value block to be passed to `Hash.new`.
|
||||
# @return [Hash] a `Hash` to store pooled `String` instances.
|
||||
def create_hash(&block)
|
||||
Hash.new(&block)
|
||||
end
|
||||
end
|
||||
private_constant :StringDeduper
|
||||
|
||||
# A thread-safe version of {StringDeduper}.
|
||||
#
|
||||
# @private
|
||||
class ConcurrentStringDeduper < StringDeduper #:nodoc:
|
||||
protected
|
||||
|
||||
def create_hash(&block)
|
||||
Concurrent::Map.new(&block)
|
||||
end
|
||||
end
|
||||
private_constant :ConcurrentStringDeduper
|
||||
|
||||
|
||||
string_unary_minus_does_dedupe = if '0'.respond_to?(:-@)
|
||||
# :nocov_no_string_-@:
|
||||
s1 = -('0'.dup)
|
||||
s2 = -('0'.dup)
|
||||
s1.object_id == s2.object_id
|
||||
# :nocov_no_string_-@:
|
||||
else
|
||||
# :nocov_string_-@:
|
||||
false
|
||||
# :nocov_string_-@:
|
||||
end
|
||||
|
||||
if string_unary_minus_does_dedupe
|
||||
# :nocov_no_deduping_string_unary_minus:
|
||||
|
||||
# An implementation of {StringDeduper} using the `String#-@` method where
|
||||
# that method performs deduplication (Ruby 2.5 and later).
|
||||
#
|
||||
# Note that this is slightly different to the plain {StringDeduper}
|
||||
# implementation. In this implementation, frozen literal strings are already
|
||||
# in the pool and are candidates for being returned, even when passed
|
||||
# another equal frozen non-literal string. {StringDeduper} will always
|
||||
# return frozen strings.
|
||||
#
|
||||
# There are also differences in encoding handling. This implementation will
|
||||
# treat strings with different encodings as different strings.
|
||||
# {StringDeduper} will treat strings with the compatible encodings as the
|
||||
# same string.
|
||||
#
|
||||
# @private
|
||||
class UnaryMinusGlobalStringDeduper #:nodoc:
|
||||
# @param string [String] the string to deduplicate.
|
||||
# @return [bool] `string` if it is frozen, otherwise a frozen, possibly
|
||||
# pre-existing copy of `string`.
|
||||
def dedupe(string)
|
||||
# String#-@ on Ruby 2.6 will dedupe a frozen non-literal String. Ruby
|
||||
# 2.5 will just return frozen strings.
|
||||
#
|
||||
# The pooled implementation can't tell the difference between frozen
|
||||
# literals and frozen non-literals, so must always return frozen String
|
||||
# instances to avoid doing unncessary work when loading format 2
|
||||
# TZInfo::Data modules.
|
||||
#
|
||||
# For compatibility with the pooled implementation, just return frozen
|
||||
# string instances (acting like Ruby 2.5).
|
||||
return string if string.frozen?
|
||||
-string
|
||||
end
|
||||
end
|
||||
private_constant :UnaryMinusGlobalStringDeduper
|
||||
|
||||
StringDeduper.instance_variable_set(:@global, UnaryMinusGlobalStringDeduper.new)
|
||||
# :nocov_no_deduping_string_unary_minus:
|
||||
else
|
||||
# :nocov_deduping_string_unary_minus:
|
||||
StringDeduper.instance_variable_set(:@global, ConcurrentStringDeduper.new)
|
||||
# :nocov_deduping_string_unary_minus:
|
||||
end
|
||||
end
|
||||
@ -1,154 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
# A subclass of `Time` used to represent local times. {TimeWithOffset} holds a
|
||||
# reference to the related {TimezoneOffset} and overrides various methods to
|
||||
# return results appropriate for the {TimezoneOffset}. Certain operations will
|
||||
# clear the associated {TimezoneOffset} (if the {TimezoneOffset} would not
|
||||
# necessarily be valid for the result). Once the {TimezoneOffset} has been
|
||||
# cleared, {TimeWithOffset} behaves identically to `Time`.
|
||||
#
|
||||
# Arithmetic performed on {TimeWithOffset} instances is _not_ time zone-aware.
|
||||
# Regardless of whether transitions in the time zone are crossed, results of
|
||||
# arithmetic operations will always maintain the same offset from UTC
|
||||
# (`utc_offset`). The associated {TimezoneOffset} will aways be cleared.
|
||||
class TimeWithOffset < Time
|
||||
include WithOffset
|
||||
|
||||
# @return [TimezoneOffset] the {TimezoneOffset} associated with this
|
||||
# instance.
|
||||
attr_reader :timezone_offset
|
||||
|
||||
# Marks this {TimeWithOffset} as a local time with the UTC offset of a given
|
||||
# {TimezoneOffset} and sets the associated {TimezoneOffset}.
|
||||
#
|
||||
# @param timezone_offset [TimezoneOffset] the {TimezoneOffset} to use to set
|
||||
# the offset of this {TimeWithOffset}.
|
||||
# @return [TimeWithOffset] `self`.
|
||||
# @raise [ArgumentError] if `timezone_offset` is `nil`.
|
||||
def set_timezone_offset(timezone_offset)
|
||||
raise ArgumentError, 'timezone_offset must be specified' unless timezone_offset
|
||||
localtime(timezone_offset.observed_utc_offset)
|
||||
@timezone_offset = timezone_offset
|
||||
self
|
||||
end
|
||||
|
||||
# An overridden version of `Time#dst?` that, if there is an associated
|
||||
# {TimezoneOffset}, returns the result of calling {TimezoneOffset#dst? dst?}
|
||||
# on that offset.
|
||||
#
|
||||
# @return [Boolean] `true` if daylight savings time is being observed,
|
||||
# otherwise `false`.
|
||||
def dst?
|
||||
to = timezone_offset
|
||||
to ? to.dst? : super
|
||||
end
|
||||
alias isdst dst?
|
||||
|
||||
# An overridden version of `Time#getlocal` that clears the associated
|
||||
# {TimezoneOffset} if the base implementation of `getlocal` returns a
|
||||
# {TimeWithOffset}.
|
||||
#
|
||||
# @return [Time] a representation of the {TimeWithOffset} using either the
|
||||
# local time zone or the given offset.
|
||||
def getlocal(*args)
|
||||
# JRuby < 9.3 returns a Time in all cases.
|
||||
# JRuby >= 9.3 returns a Time when called with no arguments and a
|
||||
# TimeWithOffset with a timezone_offset assigned when called with an
|
||||
# offset argument.
|
||||
result = super
|
||||
result.clear_timezone_offset if result.kind_of?(TimeWithOffset)
|
||||
result
|
||||
end
|
||||
|
||||
# An overridden version of `Time#gmtime` that clears the associated
|
||||
# {TimezoneOffset}.
|
||||
#
|
||||
# @return [TimeWithOffset] `self`.
|
||||
def gmtime
|
||||
super
|
||||
@timezone_offset = nil
|
||||
self
|
||||
end
|
||||
|
||||
# An overridden version of `Time#localtime` that clears the associated
|
||||
# {TimezoneOffset}.
|
||||
#
|
||||
# @return [TimeWithOffset] `self`.
|
||||
def localtime(*args)
|
||||
super
|
||||
@timezone_offset = nil
|
||||
self
|
||||
end
|
||||
|
||||
# An overridden version of `Time#round` that, if there is an associated
|
||||
# {TimezoneOffset}, returns a {TimeWithOffset} preserving that offset.
|
||||
#
|
||||
# @return [Time] the rounded time.
|
||||
def round(ndigits = 0)
|
||||
if_timezone_offset(super) {|o,t| self.class.at(t.to_i, t.subsec * 1_000_000).set_timezone_offset(o) }
|
||||
end
|
||||
|
||||
# An overridden version of `Time#to_a`. The `isdst` (index 8) and `zone`
|
||||
# (index 9) elements of the array are set according to the associated
|
||||
# {TimezoneOffset}.
|
||||
#
|
||||
# @return [Array] an `Array` representation of the {TimeWithOffset}.
|
||||
def to_a
|
||||
if_timezone_offset(super) do |o,a|
|
||||
a[8] = o.dst?
|
||||
a[9] = o.abbreviation
|
||||
a
|
||||
end
|
||||
end
|
||||
|
||||
# An overridden version of `Time#utc` that clears the associated
|
||||
# {TimezoneOffset}.
|
||||
#
|
||||
# @return [TimeWithOffset] `self`.
|
||||
def utc
|
||||
super
|
||||
@timezone_offset = nil
|
||||
self
|
||||
end
|
||||
|
||||
# An overridden version of `Time#zone` that, if there is an associated
|
||||
# {TimezoneOffset}, returns the {TimezoneOffset#abbreviation abbreviation}
|
||||
# of that offset.
|
||||
#
|
||||
# @return [String] the {TimezoneOffset#abbreviation abbreviation} of the
|
||||
# associated {TimezoneOffset}, or the result from `Time#zone` if there is
|
||||
# no such offset.
|
||||
def zone
|
||||
to = timezone_offset
|
||||
to ? to.abbreviation : super
|
||||
end
|
||||
|
||||
# An overridden version of `Time#to_datetime` that, if there is an
|
||||
# associated {TimezoneOffset}, returns a {DateTimeWithOffset} with that
|
||||
# offset.
|
||||
#
|
||||
# @return [DateTime] if there is an associated {TimezoneOffset}, a
|
||||
# {DateTimeWithOffset} representation of this {TimeWithOffset}, otherwise
|
||||
# a `Time` representation.
|
||||
def to_datetime
|
||||
if_timezone_offset(super) do |o,dt|
|
||||
offset = dt.offset
|
||||
result = DateTimeWithOffset.jd(dt.jd + dt.day_fraction - offset)
|
||||
result = result.new_offset(offset) unless offset == 0
|
||||
result.set_timezone_offset(o)
|
||||
end
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
# Clears the associated {TimezoneOffset}.
|
||||
#
|
||||
# @return [TimeWithOffset] `self`.
|
||||
def clear_timezone_offset
|
||||
@timezone_offset = nil
|
||||
self
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,552 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
# A time represented as an `Integer` number of seconds since 1970-01-01
|
||||
# 00:00:00 UTC (ignoring leap seconds and using the proleptic Gregorian
|
||||
# calendar), the fraction through the second (sub_second as a `Rational`) and
|
||||
# an optional UTC offset. Like Ruby's `Time` class, {Timestamp} can
|
||||
# distinguish between a local time with a zero offset and a time specified
|
||||
# explicitly as UTC.
|
||||
class Timestamp
|
||||
include Comparable
|
||||
|
||||
# The Unix epoch (1970-01-01 00:00:00 UTC) as a chronological Julian day
|
||||
# number.
|
||||
JD_EPOCH = 2440588
|
||||
private_constant :JD_EPOCH
|
||||
|
||||
class << self
|
||||
# Returns a new {Timestamp} representing the (proleptic Gregorian
|
||||
# calendar) date and time specified by the supplied parameters.
|
||||
#
|
||||
# If `utc_offset` is `nil`, `:utc` or 0, the date and time parameters will
|
||||
# be interpreted as representing a UTC date and time. Otherwise the date
|
||||
# and time parameters will be interpreted as a local date and time with
|
||||
# the given offset.
|
||||
#
|
||||
# @param year [Integer] the year.
|
||||
# @param month [Integer] the month (1-12).
|
||||
# @param day [Integer] the day of the month (1-31).
|
||||
# @param hour [Integer] the hour (0-23).
|
||||
# @param minute [Integer] the minute (0-59).
|
||||
# @param second [Integer] the second (0-59).
|
||||
# @param sub_second [Numeric] the fractional part of the second as either
|
||||
# a `Rational` that is greater than or equal to 0 and less than 1, or
|
||||
# the `Integer` 0.
|
||||
# @param utc_offset [Object] either `nil` for a {Timestamp} without a
|
||||
# specified offset, an offset from UTC specified as an `Integer` number
|
||||
# of seconds or the `Symbol` `:utc`).
|
||||
# @return [Timestamp] a new {Timestamp} representing the specified
|
||||
# (proleptic Gregorian calendar) date and time.
|
||||
# @raise [ArgumentError] if either of `year`, `month`, `day`, `hour`,
|
||||
# `minute`, or `second` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `sub_second` is not a `Rational`, or the
|
||||
# `Integer` 0.
|
||||
# @raise [ArgumentError] if `utc_offset` is not `nil`, not an `Integer`
|
||||
# and not the `Symbol` `:utc`.
|
||||
# @raise [RangeError] if `month` is not between 1 and 12.
|
||||
# @raise [RangeError] if `day` is not between 1 and 31.
|
||||
# @raise [RangeError] if `hour` is not between 0 and 23.
|
||||
# @raise [RangeError] if `minute` is not between 0 and 59.
|
||||
# @raise [RangeError] if `second` is not between 0 and 59.
|
||||
# @raise [RangeError] if `sub_second` is a `Rational` but that is less
|
||||
# than 0 or greater than or equal to 1.
|
||||
def create(year, month = 1, day = 1, hour = 0, minute = 0, second = 0, sub_second = 0, utc_offset = nil)
|
||||
raise ArgumentError, 'year must be an Integer' unless year.kind_of?(Integer)
|
||||
raise ArgumentError, 'month must be an Integer' unless month.kind_of?(Integer)
|
||||
raise ArgumentError, 'day must be an Integer' unless day.kind_of?(Integer)
|
||||
raise ArgumentError, 'hour must be an Integer' unless hour.kind_of?(Integer)
|
||||
raise ArgumentError, 'minute must be an Integer' unless minute.kind_of?(Integer)
|
||||
raise ArgumentError, 'second must be an Integer' unless second.kind_of?(Integer)
|
||||
raise RangeError, 'month must be between 1 and 12' if month < 1 || month > 12
|
||||
raise RangeError, 'day must be between 1 and 31' if day < 1 || day > 31
|
||||
raise RangeError, 'hour must be between 0 and 23' if hour < 0 || hour > 23
|
||||
raise RangeError, 'minute must be between 0 and 59' if minute < 0 || minute > 59
|
||||
raise RangeError, 'second must be between 0 and 59' if second < 0 || second > 59
|
||||
|
||||
# Based on days_from_civil from https://howardhinnant.github.io/date_algorithms.html#days_from_civil
|
||||
after_february = month > 2
|
||||
year -= 1 unless after_february
|
||||
era = year / 400
|
||||
year_of_era = year - era * 400
|
||||
day_of_year = (153 * (month + (after_february ? -3 : 9)) + 2) / 5 + day - 1
|
||||
day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year
|
||||
days_since_epoch = era * 146097 + day_of_era - 719468
|
||||
value = ((days_since_epoch * 24 + hour) * 60 + minute) * 60 + second
|
||||
value -= utc_offset if utc_offset.kind_of?(Integer)
|
||||
|
||||
new(value, sub_second, utc_offset)
|
||||
end
|
||||
|
||||
# When used without a block, returns a {Timestamp} representation of a
|
||||
# given `Time`, `DateTime` or {Timestamp}.
|
||||
#
|
||||
# When called with a block, the {Timestamp} representation of `value` is
|
||||
# passed to the block. The block must then return a {Timestamp}, which
|
||||
# will be converted back to the type of the initial value. If the initial
|
||||
# value was a {Timestamp}, the block result will be returned. If the
|
||||
# initial value was a `DateTime`, a Gregorian `DateTime` will be returned.
|
||||
#
|
||||
# The UTC offset of `value` can either be preserved (the {Timestamp}
|
||||
# representation will have the same UTC offset as `value`), ignored (the
|
||||
# {Timestamp} representation will have no defined UTC offset), or treated
|
||||
# as though it were UTC (the {Timestamp} representation will have a
|
||||
# {utc_offset} of 0 and {utc?} will return `true`).
|
||||
#
|
||||
# @param value [Object] a `Time`, `DateTime` or {Timestamp}.
|
||||
# @param offset [Symbol] either `:preserve` to preserve the offset of
|
||||
# `value`, `:ignore` to ignore the offset of `value` and create a
|
||||
# {Timestamp} with an unspecified offset, or `:treat_as_utc` to treat
|
||||
# the offset of `value` as though it were UTC and create a UTC
|
||||
# {Timestamp}.
|
||||
# @yield [timestamp] if a block is provided, the {Timestamp}
|
||||
# representation is passed to the block.
|
||||
# @yieldparam timestamp [Timestamp] the {Timestamp} representation of
|
||||
# `value`.
|
||||
# @yieldreturn [Timestamp] a {Timestamp} to be converted back to the type
|
||||
# of `value`.
|
||||
# @return [Object] if called without a block, the {Timestamp}
|
||||
# representation of `value`, otherwise the result of the block,
|
||||
# converted back to the type of `value`.
|
||||
def for(value, offset = :preserve)
|
||||
raise ArgumentError, 'value must be specified' unless value
|
||||
|
||||
case offset
|
||||
when :ignore
|
||||
ignore_offset = true
|
||||
target_utc_offset = nil
|
||||
when :treat_as_utc
|
||||
ignore_offset = true
|
||||
target_utc_offset = :utc
|
||||
when :preserve
|
||||
ignore_offset = false
|
||||
target_utc_offset = nil
|
||||
else
|
||||
raise ArgumentError, 'offset must be :preserve, :ignore or :treat_as_utc'
|
||||
end
|
||||
|
||||
time_like = false
|
||||
timestamp = case value
|
||||
when Time
|
||||
for_time(value, ignore_offset, target_utc_offset)
|
||||
when DateTime
|
||||
for_datetime(value, ignore_offset, target_utc_offset)
|
||||
when Timestamp
|
||||
for_timestamp(value, ignore_offset, target_utc_offset)
|
||||
else
|
||||
raise ArgumentError, "#{value.class} values are not supported" unless is_time_like?(value)
|
||||
time_like = true
|
||||
for_time_like(value, ignore_offset, target_utc_offset)
|
||||
end
|
||||
|
||||
if block_given?
|
||||
result = yield timestamp
|
||||
raise ArgumentError, 'block must return a Timestamp' unless result.kind_of?(Timestamp)
|
||||
|
||||
case value
|
||||
when Time
|
||||
result.to_time
|
||||
when DateTime
|
||||
result.to_datetime
|
||||
else # A Time-like value or a Timestamp
|
||||
time_like ? result.to_time : result
|
||||
end
|
||||
else
|
||||
timestamp
|
||||
end
|
||||
end
|
||||
|
||||
# Creates a new UTC {Timestamp}.
|
||||
#
|
||||
# @param value [Integer] the number of seconds since 1970-01-01 00:00:00
|
||||
# UTC ignoring leap seconds.
|
||||
# @param sub_second [Numeric] the fractional part of the second as either
|
||||
# a `Rational` that is greater than or equal to 0 and less than 1, or
|
||||
# the `Integer` 0.
|
||||
# @raise [ArgumentError] if `value` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `sub_second` is not a `Rational`, or the
|
||||
# `Integer` 0.
|
||||
# @raise [RangeError] if `sub_second` is a `Rational` but that is less
|
||||
# than 0 or greater than or equal to 1.
|
||||
def utc(value, sub_second = 0)
|
||||
new(value, sub_second, :utc)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Constructs a new instance of `self` (i.e. {Timestamp} or a subclass of
|
||||
# {Timestamp}) without validating the parameters. This method is used
|
||||
# internally within {Timestamp} to avoid the overhead of checking
|
||||
# parameters.
|
||||
#
|
||||
# @param value [Integer] the number of seconds since 1970-01-01 00:00:00
|
||||
# UTC ignoring leap seconds.
|
||||
# @param sub_second [Numeric] the fractional part of the second as either
|
||||
# a `Rational` that is greater than or equal to 0 and less than 1, or
|
||||
# the `Integer` 0.
|
||||
# @param utc_offset [Object] either `nil` for a {Timestamp} without a
|
||||
# specified offset, an offset from UTC specified as an `Integer` number
|
||||
# of seconds or the `Symbol` `:utc`).
|
||||
# @return [Timestamp] a new instance of `self`.
|
||||
def new!(value, sub_second = 0, utc_offset = nil)
|
||||
result = allocate
|
||||
result.send(:initialize!, value, sub_second, utc_offset)
|
||||
result
|
||||
end
|
||||
|
||||
# Creates a {Timestamp} that represents a given `Time`, optionally
|
||||
# ignoring the offset.
|
||||
#
|
||||
# @param time [Time] a `Time`.
|
||||
# @param ignore_offset [Boolean] whether to ignore the offset of `time`.
|
||||
# @param target_utc_offset [Object] if `ignore_offset` is `true`, the UTC
|
||||
# offset of the result (`:utc`, `nil` or an `Integer`).
|
||||
# @return [Timestamp] the {Timestamp} representation of `time`.
|
||||
def for_time(time, ignore_offset, target_utc_offset)
|
||||
value = time.to_i
|
||||
sub_second = time.subsec
|
||||
|
||||
if ignore_offset
|
||||
utc_offset = target_utc_offset
|
||||
value += time.utc_offset
|
||||
elsif time.utc?
|
||||
utc_offset = :utc
|
||||
else
|
||||
utc_offset = time.utc_offset
|
||||
end
|
||||
|
||||
new!(value, sub_second, utc_offset)
|
||||
end
|
||||
|
||||
# Creates a {Timestamp} that represents a given `DateTime`, optionally
|
||||
# ignoring the offset.
|
||||
#
|
||||
# @param datetime [DateTime] a `DateTime`.
|
||||
# @param ignore_offset [Boolean] whether to ignore the offset of
|
||||
# `datetime`.
|
||||
# @param target_utc_offset [Object] if `ignore_offset` is `true`, the UTC
|
||||
# offset of the result (`:utc`, `nil` or an `Integer`).
|
||||
# @return [Timestamp] the {Timestamp} representation of `datetime`.
|
||||
def for_datetime(datetime, ignore_offset, target_utc_offset)
|
||||
value = (datetime.jd - JD_EPOCH) * 86400 + datetime.sec + datetime.min * 60 + datetime.hour * 3600
|
||||
sub_second = datetime.sec_fraction
|
||||
|
||||
if ignore_offset
|
||||
utc_offset = target_utc_offset
|
||||
else
|
||||
utc_offset = (datetime.offset * 86400).to_i
|
||||
value -= utc_offset
|
||||
end
|
||||
|
||||
new!(value, sub_second, utc_offset)
|
||||
end
|
||||
|
||||
# Returns a {Timestamp} that represents another {Timestamp}, optionally
|
||||
# ignoring the offset. If the result would be identical to `value`, the
|
||||
# same instance is returned. If the passed in value is an instance of a
|
||||
# subclass of {Timestamp}, then a new {Timestamp} will always be returned.
|
||||
#
|
||||
# @param timestamp [Timestamp] a {Timestamp}.
|
||||
# @param ignore_offset [Boolean] whether to ignore the offset of
|
||||
# `timestamp`.
|
||||
# @param target_utc_offset [Object] if `ignore_offset` is `true`, the UTC
|
||||
# offset of the result (`:utc`, `nil` or an `Integer`).
|
||||
# @return [Timestamp] a [Timestamp] representation of `timestamp`.
|
||||
def for_timestamp(timestamp, ignore_offset, target_utc_offset)
|
||||
if ignore_offset
|
||||
if target_utc_offset
|
||||
unless target_utc_offset == :utc && timestamp.utc? || timestamp.utc_offset == target_utc_offset
|
||||
return new!(timestamp.value + (timestamp.utc_offset || 0), timestamp.sub_second, target_utc_offset)
|
||||
end
|
||||
elsif timestamp.utc_offset
|
||||
return new!(timestamp.value + timestamp.utc_offset, timestamp.sub_second)
|
||||
end
|
||||
end
|
||||
|
||||
unless timestamp.instance_of?(Timestamp)
|
||||
# timestamp is identical in value, sub_second and utc_offset but is a
|
||||
# subclass (i.e. TimestampWithOffset). Return a new Timestamp
|
||||
# instance.
|
||||
return new!(timestamp.value, timestamp.sub_second, timestamp.utc? ? :utc : timestamp.utc_offset)
|
||||
end
|
||||
|
||||
timestamp
|
||||
end
|
||||
|
||||
# Determines if an object is like a `Time` (for the purposes of converting
|
||||
# to a {Timestamp} with {for}), responding to `to_i` and `subsec`.
|
||||
#
|
||||
# @param value [Object] an object to test.
|
||||
# @return [Boolean] `true` if the object is `Time`-like, otherwise
|
||||
# `false`.
|
||||
def is_time_like?(value)
|
||||
value.respond_to?(:to_i) && value.respond_to?(:subsec)
|
||||
end
|
||||
|
||||
# Creates a {Timestamp} that represents a given `Time`-like object,
|
||||
# optionally ignoring the offset (if the `time_like` responds to
|
||||
# `utc_offset`).
|
||||
#
|
||||
# @param time_like [Object] a `Time`-like object.
|
||||
# @param ignore_offset [Boolean] whether to ignore the offset of `time`.
|
||||
# @param target_utc_offset [Object] if `ignore_offset` is `true`, the UTC
|
||||
# offset of the result (`:utc`, `nil` or an `Integer`).
|
||||
# @return [Timestamp] the {Timestamp} representation of `time_like`.
|
||||
def for_time_like(time_like, ignore_offset, target_utc_offset)
|
||||
value = time_like.to_i
|
||||
sub_second = time_like.subsec.to_r
|
||||
|
||||
if ignore_offset
|
||||
utc_offset = target_utc_offset
|
||||
value += time_like.utc_offset.to_i if time_like.respond_to?(:utc_offset)
|
||||
elsif time_like.respond_to?(:utc_offset)
|
||||
utc_offset = time_like.utc_offset.to_i
|
||||
else
|
||||
utc_offset = 0
|
||||
end
|
||||
|
||||
new(value, sub_second, utc_offset)
|
||||
end
|
||||
end
|
||||
|
||||
# @return [Integer] the number of seconds since 1970-01-01 00:00:00 UTC
|
||||
# ignoring leap seconds (i.e. each day is treated as if it were 86,400
|
||||
# seconds long).
|
||||
attr_reader :value
|
||||
|
||||
# @return [Numeric] the fraction of a second elapsed since timestamp as
|
||||
# either a `Rational` or the `Integer` 0. Always greater than or equal to
|
||||
# 0 and less than 1.
|
||||
attr_reader :sub_second
|
||||
|
||||
# @return [Integer] the offset from UTC in seconds or `nil` if the
|
||||
# {Timestamp} doesn't have a specified offset.
|
||||
attr_reader :utc_offset
|
||||
|
||||
# Initializes a new {Timestamp}.
|
||||
#
|
||||
# @param value [Integer] the number of seconds since 1970-01-01 00:00:00 UTC
|
||||
# ignoring leap seconds.
|
||||
# @param sub_second [Numeric] the fractional part of the second as either a
|
||||
# `Rational` that is greater than or equal to 0 and less than 1, or
|
||||
# the `Integer` 0.
|
||||
# @param utc_offset [Object] either `nil` for a {Timestamp} without a
|
||||
# specified offset, an offset from UTC specified as an `Integer` number of
|
||||
# seconds or the `Symbol` `:utc`).
|
||||
# @raise [ArgumentError] if `value` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `sub_second` is not a `Rational`, or the
|
||||
# `Integer` 0.
|
||||
# @raise [RangeError] if `sub_second` is a `Rational` but that is less
|
||||
# than 0 or greater than or equal to 1.
|
||||
# @raise [ArgumentError] if `utc_offset` is not `nil`, not an `Integer` and
|
||||
# not the `Symbol` `:utc`.
|
||||
def initialize(value, sub_second = 0, utc_offset = nil)
|
||||
raise ArgumentError, 'value must be an Integer' unless value.kind_of?(Integer)
|
||||
raise ArgumentError, 'sub_second must be a Rational or the Integer 0' unless (sub_second.kind_of?(Integer) && sub_second == 0) || sub_second.kind_of?(Rational)
|
||||
raise RangeError, 'sub_second must be >= 0 and < 1' if sub_second < 0 || sub_second >= 1
|
||||
raise ArgumentError, 'utc_offset must be an Integer, :utc or nil' if utc_offset && utc_offset != :utc && !utc_offset.kind_of?(Integer)
|
||||
initialize!(value, sub_second, utc_offset)
|
||||
end
|
||||
|
||||
# @return [Boolean] `true` if this {Timestamp} represents UTC, `false` if
|
||||
# the {Timestamp} wasn't specified as UTC or `nil` if the {Timestamp} has
|
||||
# no specified offset.
|
||||
def utc?
|
||||
@utc
|
||||
end
|
||||
|
||||
# Adds a number of seconds to the {Timestamp} value, setting the UTC offset
|
||||
# of the result.
|
||||
#
|
||||
# @param seconds [Integer] the number of seconds to be added.
|
||||
# @param utc_offset [Object] either `nil` for a {Timestamp} without a
|
||||
# specified offset, an offset from UTC specified as an `Integer` number of
|
||||
# seconds or the `Symbol` `:utc`).
|
||||
# @return [Timestamp] the result of adding `seconds` to the
|
||||
# {Timestamp} value as a new {Timestamp} instance with the chosen
|
||||
# `utc_offset`.
|
||||
# @raise [ArgumentError] if `seconds` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `utc_offset` is not `nil`, not an `Integer` and
|
||||
# not the `Symbol` `:utc`.
|
||||
def add_and_set_utc_offset(seconds, utc_offset)
|
||||
raise ArgumentError, 'seconds must be an Integer' unless seconds.kind_of?(Integer)
|
||||
raise ArgumentError, 'utc_offset must be an Integer, :utc or nil' if utc_offset && utc_offset != :utc && !utc_offset.kind_of?(Integer)
|
||||
return self if seconds == 0 && utc_offset == (@utc ? :utc : @utc_offset)
|
||||
Timestamp.send(:new!, @value + seconds, @sub_second, utc_offset)
|
||||
end
|
||||
|
||||
# @return [Timestamp] a UTC {Timestamp} equivalent to this instance. Returns
|
||||
# `self` if {#utc? self.utc?} is `true`.
|
||||
def utc
|
||||
return self if @utc
|
||||
Timestamp.send(:new!, @value, @sub_second, :utc)
|
||||
end
|
||||
|
||||
# Converts this {Timestamp} to a `Time`.
|
||||
#
|
||||
# @return [Time] a `Time` representation of this {Timestamp}. If the UTC
|
||||
# offset of this {Timestamp} is not specified, a UTC `Time` will be
|
||||
# returned.
|
||||
def to_time
|
||||
time = new_time
|
||||
|
||||
if @utc_offset && !@utc
|
||||
time.localtime(@utc_offset)
|
||||
else
|
||||
time.utc
|
||||
end
|
||||
end
|
||||
|
||||
# Converts this {Timestamp} to a Gregorian `DateTime`.
|
||||
#
|
||||
# @return [DateTime] a Gregorian `DateTime` representation of this
|
||||
# {Timestamp}. If the UTC offset of this {Timestamp} is not specified, a
|
||||
# UTC `DateTime` will be returned.
|
||||
def to_datetime
|
||||
new_datetime
|
||||
end
|
||||
|
||||
# Converts this {Timestamp} to an `Integer` number of seconds since
|
||||
# 1970-01-01 00:00:00 UTC (ignoring leap seconds).
|
||||
#
|
||||
# @return [Integer] an `Integer` representation of this {Timestamp} (the
|
||||
# number of seconds since 1970-01-01 00:00:00 UTC ignoring leap seconds).
|
||||
def to_i
|
||||
value
|
||||
end
|
||||
|
||||
# Formats this {Timestamp} according to the directives in the given format
|
||||
# string.
|
||||
#
|
||||
# @param format [String] the format string. Please refer to `Time#strftime`
|
||||
# for a list of supported format directives.
|
||||
# @return [String] the formatted {Timestamp}.
|
||||
# @raise [ArgumentError] if `format` is not specified.
|
||||
def strftime(format)
|
||||
raise ArgumentError, 'format must be specified' unless format
|
||||
to_time.strftime(format)
|
||||
end
|
||||
|
||||
# @return [String] a `String` representation of this {Timestamp}.
|
||||
def to_s
|
||||
return value_and_sub_second_to_s unless @utc_offset
|
||||
return "#{value_and_sub_second_to_s} UTC" if @utc
|
||||
|
||||
sign = @utc_offset >= 0 ? '+' : '-'
|
||||
min, sec = @utc_offset.abs.divmod(60)
|
||||
hour, min = min.divmod(60)
|
||||
|
||||
"#{value_and_sub_second_to_s(@utc_offset)} #{sign}#{'%02d' % hour}:#{'%02d' % min}#{sec > 0 ? ':%02d' % sec : nil}#{@utc_offset != 0 ? " (#{value_and_sub_second_to_s} UTC)" : nil}"
|
||||
end
|
||||
|
||||
# Compares this {Timestamp} with another.
|
||||
#
|
||||
# {Timestamp} instances without a defined UTC offset are not comparable with
|
||||
# {Timestamp} instances that have a defined UTC offset.
|
||||
#
|
||||
# @param t [Timestamp] the {Timestamp} to compare this instance with.
|
||||
# @return [Integer] -1, 0 or 1 depending if this instance is earlier, equal
|
||||
# or later than `t` respectively. Returns `nil` when comparing a
|
||||
# {Timestamp} that does not have a defined UTC offset with a {Timestamp}
|
||||
# that does have a defined UTC offset. Returns `nil` if `t` is not a
|
||||
# {Timestamp}.
|
||||
def <=>(t)
|
||||
return nil unless t.kind_of?(Timestamp)
|
||||
return nil if utc_offset && !t.utc_offset
|
||||
return nil if !utc_offset && t.utc_offset
|
||||
|
||||
result = value <=> t.value
|
||||
result = sub_second <=> t.sub_second if result == 0
|
||||
result
|
||||
end
|
||||
|
||||
alias eql? ==
|
||||
|
||||
# @return [Integer] a hash based on the value, sub-second and whether there
|
||||
# is a defined UTC offset.
|
||||
def hash
|
||||
[@value, @sub_second, !!@utc_offset].hash
|
||||
end
|
||||
|
||||
# @return [String] the internal object state as a programmer-readable
|
||||
# `String`.
|
||||
def inspect
|
||||
"#<#{self.class}: @value=#{@value}, @sub_second=#{@sub_second}, @utc_offset=#{@utc_offset.inspect}, @utc=#{@utc.inspect}>"
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
# Creates a new instance of a `Time` or `Time`-like class matching the
|
||||
# {value} and {sub_second} of this {Timestamp}, but not setting the offset.
|
||||
#
|
||||
# @param klass [Class] the class to instantiate.
|
||||
#
|
||||
# @private
|
||||
def new_time(klass = Time)
|
||||
klass.at(@value, @sub_second * 1_000_000)
|
||||
end
|
||||
|
||||
# Constructs a new instance of a `DateTime` or `DateTime`-like class with
|
||||
# the same {value}, {sub_second} and {utc_offset} as this {Timestamp}.
|
||||
#
|
||||
# @param klass [Class] the class to instantiate.
|
||||
#
|
||||
# @private
|
||||
def new_datetime(klass = DateTime)
|
||||
# Can't specify the start parameter unless the jd parameter is an exact number of days.
|
||||
# Use #gregorian instead.
|
||||
datetime = klass.jd(JD_EPOCH + ((@value.to_r + @sub_second) / 86400)).gregorian
|
||||
@utc_offset && @utc_offset != 0 ? datetime.new_offset(Rational(@utc_offset, 86400)) : datetime
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Converts the value and sub-seconds to a `String`, adding on the given
|
||||
# offset.
|
||||
#
|
||||
# @param offset [Integer] the offset to add to the value.
|
||||
# @return [String] the value and sub-seconds.
|
||||
def value_and_sub_second_to_s(offset = 0)
|
||||
"#{@value + offset}#{sub_second_to_s}"
|
||||
end
|
||||
|
||||
# Converts the {sub_second} value to a `String` suitable for appending to
|
||||
# the `String` representation of a {Timestamp}.
|
||||
#
|
||||
# @return [String] a `String` representation of {sub_second}.
|
||||
def sub_second_to_s
|
||||
if @sub_second == 0
|
||||
''
|
||||
else
|
||||
" #{@sub_second.numerator}/#{@sub_second.denominator}"
|
||||
end
|
||||
end
|
||||
|
||||
# Initializes a new {Timestamp} without validating the parameters. This
|
||||
# method is used internally within {Timestamp} to avoid the overhead of
|
||||
# checking parameters.
|
||||
#
|
||||
# @param value [Integer] the number of seconds since 1970-01-01 00:00:00 UTC
|
||||
# ignoring leap seconds.
|
||||
# @param sub_second [Numeric] the fractional part of the second as either a
|
||||
# `Rational` that is greater than or equal to 0 and less than 1, or the
|
||||
# `Integer` 0.
|
||||
# @param utc_offset [Object] either `nil` for a {Timestamp} without a
|
||||
# specified offset, an offset from UTC specified as an `Integer` number of
|
||||
# seconds or the `Symbol` `:utc`).
|
||||
def initialize!(value, sub_second = 0, utc_offset = nil)
|
||||
@value = value
|
||||
|
||||
# Convert Rational(0,1) to 0.
|
||||
@sub_second = sub_second == 0 ? 0 : sub_second
|
||||
|
||||
if utc_offset
|
||||
@utc = utc_offset == :utc
|
||||
@utc_offset = @utc ? 0 : utc_offset
|
||||
else
|
||||
@utc = @utc_offset = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,85 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
# A subclass of {Timestamp} used to represent local times.
|
||||
# {TimestampWithOffset} holds a reference to the related {TimezoneOffset} and
|
||||
# overrides various methods to return results appropriate for the
|
||||
# {TimezoneOffset}. Certain operations will clear the associated
|
||||
# {TimezoneOffset} (if the {TimezoneOffset} would not necessarily be valid for
|
||||
# the result). Once the {TimezoneOffset} has been cleared,
|
||||
# {TimestampWithOffset} behaves identically to {Timestamp}.
|
||||
class TimestampWithOffset < Timestamp
|
||||
include WithOffset
|
||||
|
||||
# @return [TimezoneOffset] the {TimezoneOffset} associated with this
|
||||
# instance.
|
||||
attr_reader :timezone_offset
|
||||
|
||||
# Creates a new {TimestampWithOffset} from a given {Timestamp} and
|
||||
# {TimezoneOffset}.
|
||||
#
|
||||
# @param timestamp [Timestamp] a {Timestamp}.
|
||||
# @param timezone_offset [TimezoneOffset] a {TimezoneOffset} valid at the
|
||||
# time of `timestamp`.
|
||||
# @return [TimestampWithOffset] a {TimestampWithOffset} that has the same
|
||||
# {value value} and {sub_second sub_second} as the `timestamp` parameter,
|
||||
# a {utc_offset utc_offset} equal to the
|
||||
# {TimezoneOffset#observed_utc_offset observed_utc_offset} of the
|
||||
# `timezone_offset` parameter and {timezone_offset timezone_offset} set to
|
||||
# the `timezone_offset` parameter.
|
||||
# @raise [ArgumentError] if `timestamp` or `timezone_offset` is `nil`.
|
||||
def self.set_timezone_offset(timestamp, timezone_offset)
|
||||
raise ArgumentError, 'timestamp must be specified' unless timestamp
|
||||
raise ArgumentError, 'timezone_offset must be specified' unless timezone_offset
|
||||
new!(timestamp.value, timestamp.sub_second, timezone_offset.observed_utc_offset).set_timezone_offset(timezone_offset)
|
||||
end
|
||||
|
||||
# Sets the associated {TimezoneOffset} of this {TimestampWithOffset}.
|
||||
#
|
||||
# @param timezone_offset [TimezoneOffset] a {TimezoneOffset} valid at the time
|
||||
# and for the offset of this {TimestampWithOffset}.
|
||||
# @return [TimestampWithOffset] `self`.
|
||||
# @raise [ArgumentError] if `timezone_offset` is `nil`.
|
||||
# @raise [ArgumentError] if {utc? self.utc?} is `true`.
|
||||
# @raise [ArgumentError] if `timezone_offset.observed_utc_offset` does not equal
|
||||
# `self.utc_offset`.
|
||||
def set_timezone_offset(timezone_offset)
|
||||
raise ArgumentError, 'timezone_offset must be specified' unless timezone_offset
|
||||
raise ArgumentError, 'timezone_offset.observed_utc_offset does not match self.utc_offset' if utc? || utc_offset != timezone_offset.observed_utc_offset
|
||||
@timezone_offset = timezone_offset
|
||||
self
|
||||
end
|
||||
|
||||
# An overridden version of {Timestamp#to_time} that, if there is an
|
||||
# associated {TimezoneOffset}, returns a {TimeWithOffset} with that offset.
|
||||
#
|
||||
# @return [Time] if there is an associated {TimezoneOffset}, a
|
||||
# {TimeWithOffset} representation of this {TimestampWithOffset}, otherwise
|
||||
# a `Time` representation.
|
||||
def to_time
|
||||
to = timezone_offset
|
||||
if to
|
||||
new_time(TimeWithOffset).set_timezone_offset(to)
|
||||
else
|
||||
super
|
||||
end
|
||||
end
|
||||
|
||||
# An overridden version of {Timestamp#to_datetime}, if there is an
|
||||
# associated {TimezoneOffset}, returns a {DateTimeWithOffset} with that
|
||||
# offset.
|
||||
#
|
||||
# @return [DateTime] if there is an associated {TimezoneOffset}, a
|
||||
# {DateTimeWithOffset} representation of this {TimestampWithOffset},
|
||||
# otherwise a `DateTime` representation.
|
||||
def to_datetime
|
||||
to = timezone_offset
|
||||
if to
|
||||
new_datetime(DateTimeWithOffset).set_timezone_offset(to)
|
||||
else
|
||||
super
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,111 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
# Represents an offset from UTC observed by a time zone.
|
||||
class TimezoneOffset
|
||||
# Returns the base offset from UTC in seconds (`observed_utc_offset -
|
||||
# std_offset`). This does not include any adjustment made for daylight
|
||||
# savings time and will typically remain constant throughout the year.
|
||||
#
|
||||
# To obtain the currently observed offset from UTC, including the effect of
|
||||
# daylight savings time, use {observed_utc_offset} instead.
|
||||
#
|
||||
# If you require accurate {base_utc_offset} values, you should install the
|
||||
# tzinfo-data gem and set {DataSources::RubyDataSource} as the {DataSource}.
|
||||
# When using {DataSources::ZoneinfoDataSource}, the value of
|
||||
# {base_utc_offset} has to be derived from changes to the observed UTC
|
||||
# offset and DST status since it is not included in zoneinfo files.
|
||||
#
|
||||
# @return [Integer] the base offset from UTC in seconds.
|
||||
attr_reader :base_utc_offset
|
||||
alias utc_offset base_utc_offset
|
||||
|
||||
# Returns the offset from the time zone's standard time in seconds
|
||||
# (`observed_utc_offset - base_utc_offset`). Zero when daylight savings time
|
||||
# is not in effect. Non-zero (usually 3600 = 1 hour) if daylight savings is
|
||||
# being observed.
|
||||
#
|
||||
# If you require accurate {std_offset} values, you should install the
|
||||
# tzinfo-data gem and set {DataSources::RubyDataSource} as the {DataSource}.
|
||||
# When using {DataSources::ZoneinfoDataSource}, the value of {std_offset}
|
||||
# has to be derived from changes to the observed UTC offset and DST status
|
||||
# since it is not included in zoneinfo files.
|
||||
#
|
||||
# @return [Integer] the offset from the time zone's standard time in
|
||||
# seconds.
|
||||
attr_reader :std_offset
|
||||
|
||||
# Returns the observed offset from UTC in seconds (`base_utc_offset +
|
||||
# std_offset`). This includes adjustments made for daylight savings time.
|
||||
#
|
||||
# @return [Integer] the observed offset from UTC in seconds.
|
||||
attr_reader :observed_utc_offset
|
||||
alias utc_total_offset observed_utc_offset
|
||||
|
||||
# The abbreviation that identifies this offset. For example GMT
|
||||
# (Greenwich Mean Time) or BST (British Summer Time) for Europe/London.
|
||||
#
|
||||
# @return [String] the abbreviation that identifies this offset.
|
||||
attr_reader :abbreviation
|
||||
alias abbr abbreviation
|
||||
|
||||
# Initializes a new {TimezoneOffset}.
|
||||
#
|
||||
# {TimezoneOffset} instances should not normally be constructed manually.
|
||||
#
|
||||
# The passed in `abbreviation` instance will be frozen.
|
||||
#
|
||||
# @param base_utc_offset [Integer] the base offset from UTC in seconds.
|
||||
# @param std_offset [Integer] the offset from standard time in seconds.
|
||||
# @param abbreviation [String] the abbreviation identifying the offset.
|
||||
def initialize(base_utc_offset, std_offset, abbreviation)
|
||||
@base_utc_offset = base_utc_offset
|
||||
@std_offset = std_offset
|
||||
@abbreviation = abbreviation.freeze
|
||||
|
||||
@observed_utc_offset = @base_utc_offset + @std_offset
|
||||
end
|
||||
|
||||
# Determines if daylight savings is in effect (i.e. if {std_offset} is
|
||||
# non-zero).
|
||||
#
|
||||
# @return [Boolean] `true` if {std_offset} is non-zero, otherwise `false`.
|
||||
def dst?
|
||||
@std_offset != 0
|
||||
end
|
||||
|
||||
# Determines if this {TimezoneOffset} is equal to another instance.
|
||||
#
|
||||
# @param toi [Object] the instance to test for equality.
|
||||
# @return [Boolean] `true` if `toi` is a {TimezoneOffset} with the same
|
||||
# {utc_offset}, {std_offset} and {abbreviation} as this {TimezoneOffset},
|
||||
# otherwise `false`.
|
||||
def ==(toi)
|
||||
toi.kind_of?(TimezoneOffset) &&
|
||||
base_utc_offset == toi.base_utc_offset && std_offset == toi.std_offset && abbreviation == toi.abbreviation
|
||||
end
|
||||
|
||||
# Determines if this {TimezoneOffset} is equal to another instance.
|
||||
#
|
||||
# @param toi [Object] the instance to test for equality.
|
||||
# @return [Boolean] `true` if `toi` is a {TimezoneOffset} with the same
|
||||
# {utc_offset}, {std_offset} and {abbreviation} as this {TimezoneOffset},
|
||||
# otherwise `false`.
|
||||
def eql?(toi)
|
||||
self == toi
|
||||
end
|
||||
|
||||
# @return [Integer] a hash based on {utc_offset}, {std_offset} and
|
||||
# {abbreviation}.
|
||||
def hash
|
||||
[@base_utc_offset, @std_offset, @abbreviation].hash
|
||||
end
|
||||
|
||||
# @return [String] the internal object state as a programmer-readable
|
||||
# `String`.
|
||||
def inspect
|
||||
"#<#{self.class}: @base_utc_offset=#{@base_utc_offset}, @std_offset=#{@std_offset}, @abbreviation=#{@abbreviation}>"
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,179 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
# {TimezonePeriod} represents a period of time for a time zone where the same
|
||||
# offset from UTC applies. It provides access to the observed offset, time
|
||||
# zone abbreviation, start time and end time.
|
||||
#
|
||||
# The period of time can be unbounded at the start, end, or both the start
|
||||
# and end.
|
||||
#
|
||||
# @abstract Time zone period data will returned as an instance of one of the
|
||||
# subclasses of {TimezonePeriod}.
|
||||
class TimezonePeriod
|
||||
# @return [TimezoneOffset] the offset that applies in the period of time.
|
||||
attr_reader :offset
|
||||
|
||||
# Initializes a {TimezonePeriod}.
|
||||
#
|
||||
# @param offset [TimezoneOffset] the offset that is observed for the period
|
||||
# of time.
|
||||
# @raise [ArgumentError] if `offset` is `nil`.
|
||||
def initialize(offset)
|
||||
raise ArgumentError, 'offset must be specified' unless offset
|
||||
@offset = offset
|
||||
end
|
||||
|
||||
# @return [TimezoneTransition] the transition that defines the start of this
|
||||
# {TimezonePeriod} (`nil` if the start is unbounded).
|
||||
def start_transition
|
||||
raise_not_implemented(:start_transition)
|
||||
end
|
||||
|
||||
# @return [TimezoneTransition] the transition that defines the end of this
|
||||
# {TimezonePeriod} (`nil` if the end is unbounded).
|
||||
def end_transition
|
||||
raise_not_implemented(:end_transition)
|
||||
end
|
||||
|
||||
# Returns the base offset from UTC in seconds (`observed_utc_offset -
|
||||
# std_offset`). This does not include any adjustment made for daylight
|
||||
# savings time and will typically remain constant throughout the year.
|
||||
#
|
||||
# To obtain the currently observed offset from UTC, including the effect of
|
||||
# daylight savings time, use {observed_utc_offset} instead.
|
||||
#
|
||||
# If you require accurate {base_utc_offset} values, you should install the
|
||||
# tzinfo-data gem and set {DataSources::RubyDataSource} as the {DataSource}.
|
||||
# When using {DataSources::ZoneinfoDataSource}, the value of
|
||||
# {base_utc_offset} has to be derived from changes to the observed UTC
|
||||
# offset and DST status since it is not included in zoneinfo files.
|
||||
#
|
||||
# @return [Integer] the base offset from UTC in seconds.
|
||||
def base_utc_offset
|
||||
@offset.base_utc_offset
|
||||
end
|
||||
alias utc_offset base_utc_offset
|
||||
|
||||
# Returns the offset from the time zone's standard time in seconds
|
||||
# (`observed_utc_offset - base_utc_offset`). Zero when daylight savings time
|
||||
# is not in effect. Non-zero (usually 3600 = 1 hour) if daylight savings is
|
||||
# being observed.
|
||||
#
|
||||
# If you require accurate {std_offset} values, you should install the
|
||||
# tzinfo-data gem and set {DataSources::RubyDataSource} as the {DataSource}.
|
||||
# When using {DataSources::ZoneinfoDataSource}, the value of {std_offset}
|
||||
# has to be derived from changes to the observed UTC offset and DST status
|
||||
# since it is not included in zoneinfo files.
|
||||
#
|
||||
# @return [Integer] the offset from the time zone's standard time in
|
||||
# seconds.
|
||||
def std_offset
|
||||
@offset.std_offset
|
||||
end
|
||||
|
||||
# The abbreviation that identifies this offset. For example GMT
|
||||
# (Greenwich Mean Time) or BST (British Summer Time) for Europe/London.
|
||||
#
|
||||
# @return [String] the abbreviation that identifies this offset.
|
||||
def abbreviation
|
||||
@offset.abbreviation
|
||||
end
|
||||
alias abbr abbreviation
|
||||
alias zone_identifier abbreviation
|
||||
|
||||
# Returns the observed offset from UTC in seconds (`base_utc_offset +
|
||||
# std_offset`). This includes adjustments made for daylight savings time.
|
||||
#
|
||||
# @return [Integer] the observed offset from UTC in seconds.
|
||||
def observed_utc_offset
|
||||
@offset.observed_utc_offset
|
||||
end
|
||||
alias utc_total_offset observed_utc_offset
|
||||
|
||||
# Determines if daylight savings is in effect (i.e. if {std_offset} is
|
||||
# non-zero).
|
||||
#
|
||||
# @return [Boolean] `true` if {std_offset} is non-zero, otherwise `false`.
|
||||
def dst?
|
||||
@offset.dst?
|
||||
end
|
||||
|
||||
# Returns the UTC start time of the period or `nil` if the start of the
|
||||
# period is unbounded.
|
||||
#
|
||||
# The result is returned as a {Timestamp}. To obtain the start time as a
|
||||
# `Time` or `DateTime`, call either {Timestamp#to_time to_time} or
|
||||
# {Timestamp#to_datetime to_datetime} on the result.
|
||||
#
|
||||
# @return [Timestamp] the UTC start time of the period or `nil` if the start
|
||||
# of the period is unbounded.
|
||||
def starts_at
|
||||
timestamp(start_transition)
|
||||
end
|
||||
|
||||
# Returns the UTC end time of the period or `nil` if the end of the period
|
||||
# is unbounded.
|
||||
#
|
||||
# The result is returned as a {Timestamp}. To obtain the end time as a
|
||||
# `Time` or `DateTime`, call either {Timestamp#to_time to_time} or
|
||||
# {Timestamp#to_datetime to_datetime} on the result.
|
||||
#
|
||||
# @return [Timestamp] the UTC end time of the period or `nil` if the end of
|
||||
# the period is unbounded.
|
||||
def ends_at
|
||||
timestamp(end_transition)
|
||||
end
|
||||
|
||||
# Returns the local start time of the period or `nil` if the start of the
|
||||
# period is unbounded.
|
||||
#
|
||||
# The result is returned as a {TimestampWithOffset}. To obtain the start
|
||||
# time as a `Time` or `DateTime`, call either {TimestampWithOffset#to_time
|
||||
# to_time} or {TimestampWithOffset#to_datetime to_datetime} on the result.
|
||||
#
|
||||
# @return [TimestampWithOffset] the local start time of the period or `nil`
|
||||
# if the start of the period is unbounded.
|
||||
def local_starts_at
|
||||
timestamp_with_offset(start_transition)
|
||||
end
|
||||
|
||||
# Returns the local end time of the period or `nil` if the end of the period
|
||||
# is unbounded.
|
||||
#
|
||||
# The result is returned as a {TimestampWithOffset}. To obtain the end time
|
||||
# as a `Time` or `DateTime`, call either {TimestampWithOffset#to_time
|
||||
# to_time} or {TimestampWithOffset#to_datetime to_datetime} on the result.
|
||||
#
|
||||
# @return [TimestampWithOffset] the local end time of the period or `nil` if
|
||||
# the end of the period is unbounded.
|
||||
def local_ends_at
|
||||
timestamp_with_offset(end_transition)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Raises a {NotImplementedError} to indicate that subclasses should override
|
||||
# a method.
|
||||
#
|
||||
# @raise [NotImplementedError] always.
|
||||
def raise_not_implemented(method_name)
|
||||
raise NotImplementedError, "Subclasses must override #{method_name}"
|
||||
end
|
||||
|
||||
# @param transition [TimezoneTransition] a transition or `nil`.
|
||||
# @return [Timestamp] the {Timestamp} representing when a transition occurs,
|
||||
# or `nil` if `transition` is `nil`.
|
||||
def timestamp(transition)
|
||||
transition ? transition.at : nil
|
||||
end
|
||||
|
||||
# @param transition [TimezoneTransition] a transition or `nil`.
|
||||
# @return [TimestampWithOffset] a {Timestamp} representing when a transition
|
||||
# occurs with offset set to {#offset}, or `nil` if `transition` is `nil`.
|
||||
def timestamp_with_offset(transition)
|
||||
transition ? TimestampWithOffset.set_timezone_offset(transition.at, offset) : nil
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,96 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
|
||||
module TZInfo
|
||||
|
||||
# A proxy class standing in for a {Timezone} with a given identifier.
|
||||
# {TimezoneProxy} inherits from {Timezone} and can be treated identically to
|
||||
# {Timezone} instances loaded with {Timezone.get}.
|
||||
#
|
||||
# {TimezoneProxy} instances are used to avoid the performance overhead of
|
||||
# loading time zone data into memory, for example, by {Timezone.all}.
|
||||
#
|
||||
# The first time an attempt is made to access the data for the time zone, the
|
||||
# real {Timezone} will be loaded is loaded. If the proxy's identifier was not
|
||||
# valid, then an exception will be raised at this point.
|
||||
class TimezoneProxy < Timezone
|
||||
# Initializes a new {TimezoneProxy}.
|
||||
#
|
||||
# The `identifier` parameter is not checked when initializing the proxy. It
|
||||
# will be validated when the real {Timezone} instance is loaded.
|
||||
#
|
||||
# @param identifier [String] an IANA Time Zone Database time zone
|
||||
# identifier.
|
||||
def initialize(identifier)
|
||||
super()
|
||||
@identifier = identifier
|
||||
@real_timezone = nil
|
||||
end
|
||||
|
||||
# (see Timezone#identifier)
|
||||
def identifier
|
||||
@real_timezone ? @real_timezone.identifier : @identifier
|
||||
end
|
||||
|
||||
# (see Timezone#period_for)
|
||||
def period_for(time)
|
||||
real_timezone.period_for_utc(time)
|
||||
end
|
||||
|
||||
# (see Timezone#periods_for_local)
|
||||
def periods_for_local(local_time)
|
||||
real_timezone.periods_for_local(local_time)
|
||||
end
|
||||
|
||||
# (see Timezone#transitions_up_to)
|
||||
def transitions_up_to(to, from = nil)
|
||||
real_timezone.transitions_up_to(to, from)
|
||||
end
|
||||
|
||||
# (see Timezone#canonical_zone)
|
||||
def canonical_zone
|
||||
real_timezone.canonical_zone
|
||||
end
|
||||
|
||||
# Returns a serialized representation of this {TimezoneProxy}. This method
|
||||
# is called when using `Marshal.dump` with an instance of {TimezoneProxy}.
|
||||
#
|
||||
# @param limit [Integer] the maximum depth to dump - ignored. @return
|
||||
# [String] a serialized representation of this {TimezoneProxy}.
|
||||
# @return [String] a serialized representation of this {TimezoneProxy}.
|
||||
def _dump(limit)
|
||||
identifier
|
||||
end
|
||||
|
||||
# Loads a {TimezoneProxy} from the serialized representation returned by
|
||||
# {_dump}. This is method is called when using `Marshal.load` or
|
||||
# `Marshal.restore` to restore a serialized {Timezone}.
|
||||
#
|
||||
# @param data [String] a serialized representation of a {TimezoneProxy}.
|
||||
# @return [TimezoneProxy] the result of converting `data` back into a
|
||||
# {TimezoneProxy}.
|
||||
def self._load(data)
|
||||
TimezoneProxy.new(data)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Returns the real {Timezone} instance being proxied.
|
||||
#
|
||||
# The real {Timezone} is loaded using {Timezone.get} on the first access.
|
||||
#
|
||||
# @return [Timezone] the real {Timezone} instance being proxied.
|
||||
def real_timezone
|
||||
# Thread-safety: It is possible that the value of @real_timezone may be
|
||||
# calculated multiple times in concurrently executing threads. It is not
|
||||
# worth the overhead of locking to ensure that @real_timezone is only
|
||||
# calculated once.
|
||||
unless @real_timezone
|
||||
result = Timezone.get(@identifier)
|
||||
return result if frozen?
|
||||
@real_timezone = result
|
||||
end
|
||||
|
||||
@real_timezone
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,98 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
# Represents a transition from one observed UTC offset ({TimezoneOffset} to
|
||||
# another for a time zone.
|
||||
class TimezoneTransition
|
||||
# @return [TimezoneOffset] the offset this transition changes to.
|
||||
attr_reader :offset
|
||||
|
||||
# @return [TimezoneOffset] the offset this transition changes from.
|
||||
attr_reader :previous_offset
|
||||
|
||||
# When this transition occurs as an `Integer` number of seconds since
|
||||
# 1970-01-01 00:00:00 UTC ignoring leap seconds (i.e. each day is treated as
|
||||
# if it were 86,400 seconds long). Equivalent to the result of calling the
|
||||
# {Timestamp#value value} method on the {Timestamp} returned by {at}.
|
||||
#
|
||||
# @return [Integer] when this transition occurs as a number of seconds since
|
||||
# 1970-01-01 00:00:00 UTC ignoring leap seconds.
|
||||
attr_reader :timestamp_value
|
||||
|
||||
# Initializes a new {TimezoneTransition}.
|
||||
#
|
||||
# {TimezoneTransition} instances should not normally be constructed
|
||||
# manually.
|
||||
#
|
||||
# @param offset [TimezoneOffset] the offset the transition changes to.
|
||||
# @param previous_offset [TimezoneOffset] the offset the transition changes
|
||||
# from.
|
||||
# @param timestamp_value [Integer] when the transition occurs as a
|
||||
# number of seconds since 1970-01-01 00:00:00 UTC ignoring leap seconds
|
||||
# (i.e. each day is treated as if it were 86,400 seconds long).
|
||||
def initialize(offset, previous_offset, timestamp_value)
|
||||
@offset = offset
|
||||
@previous_offset = previous_offset
|
||||
@timestamp_value = timestamp_value
|
||||
end
|
||||
|
||||
# Returns a {Timestamp} instance representing the UTC time when this
|
||||
# transition occurs.
|
||||
#
|
||||
# To obtain the result as a `Time` or `DateTime`, call either
|
||||
# {Timestamp#to_time to_time} or {Timestamp#to_datetime to_datetime} on the
|
||||
# {Timestamp} instance that is returned.
|
||||
#
|
||||
# @return [Timestamp] the UTC time when this transition occurs.
|
||||
def at
|
||||
Timestamp.utc(@timestamp_value)
|
||||
end
|
||||
|
||||
# Returns a {TimestampWithOffset} instance representing the local time when
|
||||
# this transition causes the previous observance to end (calculated from
|
||||
# {at} using {previous_offset}).
|
||||
#
|
||||
# To obtain the result as a `Time` or `DateTime`, call either
|
||||
# {TimestampWithOffset#to_time to_time} or {TimestampWithOffset#to_datetime
|
||||
# to_datetime} on the {TimestampWithOffset} instance that is returned.
|
||||
#
|
||||
# @return [TimestampWithOffset] the local time when this transition causes
|
||||
# the previous observance to end.
|
||||
def local_end_at
|
||||
TimestampWithOffset.new(@timestamp_value, 0, @previous_offset.observed_utc_offset).set_timezone_offset(@previous_offset)
|
||||
end
|
||||
|
||||
# Returns a {TimestampWithOffset} instance representing the local time when
|
||||
# this transition causes the next observance to start (calculated from {at}
|
||||
# using {offset}).
|
||||
#
|
||||
# To obtain the result as a `Time` or `DateTime`, call either
|
||||
# {TimestampWithOffset#to_time to_time} or {TimestampWithOffset#to_datetime
|
||||
# to_datetime} on the {TimestampWithOffset} instance that is returned.
|
||||
#
|
||||
# @return [TimestampWithOffset] the local time when this transition causes
|
||||
# the next observance to start.
|
||||
def local_start_at
|
||||
TimestampWithOffset.new(@timestamp_value, 0, @offset.observed_utc_offset).set_timezone_offset(@offset)
|
||||
end
|
||||
|
||||
# Determines if this {TimezoneTransition} is equal to another instance.
|
||||
#
|
||||
# @param tti [Object] the instance to test for equality.
|
||||
# @return [Boolean] `true` if `tti` is a {TimezoneTransition} with the same
|
||||
# {offset}, {previous_offset} and {timestamp_value} as this
|
||||
# {TimezoneTransition}, otherwise `false`.
|
||||
def ==(tti)
|
||||
tti.kind_of?(TimezoneTransition) &&
|
||||
offset == tti.offset && previous_offset == tti.previous_offset && timestamp_value == tti.timestamp_value
|
||||
end
|
||||
alias eql? ==
|
||||
|
||||
# @return [Integer] a hash based on {offset}, {previous_offset} and
|
||||
# {timestamp_value}.
|
||||
def hash
|
||||
[@offset, @previous_offset, @timestamp_value].hash
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,455 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
# Base class for rules definining the transition between standard and daylight
|
||||
# savings time.
|
||||
#
|
||||
# @abstract
|
||||
# @private
|
||||
class TransitionRule #:nodoc:
|
||||
# Returns the number of seconds after midnight local time on the day
|
||||
# identified by the rule at which the transition occurs. Can be negative to
|
||||
# denote a time on the prior day. Can be greater than or equal to 86,400 to
|
||||
# denote a time of the following day.
|
||||
#
|
||||
# @return [Integer] the time in seconds after midnight local time at which
|
||||
# the transition occurs.
|
||||
attr_reader :transition_at
|
||||
|
||||
# Initializes a new {TransitionRule}.
|
||||
#
|
||||
# @param transition_at [Integer] the time in seconds after midnight local
|
||||
# time at which the transition occurs.
|
||||
# @raise [ArgumentError] if `transition_at` is not an `Integer`.
|
||||
def initialize(transition_at)
|
||||
raise ArgumentError, 'Invalid transition_at' unless transition_at.kind_of?(Integer)
|
||||
@transition_at = transition_at
|
||||
end
|
||||
|
||||
# Calculates the time of the transition from a given offset on a given year.
|
||||
#
|
||||
# @param offset [TimezoneOffset] the current offset at the time the rule
|
||||
# will transition.
|
||||
# @param year [Integer] the year in which the transition occurs (local
|
||||
# time).
|
||||
# @return [TimestampWithOffset] the time at which the transition occurs.
|
||||
def at(offset, year)
|
||||
day = get_day(offset, year)
|
||||
TimestampWithOffset.set_timezone_offset(Timestamp.for(day + @transition_at), offset)
|
||||
end
|
||||
|
||||
# Determines if this {TransitionRule} is equal to another instance.
|
||||
#
|
||||
# @param r [Object] the instance to test for equality.
|
||||
# @return [Boolean] `true` if `r` is a {TransitionRule} with the same
|
||||
# {transition_at} as this {TransitionRule}, otherwise `false`.
|
||||
def ==(r)
|
||||
r.kind_of?(TransitionRule) && @transition_at == r.transition_at
|
||||
end
|
||||
alias eql? ==
|
||||
|
||||
# @return [Integer] a hash based on {hash_args} (defaulting to
|
||||
# {transition_at}).
|
||||
def hash
|
||||
hash_args.hash
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
# @return [Array] an `Array` of parameters that will influence the output of
|
||||
# {hash}.
|
||||
def hash_args
|
||||
[@transition_at]
|
||||
end
|
||||
end
|
||||
private_constant :TransitionRule
|
||||
|
||||
# A base class for transition rules that activate based on an integer day of
|
||||
# the year.
|
||||
#
|
||||
# @abstract
|
||||
# @private
|
||||
class DayOfYearTransitionRule < TransitionRule #:nodoc:
|
||||
# Initializes a new {DayOfYearTransitionRule}.
|
||||
#
|
||||
# @param day [Integer] the day of the year on which the transition occurs.
|
||||
# The precise meaning is defined by subclasses.
|
||||
# @param transition_at [Integer] the time in seconds after midnight local
|
||||
# time at which the transition occurs.
|
||||
# @raise [ArgumentError] if `transition_at` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `day` is not an `Integer`.
|
||||
def initialize(day, transition_at)
|
||||
super(transition_at)
|
||||
raise ArgumentError, 'Invalid day' unless day.kind_of?(Integer)
|
||||
@seconds = day * 86400
|
||||
end
|
||||
|
||||
# Determines if this {DayOfYearTransitionRule} is equal to another instance.
|
||||
#
|
||||
# @param r [Object] the instance to test for equality.
|
||||
# @return [Boolean] `true` if `r` is a {DayOfYearTransitionRule} with the
|
||||
# same {transition_at} and day as this {DayOfYearTransitionRule},
|
||||
# otherwise `false`.
|
||||
def ==(r)
|
||||
super(r) && r.kind_of?(DayOfYearTransitionRule) && @seconds == r.seconds
|
||||
end
|
||||
alias eql? ==
|
||||
|
||||
protected
|
||||
|
||||
# @return [Integer] the day multipled by the number of seconds in a day.
|
||||
attr_reader :seconds
|
||||
|
||||
# (see TransitionRule#hash_args)
|
||||
def hash_args
|
||||
[@seconds] + super
|
||||
end
|
||||
end
|
||||
private_constant :DayOfYearTransitionRule
|
||||
|
||||
# Defines transitions that occur on the zero-based nth day of the year.
|
||||
#
|
||||
# Day 0 is 1 January.
|
||||
#
|
||||
# Leap days are counted. Day 59 will be 29 February on a leap year and 1 March
|
||||
# on a non-leap year. Day 365 will be 31 December on a leap year and 1 January
|
||||
# the following year on a non-leap year.
|
||||
#
|
||||
# @private
|
||||
class AbsoluteDayOfYearTransitionRule < DayOfYearTransitionRule #:nodoc:
|
||||
# Initializes a new {AbsoluteDayOfYearTransitionRule}.
|
||||
#
|
||||
# @param day [Integer] the zero-based day of the year on which the
|
||||
# transition occurs (0 to 365 inclusive).
|
||||
# @param transition_at [Integer] the time in seconds after midnight local
|
||||
# time at which the transition occurs.
|
||||
# @raise [ArgumentError] if `transition_at` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `day` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `day` is less than 0 or greater than 365.
|
||||
def initialize(day, transition_at = 0)
|
||||
super(day, transition_at)
|
||||
raise ArgumentError, 'Invalid day' unless day >= 0 && day <= 365
|
||||
end
|
||||
|
||||
# @return [Boolean] `true` if the day specified by this transition is the
|
||||
# first in the year (a day number of 0), otherwise `false`.
|
||||
def is_always_first_day_of_year?
|
||||
seconds == 0
|
||||
end
|
||||
|
||||
# @return [Boolean] `false`.
|
||||
def is_always_last_day_of_year?
|
||||
false
|
||||
end
|
||||
|
||||
# Determines if this {AbsoluteDayOfYearTransitionRule} is equal to another
|
||||
# instance.
|
||||
#
|
||||
# @param r [Object] the instance to test for equality.
|
||||
# @return [Boolean] `true` if `r` is a {AbsoluteDayOfYearTransitionRule}
|
||||
# with the same {transition_at} and day as this
|
||||
# {AbsoluteDayOfYearTransitionRule}, otherwise `false`.
|
||||
def ==(r)
|
||||
super(r) && r.kind_of?(AbsoluteDayOfYearTransitionRule)
|
||||
end
|
||||
alias eql? ==
|
||||
|
||||
protected
|
||||
|
||||
# Returns a `Time` representing midnight local time on the day specified by
|
||||
# the rule for the given offset and year.
|
||||
#
|
||||
# @param offset [TimezoneOffset] the current offset at the time of the
|
||||
# transition.
|
||||
# @param year [Integer] the year in which the transition occurs.
|
||||
# @return [Time] midnight local time on the day specified by the rule for
|
||||
# the given offset and year.
|
||||
def get_day(offset, year)
|
||||
Time.new(year, 1, 1, 0, 0, 0, offset.observed_utc_offset) + seconds
|
||||
end
|
||||
|
||||
# (see TransitionRule#hash_args)
|
||||
def hash_args
|
||||
[AbsoluteDayOfYearTransitionRule] + super
|
||||
end
|
||||
end
|
||||
|
||||
# Defines transitions that occur on the one-based nth Julian day of the year.
|
||||
#
|
||||
# Leap days are not counted. Day 1 is 1 January. Day 60 is always 1 March.
|
||||
# Day 365 is always 31 December.
|
||||
#
|
||||
# @private
|
||||
class JulianDayOfYearTransitionRule < DayOfYearTransitionRule #:nodoc:
|
||||
# The 60 days in seconds.
|
||||
LEAP = 60 * 86400
|
||||
private_constant :LEAP
|
||||
|
||||
# The length of a non-leap year in seconds.
|
||||
YEAR = 365 * 86400
|
||||
private_constant :YEAR
|
||||
|
||||
# Initializes a new {JulianDayOfYearTransitionRule}.
|
||||
#
|
||||
# @param day [Integer] the one-based Julian day of the year on which the
|
||||
# transition occurs (1 to 365 inclusive).
|
||||
# @param transition_at [Integer] the time in seconds after midnight local
|
||||
# time at which the transition occurs.
|
||||
# @raise [ArgumentError] if `transition_at` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `day` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `day` is less than 1 or greater than 365.
|
||||
def initialize(day, transition_at = 0)
|
||||
super(day, transition_at)
|
||||
raise ArgumentError, 'Invalid day' unless day >= 1 && day <= 365
|
||||
end
|
||||
|
||||
# @return [Boolean] `true` if the day specified by this transition is the
|
||||
# first in the year (a day number of 1), otherwise `false`.
|
||||
def is_always_first_day_of_year?
|
||||
seconds == 86400
|
||||
end
|
||||
|
||||
# @return [Boolean] `true` if the day specified by this transition is the
|
||||
# last in the year (a day number of 365), otherwise `false`.
|
||||
def is_always_last_day_of_year?
|
||||
seconds == YEAR
|
||||
end
|
||||
|
||||
# Determines if this {JulianDayOfYearTransitionRule} is equal to another
|
||||
# instance.
|
||||
#
|
||||
# @param r [Object] the instance to test for equality.
|
||||
# @return [Boolean] `true` if `r` is a {JulianDayOfYearTransitionRule} with
|
||||
# the same {transition_at} and day as this
|
||||
# {JulianDayOfYearTransitionRule}, otherwise `false`.
|
||||
def ==(r)
|
||||
super(r) && r.kind_of?(JulianDayOfYearTransitionRule)
|
||||
end
|
||||
alias eql? ==
|
||||
|
||||
protected
|
||||
|
||||
# Returns a `Time` representing midnight local time on the day specified by
|
||||
# the rule for the given offset and year.
|
||||
#
|
||||
# @param offset [TimezoneOffset] the current offset at the time of the
|
||||
# transition.
|
||||
# @param year [Integer] the year in which the transition occurs.
|
||||
# @return [Time] midnight local time on the day specified by the rule for
|
||||
# the given offset and year.
|
||||
def get_day(offset, year)
|
||||
# Returns 1 March on non-leap years.
|
||||
leap = Time.new(year, 2, 29, 0, 0, 0, offset.observed_utc_offset)
|
||||
diff = seconds - LEAP
|
||||
diff += 86400 if diff >= 0 && leap.mday == 29
|
||||
leap + diff
|
||||
end
|
||||
|
||||
# (see TransitionRule#hash_args)
|
||||
def hash_args
|
||||
[JulianDayOfYearTransitionRule] + super
|
||||
end
|
||||
end
|
||||
private_constant :JulianDayOfYearTransitionRule
|
||||
|
||||
# A base class for rules that transition on a particular day of week of a
|
||||
# given week (subclasses specify which week of the month).
|
||||
#
|
||||
# @abstract
|
||||
# @private
|
||||
class DayOfWeekTransitionRule < TransitionRule #:nodoc:
|
||||
# Initializes a new {DayOfWeekTransitionRule}.
|
||||
#
|
||||
# @param month [Integer] the month of the year when the transition occurs.
|
||||
# @param day_of_week [Integer] the day of the week when the transition
|
||||
# occurs. 0 is Sunday, 6 is Saturday.
|
||||
# @param transition_at [Integer] the time in seconds after midnight local
|
||||
# time at which the transition occurs.
|
||||
# @raise [ArgumentError] if `transition_at` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `month` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `month` is less than 1 or greater than 12.
|
||||
# @raise [ArgumentError] if `day_of_week` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `day_of_week` is less than 0 or greater than 6.
|
||||
def initialize(month, day_of_week, transition_at)
|
||||
super(transition_at)
|
||||
raise ArgumentError, 'Invalid month' unless month.kind_of?(Integer) && month >= 1 && month <= 12
|
||||
raise ArgumentError, 'Invalid day_of_week' unless day_of_week.kind_of?(Integer) && day_of_week >= 0 && day_of_week <= 6
|
||||
@month = month
|
||||
@day_of_week = day_of_week
|
||||
end
|
||||
|
||||
# @return [Boolean] `false`.
|
||||
def is_always_first_day_of_year?
|
||||
false
|
||||
end
|
||||
|
||||
# @return [Boolean] `false`.
|
||||
def is_always_last_day_of_year?
|
||||
false
|
||||
end
|
||||
|
||||
# Determines if this {DayOfWeekTransitionRule} is equal to another
|
||||
# instance.
|
||||
#
|
||||
# @param r [Object] the instance to test for equality.
|
||||
# @return [Boolean] `true` if `r` is a {DayOfWeekTransitionRule} with the
|
||||
# same {transition_at}, month and day of week as this
|
||||
# {DayOfWeekTransitionRule}, otherwise `false`.
|
||||
def ==(r)
|
||||
super(r) && r.kind_of?(DayOfWeekTransitionRule) && @month == r.month && @day_of_week == r.day_of_week
|
||||
end
|
||||
alias eql? ==
|
||||
|
||||
protected
|
||||
|
||||
# @return [Integer] the month of the year (1 to 12).
|
||||
attr_reader :month
|
||||
|
||||
# @return [Integer] the day of the week (0 to 6 for Sunday to Monday).
|
||||
attr_reader :day_of_week
|
||||
|
||||
# (see TransitionRule#hash_args)
|
||||
def hash_args
|
||||
[@month, @day_of_week] + super
|
||||
end
|
||||
end
|
||||
private_constant :DayOfWeekTransitionRule
|
||||
|
||||
# A rule that transitions on the nth occurrence of a particular day of week
|
||||
# of a calendar month.
|
||||
#
|
||||
# @private
|
||||
class DayOfMonthTransitionRule < DayOfWeekTransitionRule #:nodoc:
|
||||
# Initializes a new {DayOfMonthTransitionRule}.
|
||||
#
|
||||
# @param month [Integer] the month of the year when the transition occurs.
|
||||
# @param week [Integer] the week of the month when the transition occurs (1
|
||||
# to 4).
|
||||
# @param day_of_week [Integer] the day of the week when the transition
|
||||
# occurs. 0 is Sunday, 6 is Saturday.
|
||||
# @param transition_at [Integer] the time in seconds after midnight local
|
||||
# time at which the transition occurs.
|
||||
# @raise [ArgumentError] if `transition_at` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `month` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `month` is less than 1 or greater than 12.
|
||||
# @raise [ArgumentError] if `week` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `week` is less than 1 or greater than 4.
|
||||
# @raise [ArgumentError] if `day_of_week` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `day_of_week` is less than 0 or greater than 6.
|
||||
def initialize(month, week, day_of_week, transition_at = 0)
|
||||
super(month, day_of_week, transition_at)
|
||||
raise ArgumentError, 'Invalid week' unless week.kind_of?(Integer) && week >= 1 && week <= 4
|
||||
@offset_start = (week - 1) * 7 + 1
|
||||
end
|
||||
|
||||
# Determines if this {DayOfMonthTransitionRule} is equal to another
|
||||
# instance.
|
||||
#
|
||||
# @param r [Object] the instance to test for equality.
|
||||
# @return [Boolean] `true` if `r` is a {DayOfMonthTransitionRule} with the
|
||||
# same {transition_at}, month, week and day of week as this
|
||||
# {DayOfMonthTransitionRule}, otherwise `false`.
|
||||
def ==(r)
|
||||
super(r) && r.kind_of?(DayOfMonthTransitionRule) && @offset_start == r.offset_start
|
||||
end
|
||||
alias eql? ==
|
||||
|
||||
protected
|
||||
|
||||
# @return [Integer] the day the week starts on for a month starting on a
|
||||
# Sunday.
|
||||
attr_reader :offset_start
|
||||
|
||||
# Returns a `Time` representing midnight local time on the day specified by
|
||||
# the rule for the given offset and year.
|
||||
#
|
||||
# @param offset [TimezoneOffset] the current offset at the time of the
|
||||
# transition.
|
||||
# @param year [Integer] the year in which the transition occurs.
|
||||
# @return [Time] midnight local time on the day specified by the rule for
|
||||
# the given offset and year.
|
||||
def get_day(offset, year)
|
||||
candidate = Time.new(year, month, @offset_start, 0, 0, 0, offset.observed_utc_offset)
|
||||
diff = day_of_week - candidate.wday
|
||||
|
||||
if diff < 0
|
||||
candidate + (7 + diff) * 86400
|
||||
elsif diff > 0
|
||||
candidate + diff * 86400
|
||||
else
|
||||
candidate
|
||||
end
|
||||
end
|
||||
|
||||
# (see TransitionRule#hash_args)
|
||||
def hash_args
|
||||
[@offset_start] + super
|
||||
end
|
||||
end
|
||||
private_constant :DayOfMonthTransitionRule
|
||||
|
||||
# A rule that transitions on the last occurrence of a particular day of week
|
||||
# of a calendar month.
|
||||
#
|
||||
# @private
|
||||
class LastDayOfMonthTransitionRule < DayOfWeekTransitionRule #:nodoc:
|
||||
# Initializes a new {LastDayOfMonthTransitionRule}.
|
||||
#
|
||||
# @param month [Integer] the month of the year when the transition occurs.
|
||||
# @param day_of_week [Integer] the day of the week when the transition
|
||||
# occurs. 0 is Sunday, 6 is Saturday.
|
||||
# @param transition_at [Integer] the time in seconds after midnight local
|
||||
# time at which the transition occurs.
|
||||
# @raise [ArgumentError] if `transition_at` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `month` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `month` is less than 1 or greater than 12.
|
||||
# @raise [ArgumentError] if `day_of_week` is not an `Integer`.
|
||||
# @raise [ArgumentError] if `day_of_week` is less than 0 or greater than 6.
|
||||
def initialize(month, day_of_week, transition_at = 0)
|
||||
super(month, day_of_week, transition_at)
|
||||
end
|
||||
|
||||
# Determines if this {LastDayOfMonthTransitionRule} is equal to another
|
||||
# instance.
|
||||
#
|
||||
# @param r [Object] the instance to test for equality.
|
||||
# @return [Boolean] `true` if `r` is a {LastDayOfMonthTransitionRule} with
|
||||
# the same {transition_at}, month and day of week as this
|
||||
# {LastDayOfMonthTransitionRule}, otherwise `false`.
|
||||
def ==(r)
|
||||
super(r) && r.kind_of?(LastDayOfMonthTransitionRule)
|
||||
end
|
||||
alias eql? ==
|
||||
|
||||
protected
|
||||
|
||||
# Returns a `Time` representing midnight local time on the day specified by
|
||||
# the rule for the given offset and year.
|
||||
#
|
||||
# @param offset [TimezoneOffset] the current offset at the time of the
|
||||
# transition.
|
||||
# @param year [Integer] the year in which the transition occurs.
|
||||
# @return [Time] midnight local time on the day specified by the rule for
|
||||
# the given offset and year.
|
||||
def get_day(offset, year)
|
||||
next_month = month + 1
|
||||
if next_month == 13
|
||||
year += 1
|
||||
next_month = 1
|
||||
end
|
||||
|
||||
candidate = Time.new(year, next_month, 1, 0, 0, 0, offset.observed_utc_offset) - 86400
|
||||
diff = candidate.wday - day_of_week
|
||||
|
||||
if diff < 0
|
||||
candidate - (diff + 7) * 86400
|
||||
elsif diff > 0
|
||||
candidate - diff * 86400
|
||||
else
|
||||
candidate
|
||||
end
|
||||
end
|
||||
end
|
||||
private_constant :LastDayOfMonthTransitionRule
|
||||
end
|
||||
@ -1,63 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
# Represents a period of time in a time zone where the same offset from UTC
|
||||
# applies. The period of time is bounded at at least one end, either having a
|
||||
# start transition, end transition or both start and end transitions.
|
||||
class TransitionsTimezonePeriod < TimezonePeriod
|
||||
# @return [TimezoneTransition] the transition that defines the start of this
|
||||
# {TimezonePeriod} (`nil` if the start is unbounded).
|
||||
attr_reader :start_transition
|
||||
|
||||
# @return [TimezoneTransition] the transition that defines the end of this
|
||||
# {TimezonePeriod} (`nil` if the end is unbounded).
|
||||
attr_reader :end_transition
|
||||
|
||||
# Initializes a {TransitionsTimezonePeriod}.
|
||||
#
|
||||
# At least one of `start_transition` and `end_transition` must be specified.
|
||||
#
|
||||
# @param start_transition [TimezoneTransition] the transition that defines
|
||||
# the start of the period, or `nil` if the start is unbounded.
|
||||
# @param end_transition [TimezoneTransition] the transition that defines the
|
||||
# end of the period, or `nil` if the end is unbounded.
|
||||
# @raise [ArgumentError] if both `start_transition` and `end_transition` are
|
||||
# `nil`.
|
||||
def initialize(start_transition, end_transition)
|
||||
if start_transition
|
||||
super(start_transition.offset)
|
||||
elsif end_transition
|
||||
super(end_transition.previous_offset)
|
||||
else
|
||||
raise ArgumentError, 'At least one of start_transition and end_transition must be specified'
|
||||
end
|
||||
|
||||
@start_transition = start_transition
|
||||
@end_transition = end_transition
|
||||
end
|
||||
|
||||
# Determines if this {TransitionsTimezonePeriod} is equal to another
|
||||
# instance.
|
||||
#
|
||||
# @param p [Object] the instance to test for equality.
|
||||
# @return [Boolean] `true` if `p` is a {TransitionsTimezonePeriod} with the
|
||||
# same {offset}, {start_transition} and {end_transition}, otherwise
|
||||
# `false`.
|
||||
def ==(p)
|
||||
p.kind_of?(TransitionsTimezonePeriod) && start_transition == p.start_transition && end_transition == p.end_transition
|
||||
end
|
||||
alias eql? ==
|
||||
|
||||
# @return [Integer] a hash based on {start_transition} and {end_transition}.
|
||||
def hash
|
||||
[@start_transition, @end_transition].hash
|
||||
end
|
||||
|
||||
# @return [String] the internal object state as a programmer-readable
|
||||
# `String`.
|
||||
def inspect
|
||||
"#<#{self.class}: @start_transition=#{@start_transition.inspect}, @end_transition=#{@end_transition.inspect}>"
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,7 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
# The TZInfo version number.
|
||||
VERSION = '2.0.6'
|
||||
end
|
||||
@ -1,61 +0,0 @@
|
||||
# encoding: UTF-8
|
||||
# frozen_string_literal: true
|
||||
|
||||
module TZInfo
|
||||
# The {WithOffset} module is included in {TimeWithOffset},
|
||||
# {DateTimeWithOffset} and {TimestampWithOffset}. It provides an override for
|
||||
# the {strftime} method that handles expanding the `%Z` directive according to
|
||||
# the {TimezoneOffset#abbreviation abbreviation} of the {TimezoneOffset}
|
||||
# associated with a local time.
|
||||
module WithOffset
|
||||
# Overrides the `Time`, `DateTime` or {Timestamp} version of `strftime`,
|
||||
# replacing `%Z` with the {TimezoneOffset#abbreviation abbreviation} of the
|
||||
# associated {TimezoneOffset}. If there is no associated offset, `%Z` is
|
||||
# expanded by the base class instead.
|
||||
#
|
||||
# All the format directives handled by the base class are supported.
|
||||
#
|
||||
# @param format [String] the format string.
|
||||
# @return [String] the formatted time.
|
||||
# @raise [ArgumentError] if `format` is `nil`.
|
||||
def strftime(format)
|
||||
raise ArgumentError, 'format must be specified' unless format
|
||||
|
||||
if_timezone_offset do |o|
|
||||
abbreviation = nil
|
||||
|
||||
format = format.gsub(/%(%*)Z/) do
|
||||
if $1.length.odd?
|
||||
# Return %%Z so the real strftime treats it as a literal %Z too.
|
||||
"#$1%Z"
|
||||
else
|
||||
"#$1#{abbreviation ||= o.abbreviation.gsub(/%/, '%%')}"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
super
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
# Performs a calculation if there is an associated {TimezoneOffset}.
|
||||
#
|
||||
# @param result [Object] a result value that can be manipulated by the block
|
||||
# if there is an associated {TimezoneOffset}.
|
||||
# @yield [period, result] if there is an associated {TimezoneOffset}, the
|
||||
# block is yielded to in order to calculate the method result.
|
||||
# @yieldparam period [TimezoneOffset] the associated {TimezoneOffset}.
|
||||
# @yieldparam result [Object] the `result` parameter.
|
||||
# @yieldreturn [Object] the result of the calculation performed if there is
|
||||
# an associated {TimezoneOffset}.
|
||||
# @return [Object] the result of the block if there is an associated
|
||||
# {TimezoneOffset}, otherwise the `result` parameter.
|
||||
#
|
||||
# @private
|
||||
def if_timezone_offset(result = nil) #:nodoc:
|
||||
to = timezone_offset
|
||||
to ? yield(to, result) : result
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,26 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Zeitwerk
|
||||
require_relative "zeitwerk/real_mod_name"
|
||||
require_relative "zeitwerk/internal"
|
||||
require_relative "zeitwerk/loader"
|
||||
require_relative "zeitwerk/gem_loader"
|
||||
require_relative "zeitwerk/registry"
|
||||
require_relative "zeitwerk/explicit_namespace"
|
||||
require_relative "zeitwerk/inflector"
|
||||
require_relative "zeitwerk/gem_inflector"
|
||||
require_relative "zeitwerk/kernel"
|
||||
require_relative "zeitwerk/error"
|
||||
require_relative "zeitwerk/version"
|
||||
|
||||
# This is a dangerous method.
|
||||
#
|
||||
# @experimental
|
||||
# @sig () -> void
|
||||
def self.with_loader
|
||||
loader = Zeitwerk::Loader.new
|
||||
yield loader
|
||||
ensure
|
||||
loader.unregister
|
||||
end
|
||||
end
|
||||
@ -1,21 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Zeitwerk
|
||||
class Error < StandardError
|
||||
end
|
||||
|
||||
class ReloadingDisabledError < Error
|
||||
def initialize
|
||||
super("can't reload, please call loader.enable_reloading before setup")
|
||||
end
|
||||
end
|
||||
|
||||
class NameError < ::NameError
|
||||
end
|
||||
|
||||
class SetupRequired < Error
|
||||
def initialize
|
||||
super("please, finish your configuration and call Zeitwerk::Loader#setup once all is ready")
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,93 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Zeitwerk
|
||||
# Centralizes the logic for the trace point used to detect the creation of
|
||||
# explicit namespaces, needed to descend into matching subdirectories right
|
||||
# after the constant has been defined.
|
||||
#
|
||||
# The implementation assumes an explicit namespace is managed by one loader.
|
||||
# Loaders that reopen namespaces owned by other projects are responsible for
|
||||
# loading their constant before setup. This is documented.
|
||||
module ExplicitNamespace # :nodoc: all
|
||||
class << self
|
||||
include RealModName
|
||||
extend Internal
|
||||
|
||||
# Maps constant paths that correspond to explicit namespaces according to
|
||||
# the file system, to the loader responsible for them.
|
||||
#
|
||||
# @sig Hash[String, Zeitwerk::Loader]
|
||||
attr_reader :cpaths
|
||||
private :cpaths
|
||||
|
||||
# @sig Mutex
|
||||
attr_reader :mutex
|
||||
private :mutex
|
||||
|
||||
# @sig TracePoint
|
||||
attr_reader :tracer
|
||||
private :tracer
|
||||
|
||||
# Asserts `cpath` corresponds to an explicit namespace for which `loader`
|
||||
# is responsible.
|
||||
#
|
||||
# @sig (String, Zeitwerk::Loader) -> void
|
||||
internal def register(cpath, loader)
|
||||
mutex.synchronize do
|
||||
cpaths[cpath] = loader
|
||||
# We check enabled? because, looking at the C source code, enabling an
|
||||
# enabled tracer does not seem to be a simple no-op.
|
||||
tracer.enable unless tracer.enabled?
|
||||
end
|
||||
end
|
||||
|
||||
# @sig (Zeitwerk::Loader) -> void
|
||||
internal def unregister_loader(loader)
|
||||
cpaths.delete_if { |_cpath, l| l == loader }
|
||||
disable_tracer_if_unneeded
|
||||
end
|
||||
|
||||
# This is an internal method only used by the test suite.
|
||||
#
|
||||
# @sig (String) -> bool
|
||||
internal def registered?(cpath)
|
||||
cpaths.key?(cpath)
|
||||
end
|
||||
|
||||
# @sig () -> void
|
||||
private def disable_tracer_if_unneeded
|
||||
mutex.synchronize do
|
||||
tracer.disable if cpaths.empty?
|
||||
end
|
||||
end
|
||||
|
||||
# @sig (TracePoint) -> void
|
||||
private def tracepoint_class_callback(event)
|
||||
# If the class is a singleton class, we won't do anything with it so we
|
||||
# can bail out immediately. This is several orders of magnitude faster
|
||||
# than accessing its name.
|
||||
return if event.self.singleton_class?
|
||||
|
||||
# It might be tempting to return if name.nil?, to avoid the computation
|
||||
# of a hash code and delete call. But Ruby does not trigger the :class
|
||||
# event on Class.new or Module.new, so that would incur in an extra call
|
||||
# for nothing.
|
||||
#
|
||||
# On the other hand, if we were called, cpaths is not empty. Otherwise
|
||||
# the tracer is disabled. So we do need to go ahead with the hash code
|
||||
# computation and delete call.
|
||||
if loader = cpaths.delete(real_mod_name(event.self))
|
||||
loader.on_namespace_loaded(event.self)
|
||||
disable_tracer_if_unneeded
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@cpaths = {}
|
||||
@mutex = Mutex.new
|
||||
|
||||
# We go through a method instead of defining a block mainly to have a better
|
||||
# label when profiling.
|
||||
@tracer = TracePoint.new(:class, &method(:tracepoint_class_callback))
|
||||
end
|
||||
end
|
||||
@ -1,17 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Zeitwerk
|
||||
class GemInflector < Inflector
|
||||
# @sig (String) -> void
|
||||
def initialize(root_file)
|
||||
namespace = File.basename(root_file, ".rb")
|
||||
lib_dir = File.dirname(root_file)
|
||||
@version_file = File.join(lib_dir, namespace, "version.rb")
|
||||
end
|
||||
|
||||
# @sig (String, String) -> String
|
||||
def camelize(basename, abspath)
|
||||
abspath == @version_file ? "VERSION" : super
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,65 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Zeitwerk
|
||||
# @private
|
||||
class GemLoader < Loader
|
||||
# Users should not create instances directly, the public interface is
|
||||
# `Zeitwerk::Loader.for_gem`.
|
||||
private_class_method :new
|
||||
|
||||
# @private
|
||||
# @sig (String, bool) -> Zeitwerk::GemLoader
|
||||
def self._new(root_file, warn_on_extra_files:)
|
||||
new(root_file, warn_on_extra_files: warn_on_extra_files)
|
||||
end
|
||||
|
||||
# @sig (String, bool) -> void
|
||||
def initialize(root_file, warn_on_extra_files:)
|
||||
super()
|
||||
|
||||
@tag = File.basename(root_file, ".rb")
|
||||
@inflector = GemInflector.new(root_file)
|
||||
@root_file = File.expand_path(root_file)
|
||||
@lib = File.dirname(root_file)
|
||||
@warn_on_extra_files = warn_on_extra_files
|
||||
|
||||
push_dir(@lib)
|
||||
end
|
||||
|
||||
# @sig () -> void
|
||||
def setup
|
||||
warn_on_extra_files if @warn_on_extra_files
|
||||
super
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# @sig () -> void
|
||||
def warn_on_extra_files
|
||||
expected_namespace_dir = @root_file.delete_suffix(".rb")
|
||||
|
||||
ls(@lib) do |basename, abspath|
|
||||
next if abspath == @root_file
|
||||
next if abspath == expected_namespace_dir
|
||||
|
||||
basename_without_ext = basename.delete_suffix(".rb")
|
||||
cname = inflector.camelize(basename_without_ext, abspath).to_sym
|
||||
ftype = dir?(abspath) ? "directory" : "file"
|
||||
|
||||
warn(<<~EOS)
|
||||
WARNING: Zeitwerk defines the constant #{cname} after the #{ftype}
|
||||
|
||||
#{abspath}
|
||||
|
||||
To prevent that, please configure the loader to ignore it:
|
||||
|
||||
loader.ignore("\#{__dir__}/#{basename}")
|
||||
|
||||
Otherwise, there is a flag to silence this warning:
|
||||
|
||||
Zeitwerk::Loader.for_gem(warn_on_extra_files: false)
|
||||
EOS
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,46 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Zeitwerk
|
||||
class Inflector
|
||||
# Very basic snake case -> camel case conversion.
|
||||
#
|
||||
# inflector = Zeitwerk::Inflector.new
|
||||
# inflector.camelize("post", ...) # => "Post"
|
||||
# inflector.camelize("users_controller", ...) # => "UsersController"
|
||||
# inflector.camelize("api", ...) # => "Api"
|
||||
#
|
||||
# Takes into account hard-coded mappings configured with `inflect`.
|
||||
#
|
||||
# @sig (String, String) -> String
|
||||
def camelize(basename, _abspath)
|
||||
overrides[basename] || basename.split('_').each(&:capitalize!).join
|
||||
end
|
||||
|
||||
# Configures hard-coded inflections:
|
||||
#
|
||||
# inflector = Zeitwerk::Inflector.new
|
||||
# inflector.inflect(
|
||||
# "html_parser" => "HTMLParser",
|
||||
# "mysql_adapter" => "MySQLAdapter"
|
||||
# )
|
||||
#
|
||||
# inflector.camelize("html_parser", abspath) # => "HTMLParser"
|
||||
# inflector.camelize("mysql_adapter", abspath) # => "MySQLAdapter"
|
||||
# inflector.camelize("users_controller", abspath) # => "UsersController"
|
||||
#
|
||||
# @sig (Hash[String, String]) -> void
|
||||
def inflect(inflections)
|
||||
overrides.merge!(inflections)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Hard-coded basename to constant name user maps that override the default
|
||||
# inflection logic.
|
||||
#
|
||||
# @sig () -> Hash[String, String]
|
||||
def overrides
|
||||
@overrides ||= {}
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,12 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
# This is a private module.
|
||||
module Zeitwerk::Internal
|
||||
def internal(method_name)
|
||||
private method_name
|
||||
|
||||
mangled = "__#{method_name}"
|
||||
alias_method mangled, method_name
|
||||
public mangled
|
||||
end
|
||||
end
|
||||
@ -1,68 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Kernel
|
||||
module_function
|
||||
|
||||
# Zeitwerk's main idea is to define autoloads for project constants, and then
|
||||
# intercept them when triggered in this thin `Kernel#require` wrapper.
|
||||
#
|
||||
# That allows us to complete the circle, invoke callbacks, autovivify modules,
|
||||
# define autoloads for just autoloaded namespaces, update internal state, etc.
|
||||
#
|
||||
# On the other hand, if you publish a new version of a gem that is now managed
|
||||
# by Zeitwerk, client code can reference directly your classes and modules and
|
||||
# should not require anything. But if someone has legacy require calls around,
|
||||
# they will work as expected, and in a compatible way. This feature is by now
|
||||
# EXPERIMENTAL and UNDOCUMENTED.
|
||||
#
|
||||
# We cannot decorate with prepend + super because Kernel has already been
|
||||
# included in Object, and changes in ancestors don't get propagated into
|
||||
# already existing ancestor chains on Ruby < 3.0.
|
||||
alias_method :zeitwerk_original_require, :require
|
||||
class << self
|
||||
alias_method :zeitwerk_original_require, :require
|
||||
end
|
||||
|
||||
# @sig (String) -> true | false
|
||||
def require(path)
|
||||
if loader = Zeitwerk::Registry.loader_for(path)
|
||||
if path.end_with?(".rb")
|
||||
required = zeitwerk_original_require(path)
|
||||
loader.on_file_autoloaded(path) if required
|
||||
required
|
||||
else
|
||||
loader.on_dir_autoloaded(path)
|
||||
true
|
||||
end
|
||||
else
|
||||
required = zeitwerk_original_require(path)
|
||||
if required
|
||||
abspath = $LOADED_FEATURES.last
|
||||
if loader = Zeitwerk::Registry.loader_for(abspath)
|
||||
loader.on_file_autoloaded(abspath)
|
||||
end
|
||||
end
|
||||
required
|
||||
end
|
||||
end
|
||||
|
||||
# By now, I have seen no way so far to decorate require_relative.
|
||||
#
|
||||
# For starters, at least in CRuby, require_relative does not delegate to
|
||||
# require. Both require and require_relative delegate the bulk of their work
|
||||
# to an internal C function called rb_require_safe. So, our require wrapper is
|
||||
# not executed.
|
||||
#
|
||||
# On the other hand, we cannot use the aliasing technique above because
|
||||
# require_relative receives a path relative to the directory of the file in
|
||||
# which the call is performed. If a wrapper here invoked the original method,
|
||||
# Ruby would resolve the relative path taking lib/zeitwerk as base directory.
|
||||
#
|
||||
# A workaround could be to extract the base directory from caller_locations,
|
||||
# but what if someone else decorated require_relative before us? You can't
|
||||
# really know with certainty where's the original call site in the stack.
|
||||
#
|
||||
# However, the main use case for require_relative is to load files from your
|
||||
# own project. Projects managed by Zeitwerk don't do this for files managed by
|
||||
# Zeitwerk, precisely.
|
||||
end
|
||||
@ -1,514 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require "set"
|
||||
|
||||
module Zeitwerk
|
||||
class Loader
|
||||
require_relative "loader/helpers"
|
||||
require_relative "loader/callbacks"
|
||||
require_relative "loader/config"
|
||||
require_relative "loader/eager_load"
|
||||
|
||||
extend Internal
|
||||
|
||||
include RealModName
|
||||
include Callbacks
|
||||
include Helpers
|
||||
include Config
|
||||
include EagerLoad
|
||||
|
||||
MUTEX = Mutex.new
|
||||
private_constant :MUTEX
|
||||
|
||||
# Maps absolute paths for which an autoload has been set ---and not
|
||||
# executed--- to their corresponding parent class or module and constant
|
||||
# name.
|
||||
#
|
||||
# "/Users/fxn/blog/app/models/user.rb" => [Object, :User],
|
||||
# "/Users/fxn/blog/app/models/hotel/pricing.rb" => [Hotel, :Pricing]
|
||||
# ...
|
||||
#
|
||||
# @sig Hash[String, [Module, Symbol]]
|
||||
attr_reader :autoloads
|
||||
internal :autoloads
|
||||
|
||||
# We keep track of autoloaded directories to remove them from the registry
|
||||
# at the end of eager loading.
|
||||
#
|
||||
# Files are removed as they are autoloaded, but directories need to wait due
|
||||
# to concurrency (see why in Zeitwerk::Loader::Callbacks#on_dir_autoloaded).
|
||||
#
|
||||
# @sig Array[String]
|
||||
attr_reader :autoloaded_dirs
|
||||
internal :autoloaded_dirs
|
||||
|
||||
# Stores metadata needed for unloading. Its entries look like this:
|
||||
#
|
||||
# "Admin::Role" => [".../admin/role.rb", [Admin, :Role]]
|
||||
#
|
||||
# The cpath as key helps implementing unloadable_cpath? The file name is
|
||||
# stored in order to be able to delete it from $LOADED_FEATURES, and the
|
||||
# pair [Module, Symbol] is used to remove_const the constant from the class
|
||||
# or module object.
|
||||
#
|
||||
# If reloading is enabled, this hash is filled as constants are autoloaded
|
||||
# or eager loaded. Otherwise, the collection remains empty.
|
||||
#
|
||||
# @sig Hash[String, [String, [Module, Symbol]]]
|
||||
attr_reader :to_unload
|
||||
internal :to_unload
|
||||
|
||||
# Maps namespace constant paths to their respective directories.
|
||||
#
|
||||
# For example, given this mapping:
|
||||
#
|
||||
# "Admin" => [
|
||||
# "/Users/fxn/blog/app/controllers/admin",
|
||||
# "/Users/fxn/blog/app/models/admin",
|
||||
# ...
|
||||
# ]
|
||||
#
|
||||
# when `Admin` gets defined we know that it plays the role of a namespace
|
||||
# and that its children are spread over those directories. We'll visit them
|
||||
# to set up the corresponding autoloads.
|
||||
#
|
||||
# @sig Hash[String, Array[String]]
|
||||
attr_reader :namespace_dirs
|
||||
internal :namespace_dirs
|
||||
|
||||
# A shadowed file is a file managed by this loader that is ignored when
|
||||
# setting autoloads because its matching constant is already taken.
|
||||
#
|
||||
# This private set is populated as we descend. For example, if the loader
|
||||
# has only scanned the top-level, `shadowed_files` does not have shadowed
|
||||
# files that may exist deep in the project tree yet.
|
||||
#
|
||||
# @sig Set[String]
|
||||
attr_reader :shadowed_files
|
||||
internal :shadowed_files
|
||||
|
||||
# @sig Mutex
|
||||
attr_reader :mutex
|
||||
private :mutex
|
||||
|
||||
# @sig Mutex
|
||||
attr_reader :mutex2
|
||||
private :mutex2
|
||||
|
||||
def initialize
|
||||
super
|
||||
|
||||
@autoloads = {}
|
||||
@autoloaded_dirs = []
|
||||
@to_unload = {}
|
||||
@namespace_dirs = Hash.new { |h, cpath| h[cpath] = [] }
|
||||
@shadowed_files = Set.new
|
||||
@mutex = Mutex.new
|
||||
@mutex2 = Mutex.new
|
||||
@setup = false
|
||||
@eager_loaded = false
|
||||
|
||||
Registry.register_loader(self)
|
||||
end
|
||||
|
||||
# Sets autoloads in the root namespaces.
|
||||
#
|
||||
# @sig () -> void
|
||||
def setup
|
||||
mutex.synchronize do
|
||||
break if @setup
|
||||
|
||||
actual_roots.each do |root_dir, root_namespace|
|
||||
set_autoloads_in_dir(root_dir, root_namespace)
|
||||
end
|
||||
|
||||
on_setup_callbacks.each(&:call)
|
||||
|
||||
@setup = true
|
||||
end
|
||||
end
|
||||
|
||||
# Removes loaded constants and configured autoloads.
|
||||
#
|
||||
# The objects the constants stored are no longer reachable through them. In
|
||||
# addition, since said objects are normally not referenced from anywhere
|
||||
# else, they are eligible for garbage collection, which would effectively
|
||||
# unload them.
|
||||
#
|
||||
# This method is public but undocumented. Main interface is `reload`, which
|
||||
# means `unload` + `setup`. This one is available to be used together with
|
||||
# `unregister`, which is undocumented too.
|
||||
#
|
||||
# @sig () -> void
|
||||
def unload
|
||||
mutex.synchronize do
|
||||
raise SetupRequired unless @setup
|
||||
|
||||
# We are going to keep track of the files that were required by our
|
||||
# autoloads to later remove them from $LOADED_FEATURES, thus making them
|
||||
# loadable by Kernel#require again.
|
||||
#
|
||||
# Directories are not stored in $LOADED_FEATURES, keeping track of files
|
||||
# is enough.
|
||||
unloaded_files = Set.new
|
||||
|
||||
autoloads.each do |abspath, (parent, cname)|
|
||||
if parent.autoload?(cname)
|
||||
unload_autoload(parent, cname)
|
||||
else
|
||||
# Could happen if loaded with require_relative. That is unsupported,
|
||||
# and the constant path would escape unloadable_cpath? This is just
|
||||
# defensive code to clean things up as much as we are able to.
|
||||
unload_cref(parent, cname)
|
||||
unloaded_files.add(abspath) if ruby?(abspath)
|
||||
end
|
||||
end
|
||||
|
||||
to_unload.each do |cpath, (abspath, (parent, cname))|
|
||||
unless on_unload_callbacks.empty?
|
||||
begin
|
||||
value = cget(parent, cname)
|
||||
rescue ::NameError
|
||||
# Perhaps the user deleted the constant by hand, or perhaps an
|
||||
# autoload failed to define the expected constant but the user
|
||||
# rescued the exception.
|
||||
else
|
||||
run_on_unload_callbacks(cpath, value, abspath)
|
||||
end
|
||||
end
|
||||
|
||||
unload_cref(parent, cname)
|
||||
unloaded_files.add(abspath) if ruby?(abspath)
|
||||
end
|
||||
|
||||
unless unloaded_files.empty?
|
||||
# Bootsnap decorates Kernel#require to speed it up using a cache and
|
||||
# this optimization does not check if $LOADED_FEATURES has the file.
|
||||
#
|
||||
# To make it aware of changes, the gem defines singleton methods in
|
||||
# $LOADED_FEATURES:
|
||||
#
|
||||
# https://github.com/Shopify/bootsnap/blob/master/lib/bootsnap/load_path_cache/core_ext/loaded_features.rb
|
||||
#
|
||||
# Rails applications may depend on bootsnap, so for unloading to work
|
||||
# in that setting it is preferable that we restrict our API choice to
|
||||
# one of those methods.
|
||||
$LOADED_FEATURES.reject! { |file| unloaded_files.member?(file) }
|
||||
end
|
||||
|
||||
autoloads.clear
|
||||
autoloaded_dirs.clear
|
||||
to_unload.clear
|
||||
namespace_dirs.clear
|
||||
shadowed_files.clear
|
||||
|
||||
Registry.on_unload(self)
|
||||
ExplicitNamespace.__unregister_loader(self)
|
||||
|
||||
@setup = false
|
||||
@eager_loaded = false
|
||||
end
|
||||
end
|
||||
|
||||
# Unloads all loaded code, and calls setup again so that the loader is able
|
||||
# to pick any changes in the file system.
|
||||
#
|
||||
# This method is not thread-safe, please see how this can be achieved by
|
||||
# client code in the README of the project.
|
||||
#
|
||||
# @raise [Zeitwerk::Error]
|
||||
# @sig () -> void
|
||||
def reload
|
||||
raise ReloadingDisabledError unless reloading_enabled?
|
||||
raise SetupRequired unless @setup
|
||||
|
||||
unload
|
||||
recompute_ignored_paths
|
||||
recompute_collapse_dirs
|
||||
setup
|
||||
end
|
||||
|
||||
# Says if the given constant path would be unloaded on reload. This
|
||||
# predicate returns `false` if reloading is disabled.
|
||||
#
|
||||
# @sig (String) -> bool
|
||||
def unloadable_cpath?(cpath)
|
||||
to_unload.key?(cpath)
|
||||
end
|
||||
|
||||
# Returns an array with the constant paths that would be unloaded on reload.
|
||||
# This predicate returns an empty array if reloading is disabled.
|
||||
#
|
||||
# @sig () -> Array[String]
|
||||
def unloadable_cpaths
|
||||
to_unload.keys.freeze
|
||||
end
|
||||
|
||||
# This is a dangerous method.
|
||||
#
|
||||
# @experimental
|
||||
# @sig () -> void
|
||||
def unregister
|
||||
Registry.unregister_loader(self)
|
||||
ExplicitNamespace.__unregister_loader(self)
|
||||
end
|
||||
|
||||
# The return value of this predicate is only meaningful if the loader has
|
||||
# scanned the file. This is the case in the spots where we use it.
|
||||
#
|
||||
# @sig (String) -> Boolean
|
||||
internal def shadowed_file?(file)
|
||||
shadowed_files.member?(file)
|
||||
end
|
||||
|
||||
# --- Class methods ---------------------------------------------------------------------------
|
||||
|
||||
class << self
|
||||
# @sig #call | #debug | nil
|
||||
attr_accessor :default_logger
|
||||
|
||||
# This is a shortcut for
|
||||
#
|
||||
# require "zeitwerk"
|
||||
# loader = Zeitwerk::Loader.new
|
||||
# loader.tag = File.basename(__FILE__, ".rb")
|
||||
# loader.inflector = Zeitwerk::GemInflector.new(__FILE__)
|
||||
# loader.push_dir(__dir__)
|
||||
#
|
||||
# except that this method returns the same object in subsequent calls from
|
||||
# the same file, in the unlikely case the gem wants to be able to reload.
|
||||
#
|
||||
# This method returns a subclass of Zeitwerk::Loader, but the exact type
|
||||
# is private, client code can only rely on the interface.
|
||||
#
|
||||
# @sig (bool) -> Zeitwerk::GemLoader
|
||||
def for_gem(warn_on_extra_files: true)
|
||||
called_from = caller_locations(1, 1).first.path
|
||||
Registry.loader_for_gem(called_from, warn_on_extra_files: warn_on_extra_files)
|
||||
end
|
||||
|
||||
# Broadcasts `eager_load` to all loaders. Those that have not been setup
|
||||
# are skipped.
|
||||
#
|
||||
# @sig () -> void
|
||||
def eager_load_all
|
||||
Registry.loaders.each do |loader|
|
||||
begin
|
||||
loader.eager_load
|
||||
rescue SetupRequired
|
||||
# This is fine, we eager load what can be eager loaded.
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Broadcasts `eager_load_namespace` to all loaders. Those that have not
|
||||
# been setup are skipped.
|
||||
#
|
||||
# @sig (Module) -> void
|
||||
def eager_load_namespace(mod)
|
||||
Registry.loaders.each do |loader|
|
||||
begin
|
||||
loader.eager_load_namespace(mod)
|
||||
rescue SetupRequired
|
||||
# This is fine, we eager load what can be eager loaded.
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Returns an array with the absolute paths of the root directories of all
|
||||
# registered loaders. This is a read-only collection.
|
||||
#
|
||||
# @sig () -> Array[String]
|
||||
def all_dirs
|
||||
Registry.loaders.flat_map(&:dirs).freeze
|
||||
end
|
||||
end
|
||||
|
||||
# @sig (String, Module) -> void
|
||||
private def set_autoloads_in_dir(dir, parent)
|
||||
ls(dir) do |basename, abspath|
|
||||
begin
|
||||
if ruby?(basename)
|
||||
basename.delete_suffix!(".rb")
|
||||
cname = inflector.camelize(basename, abspath).to_sym
|
||||
autoload_file(parent, cname, abspath)
|
||||
else
|
||||
if collapse?(abspath)
|
||||
set_autoloads_in_dir(abspath, parent)
|
||||
else
|
||||
cname = inflector.camelize(basename, abspath).to_sym
|
||||
autoload_subdir(parent, cname, abspath)
|
||||
end
|
||||
end
|
||||
rescue ::NameError => error
|
||||
path_type = ruby?(abspath) ? "file" : "directory"
|
||||
|
||||
raise NameError.new(<<~MESSAGE, error.name)
|
||||
#{error.message} inferred by #{inflector.class} from #{path_type}
|
||||
|
||||
#{abspath}
|
||||
|
||||
Possible ways to address this:
|
||||
|
||||
* Tell Zeitwerk to ignore this particular #{path_type}.
|
||||
* Tell Zeitwerk to ignore one of its parent directories.
|
||||
* Rename the #{path_type} to comply with the naming conventions.
|
||||
* Modify the inflector to handle this case.
|
||||
MESSAGE
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# @sig (Module, Symbol, String) -> void
|
||||
private def autoload_subdir(parent, cname, subdir)
|
||||
if autoload_path = autoload_path_set_by_me_for?(parent, cname)
|
||||
cpath = cpath(parent, cname)
|
||||
if ruby?(autoload_path)
|
||||
# Scanning visited a Ruby file first, and now a directory for the same
|
||||
# constant has been found. This means we are dealing with an explicit
|
||||
# namespace whose definition was seen first.
|
||||
#
|
||||
# Registering is idempotent, and we have to keep the autoload pointing
|
||||
# to the file. This may run again if more directories are found later
|
||||
# on, no big deal.
|
||||
register_explicit_namespace(cpath)
|
||||
end
|
||||
# If the existing autoload points to a file, it has to be preserved, if
|
||||
# not, it is fine as it is. In either case, we do not need to override.
|
||||
# Just remember the subdirectory conforms this namespace.
|
||||
namespace_dirs[cpath] << subdir
|
||||
elsif !cdef?(parent, cname)
|
||||
# First time we find this namespace, set an autoload for it.
|
||||
namespace_dirs[cpath(parent, cname)] << subdir
|
||||
set_autoload(parent, cname, subdir)
|
||||
else
|
||||
# For whatever reason the constant that corresponds to this namespace has
|
||||
# already been defined, we have to recurse.
|
||||
log("the namespace #{cpath(parent, cname)} already exists, descending into #{subdir}") if logger
|
||||
set_autoloads_in_dir(subdir, cget(parent, cname))
|
||||
end
|
||||
end
|
||||
|
||||
# @sig (Module, Symbol, String) -> void
|
||||
private def autoload_file(parent, cname, file)
|
||||
if autoload_path = strict_autoload_path(parent, cname) || Registry.inception?(cpath(parent, cname))
|
||||
# First autoload for a Ruby file wins, just ignore subsequent ones.
|
||||
if ruby?(autoload_path)
|
||||
shadowed_files << file
|
||||
log("file #{file} is ignored because #{autoload_path} has precedence") if logger
|
||||
else
|
||||
promote_namespace_from_implicit_to_explicit(
|
||||
dir: autoload_path,
|
||||
file: file,
|
||||
parent: parent,
|
||||
cname: cname
|
||||
)
|
||||
end
|
||||
elsif cdef?(parent, cname)
|
||||
shadowed_files << file
|
||||
log("file #{file} is ignored because #{cpath(parent, cname)} is already defined") if logger
|
||||
else
|
||||
set_autoload(parent, cname, file)
|
||||
end
|
||||
end
|
||||
|
||||
# `dir` is the directory that would have autovivified a namespace. `file` is
|
||||
# the file where we've found the namespace is explicitly defined.
|
||||
#
|
||||
# @sig (dir: String, file: String, parent: Module, cname: Symbol) -> void
|
||||
private def promote_namespace_from_implicit_to_explicit(dir:, file:, parent:, cname:)
|
||||
autoloads.delete(dir)
|
||||
Registry.unregister_autoload(dir)
|
||||
|
||||
log("earlier autoload for #{cpath(parent, cname)} discarded, it is actually an explicit namespace defined in #{file}") if logger
|
||||
|
||||
set_autoload(parent, cname, file)
|
||||
register_explicit_namespace(cpath(parent, cname))
|
||||
end
|
||||
|
||||
# @sig (Module, Symbol, String) -> void
|
||||
private def set_autoload(parent, cname, abspath)
|
||||
parent.autoload(cname, abspath)
|
||||
|
||||
if logger
|
||||
if ruby?(abspath)
|
||||
log("autoload set for #{cpath(parent, cname)}, to be loaded from #{abspath}")
|
||||
else
|
||||
log("autoload set for #{cpath(parent, cname)}, to be autovivified from #{abspath}")
|
||||
end
|
||||
end
|
||||
|
||||
autoloads[abspath] = [parent, cname]
|
||||
Registry.register_autoload(self, abspath)
|
||||
|
||||
# See why in the documentation of Zeitwerk::Registry.inceptions.
|
||||
unless parent.autoload?(cname)
|
||||
Registry.register_inception(cpath(parent, cname), abspath, self)
|
||||
end
|
||||
end
|
||||
|
||||
# @sig (Module, Symbol) -> String?
|
||||
private def autoload_path_set_by_me_for?(parent, cname)
|
||||
if autoload_path = strict_autoload_path(parent, cname)
|
||||
autoload_path if autoloads.key?(autoload_path)
|
||||
else
|
||||
Registry.inception?(cpath(parent, cname))
|
||||
end
|
||||
end
|
||||
|
||||
# @sig (String) -> void
|
||||
private def register_explicit_namespace(cpath)
|
||||
ExplicitNamespace.__register(cpath, self)
|
||||
end
|
||||
|
||||
# @sig (String) -> void
|
||||
private def raise_if_conflicting_directory(dir)
|
||||
MUTEX.synchronize do
|
||||
dir_slash = dir + "/"
|
||||
|
||||
Registry.loaders.each do |loader|
|
||||
next if loader == self
|
||||
next if loader.__ignores?(dir)
|
||||
|
||||
loader.__roots.each_key do |root_dir|
|
||||
next if ignores?(root_dir)
|
||||
|
||||
root_dir_slash = root_dir + "/"
|
||||
if dir_slash.start_with?(root_dir_slash) || root_dir_slash.start_with?(dir_slash)
|
||||
require "pp" # Needed for pretty_inspect, even in Ruby 2.5.
|
||||
raise Error,
|
||||
"loader\n\n#{pretty_inspect}\n\nwants to manage directory #{dir}," \
|
||||
" which is already managed by\n\n#{loader.pretty_inspect}\n"
|
||||
EOS
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# @sig (String, Object, String) -> void
|
||||
private def run_on_unload_callbacks(cpath, value, abspath)
|
||||
# Order matters. If present, run the most specific one.
|
||||
on_unload_callbacks[cpath]&.each { |c| c.call(value, abspath) }
|
||||
on_unload_callbacks[:ANY]&.each { |c| c.call(cpath, value, abspath) }
|
||||
end
|
||||
|
||||
# @sig (Module, Symbol) -> void
|
||||
private def unload_autoload(parent, cname)
|
||||
crem(parent, cname)
|
||||
log("autoload for #{cpath(parent, cname)} removed") if logger
|
||||
end
|
||||
|
||||
# @sig (Module, Symbol) -> void
|
||||
private def unload_cref(parent, cname)
|
||||
# Let's optimistically remove_const. The way we use it, this is going to
|
||||
# succeed always if all is good.
|
||||
crem(parent, cname)
|
||||
rescue ::NameError
|
||||
# There are a few edge scenarios in which this may happen. If the constant
|
||||
# is gone, that is OK, anyway.
|
||||
else
|
||||
log("#{cpath(parent, cname)} unloaded") if logger
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,92 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Zeitwerk::Loader::Callbacks
|
||||
include Zeitwerk::RealModName
|
||||
|
||||
# Invoked from our decorated Kernel#require when a managed file is autoloaded.
|
||||
#
|
||||
# @private
|
||||
# @sig (String) -> void
|
||||
def on_file_autoloaded(file)
|
||||
cref = autoloads.delete(file)
|
||||
cpath = cpath(*cref)
|
||||
|
||||
Zeitwerk::Registry.unregister_autoload(file)
|
||||
|
||||
if cdef?(*cref)
|
||||
log("constant #{cpath} loaded from file #{file}") if logger
|
||||
to_unload[cpath] = [file, cref] if reloading_enabled?
|
||||
run_on_load_callbacks(cpath, cget(*cref), file) unless on_load_callbacks.empty?
|
||||
else
|
||||
msg = "expected file #{file} to define constant #{cpath}, but didn't"
|
||||
log(msg) if logger
|
||||
crem(*cref)
|
||||
to_unload[cpath] = [file, cref] if reloading_enabled?
|
||||
raise Zeitwerk::NameError.new(msg, cref.last)
|
||||
end
|
||||
end
|
||||
|
||||
# Invoked from our decorated Kernel#require when a managed directory is
|
||||
# autoloaded.
|
||||
#
|
||||
# @private
|
||||
# @sig (String) -> void
|
||||
def on_dir_autoloaded(dir)
|
||||
# Module#autoload does not serialize concurrent requires, and we handle
|
||||
# directories ourselves, so the callback needs to account for concurrency.
|
||||
#
|
||||
# Multi-threading would introduce a race condition here in which thread t1
|
||||
# autovivifies the module, and while autoloads for its children are being
|
||||
# set, thread t2 autoloads the same namespace.
|
||||
#
|
||||
# Without the mutex and subsequent delete call, t2 would reset the module.
|
||||
# That not only would reassign the constant (undesirable per se) but, worse,
|
||||
# the module object created by t2 wouldn't have any of the autoloads for its
|
||||
# children, since t1 would have correctly deleted its namespace_dirs entry.
|
||||
mutex2.synchronize do
|
||||
if cref = autoloads.delete(dir)
|
||||
autovivified_module = cref[0].const_set(cref[1], Module.new)
|
||||
cpath = autovivified_module.name
|
||||
log("module #{cpath} autovivified from directory #{dir}") if logger
|
||||
|
||||
to_unload[cpath] = [dir, cref] if reloading_enabled?
|
||||
|
||||
# We don't unregister `dir` in the registry because concurrent threads
|
||||
# wouldn't find a loader associated to it in Kernel#require and would
|
||||
# try to require the directory. Instead, we are going to keep track of
|
||||
# these to be able to unregister later if eager loading.
|
||||
autoloaded_dirs << dir
|
||||
|
||||
on_namespace_loaded(autovivified_module)
|
||||
|
||||
run_on_load_callbacks(cpath, autovivified_module, dir) unless on_load_callbacks.empty?
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Invoked when a class or module is created or reopened, either from the
|
||||
# tracer or from module autovivification. If the namespace has matching
|
||||
# subdirectories, we descend into them now.
|
||||
#
|
||||
# @private
|
||||
# @sig (Module) -> void
|
||||
def on_namespace_loaded(namespace)
|
||||
if dirs = namespace_dirs.delete(real_mod_name(namespace))
|
||||
dirs.each do |dir|
|
||||
set_autoloads_in_dir(dir, namespace)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# @sig (String, Object) -> void
|
||||
def run_on_load_callbacks(cpath, value, abspath)
|
||||
# Order matters. If present, run the most specific one.
|
||||
callbacks = reloading_enabled? ? on_load_callbacks[cpath] : on_load_callbacks.delete(cpath)
|
||||
callbacks&.each { |c| c.call(value, abspath) }
|
||||
|
||||
callbacks = on_load_callbacks[:ANY]
|
||||
callbacks&.each { |c| c.call(cpath, value, abspath) }
|
||||
end
|
||||
end
|
||||
@ -1,365 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require "set"
|
||||
require "securerandom"
|
||||
|
||||
module Zeitwerk::Loader::Config
|
||||
extend Zeitwerk::Internal
|
||||
include Zeitwerk::RealModName
|
||||
|
||||
# @sig #camelize
|
||||
attr_accessor :inflector
|
||||
|
||||
# @sig #call | #debug | nil
|
||||
attr_accessor :logger
|
||||
|
||||
# Absolute paths of the root directories, mapped to their respective root namespaces:
|
||||
#
|
||||
# "/Users/fxn/blog/app/channels" => Object,
|
||||
# "/Users/fxn/blog/app/adapters" => ActiveJob::QueueAdapters,
|
||||
# ...
|
||||
#
|
||||
# Stored in a hash to preserve order, easily handle duplicates, and have a
|
||||
# fast lookup by directory.
|
||||
#
|
||||
# This is a private collection maintained by the loader. The public
|
||||
# interface for it is `push_dir` and `dirs`.
|
||||
#
|
||||
# @sig Hash[String, Module]
|
||||
attr_reader :roots
|
||||
internal :roots
|
||||
|
||||
# Absolute paths of files, directories, or glob patterns to be totally
|
||||
# ignored.
|
||||
#
|
||||
# @sig Set[String]
|
||||
attr_reader :ignored_glob_patterns
|
||||
private :ignored_glob_patterns
|
||||
|
||||
# The actual collection of absolute file and directory names at the time the
|
||||
# ignored glob patterns were expanded. Computed on setup, and recomputed on
|
||||
# reload.
|
||||
#
|
||||
# @sig Set[String]
|
||||
attr_reader :ignored_paths
|
||||
private :ignored_paths
|
||||
|
||||
# Absolute paths of directories or glob patterns to be collapsed.
|
||||
#
|
||||
# @sig Set[String]
|
||||
attr_reader :collapse_glob_patterns
|
||||
private :collapse_glob_patterns
|
||||
|
||||
# The actual collection of absolute directory names at the time the collapse
|
||||
# glob patterns were expanded. Computed on setup, and recomputed on reload.
|
||||
#
|
||||
# @sig Set[String]
|
||||
attr_reader :collapse_dirs
|
||||
private :collapse_dirs
|
||||
|
||||
# Absolute paths of files or directories not to be eager loaded.
|
||||
#
|
||||
# @sig Set[String]
|
||||
attr_reader :eager_load_exclusions
|
||||
private :eager_load_exclusions
|
||||
|
||||
# User-oriented callbacks to be fired on setup and on reload.
|
||||
#
|
||||
# @sig Array[{ () -> void }]
|
||||
attr_reader :on_setup_callbacks
|
||||
private :on_setup_callbacks
|
||||
|
||||
# User-oriented callbacks to be fired when a constant is loaded.
|
||||
#
|
||||
# @sig Hash[String, Array[{ (Object, String) -> void }]]
|
||||
# Hash[Symbol, Array[{ (String, Object, String) -> void }]]
|
||||
attr_reader :on_load_callbacks
|
||||
private :on_load_callbacks
|
||||
|
||||
# User-oriented callbacks to be fired before constants are removed.
|
||||
#
|
||||
# @sig Hash[String, Array[{ (Object, String) -> void }]]
|
||||
# Hash[Symbol, Array[{ (String, Object, String) -> void }]]
|
||||
attr_reader :on_unload_callbacks
|
||||
private :on_unload_callbacks
|
||||
|
||||
def initialize
|
||||
@inflector = Zeitwerk::Inflector.new
|
||||
@logger = self.class.default_logger
|
||||
@tag = SecureRandom.hex(3)
|
||||
@initialized_at = Time.now
|
||||
@roots = {}
|
||||
@ignored_glob_patterns = Set.new
|
||||
@ignored_paths = Set.new
|
||||
@collapse_glob_patterns = Set.new
|
||||
@collapse_dirs = Set.new
|
||||
@eager_load_exclusions = Set.new
|
||||
@reloading_enabled = false
|
||||
@on_setup_callbacks = []
|
||||
@on_load_callbacks = {}
|
||||
@on_unload_callbacks = {}
|
||||
end
|
||||
|
||||
# Pushes `path` to the list of root directories.
|
||||
#
|
||||
# Raises `Zeitwerk::Error` if `path` does not exist, or if another loader in
|
||||
# the same process already manages that directory or one of its ascendants or
|
||||
# descendants.
|
||||
#
|
||||
# @raise [Zeitwerk::Error]
|
||||
# @sig (String | Pathname, Module) -> void
|
||||
def push_dir(path, namespace: Object)
|
||||
# Note that Class < Module.
|
||||
unless namespace.is_a?(Module)
|
||||
raise Zeitwerk::Error, "#{namespace.inspect} is not a class or module object, should be"
|
||||
end
|
||||
|
||||
unless real_mod_name(namespace)
|
||||
raise Zeitwerk::Error, "root namespaces cannot be anonymous"
|
||||
end
|
||||
|
||||
abspath = File.expand_path(path)
|
||||
if dir?(abspath)
|
||||
raise_if_conflicting_directory(abspath)
|
||||
roots[abspath] = namespace
|
||||
else
|
||||
raise Zeitwerk::Error, "the root directory #{abspath} does not exist"
|
||||
end
|
||||
end
|
||||
|
||||
# Returns the loader's tag.
|
||||
#
|
||||
# Implemented as a method instead of via attr_reader for symmetry with the
|
||||
# writer below.
|
||||
#
|
||||
# @sig () -> String
|
||||
def tag
|
||||
@tag
|
||||
end
|
||||
|
||||
# Sets a tag for the loader, useful for logging.
|
||||
#
|
||||
# @sig (#to_s) -> void
|
||||
def tag=(tag)
|
||||
@tag = tag.to_s
|
||||
end
|
||||
|
||||
# If `namespaces` is falsey (default), returns an array with the absolute
|
||||
# paths of the root directories as strings. If truthy, returns a hash table
|
||||
# instead. Keys are the absolute paths of the root directories as strings,
|
||||
# values are their corresponding namespaces, class or module objects.
|
||||
#
|
||||
# If `ignored` is falsey (default), ignored root directories are filtered out.
|
||||
#
|
||||
# These are read-only collections, please add to them with `push_dir`.
|
||||
#
|
||||
# @sig () -> Array[String] | Hash[String, Module]
|
||||
def dirs(namespaces: false, ignored: false)
|
||||
if namespaces
|
||||
if ignored || ignored_paths.empty?
|
||||
roots.clone
|
||||
else
|
||||
roots.reject { |root_dir, _namespace| ignored_path?(root_dir) }
|
||||
end
|
||||
else
|
||||
if ignored || ignored_paths.empty?
|
||||
roots.keys
|
||||
else
|
||||
roots.keys.reject { |root_dir| ignored_path?(root_dir) }
|
||||
end
|
||||
end.freeze
|
||||
end
|
||||
|
||||
# You need to call this method before setup in order to be able to reload.
|
||||
# There is no way to undo this, either you want to reload or you don't.
|
||||
#
|
||||
# @raise [Zeitwerk::Error]
|
||||
# @sig () -> void
|
||||
def enable_reloading
|
||||
mutex.synchronize do
|
||||
break if @reloading_enabled
|
||||
|
||||
if @setup
|
||||
raise Zeitwerk::Error, "cannot enable reloading after setup"
|
||||
else
|
||||
@reloading_enabled = true
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# @sig () -> bool
|
||||
def reloading_enabled?
|
||||
@reloading_enabled
|
||||
end
|
||||
|
||||
# Let eager load ignore the given files or directories. The constants defined
|
||||
# in those files are still autoloadable.
|
||||
#
|
||||
# @sig (*(String | Pathname | Array[String | Pathname])) -> void
|
||||
def do_not_eager_load(*paths)
|
||||
mutex.synchronize { eager_load_exclusions.merge(expand_paths(paths)) }
|
||||
end
|
||||
|
||||
# Configure files, directories, or glob patterns to be totally ignored.
|
||||
#
|
||||
# @sig (*(String | Pathname | Array[String | Pathname])) -> void
|
||||
def ignore(*glob_patterns)
|
||||
glob_patterns = expand_paths(glob_patterns)
|
||||
mutex.synchronize do
|
||||
ignored_glob_patterns.merge(glob_patterns)
|
||||
ignored_paths.merge(expand_glob_patterns(glob_patterns))
|
||||
end
|
||||
end
|
||||
|
||||
# Configure directories or glob patterns to be collapsed.
|
||||
#
|
||||
# @sig (*(String | Pathname | Array[String | Pathname])) -> void
|
||||
def collapse(*glob_patterns)
|
||||
glob_patterns = expand_paths(glob_patterns)
|
||||
mutex.synchronize do
|
||||
collapse_glob_patterns.merge(glob_patterns)
|
||||
collapse_dirs.merge(expand_glob_patterns(glob_patterns))
|
||||
end
|
||||
end
|
||||
|
||||
# Configure a block to be called after setup and on each reload.
|
||||
# If setup was already done, the block runs immediately.
|
||||
#
|
||||
# @sig () { () -> void } -> void
|
||||
def on_setup(&block)
|
||||
mutex.synchronize do
|
||||
on_setup_callbacks << block
|
||||
block.call if @setup
|
||||
end
|
||||
end
|
||||
|
||||
# Configure a block to be invoked once a certain constant path is loaded.
|
||||
# Supports multiple callbacks, and if there are many, they are executed in
|
||||
# the order in which they were defined.
|
||||
#
|
||||
# loader.on_load("SomeApiClient") do |klass, _abspath|
|
||||
# klass.endpoint = "https://api.dev"
|
||||
# end
|
||||
#
|
||||
# Can also be configured for any constant loaded:
|
||||
#
|
||||
# loader.on_load do |cpath, value, abspath|
|
||||
# # ...
|
||||
# end
|
||||
#
|
||||
# @raise [TypeError]
|
||||
# @sig (String) { (Object, String) -> void } -> void
|
||||
# (:ANY) { (String, Object, String) -> void } -> void
|
||||
def on_load(cpath = :ANY, &block)
|
||||
raise TypeError, "on_load only accepts strings" unless cpath.is_a?(String) || cpath == :ANY
|
||||
|
||||
mutex.synchronize do
|
||||
(on_load_callbacks[cpath] ||= []) << block
|
||||
end
|
||||
end
|
||||
|
||||
# Configure a block to be invoked right before a certain constant is removed.
|
||||
# Supports multiple callbacks, and if there are many, they are executed in the
|
||||
# order in which they were defined.
|
||||
#
|
||||
# loader.on_unload("Country") do |klass, _abspath|
|
||||
# klass.clear_cache
|
||||
# end
|
||||
#
|
||||
# Can also be configured for any removed constant:
|
||||
#
|
||||
# loader.on_unload do |cpath, value, abspath|
|
||||
# # ...
|
||||
# end
|
||||
#
|
||||
# @raise [TypeError]
|
||||
# @sig (String) { (Object) -> void } -> void
|
||||
# (:ANY) { (String, Object) -> void } -> void
|
||||
def on_unload(cpath = :ANY, &block)
|
||||
raise TypeError, "on_unload only accepts strings" unless cpath.is_a?(String) || cpath == :ANY
|
||||
|
||||
mutex.synchronize do
|
||||
(on_unload_callbacks[cpath] ||= []) << block
|
||||
end
|
||||
end
|
||||
|
||||
# Logs to `$stdout`, handy shortcut for debugging.
|
||||
#
|
||||
# @sig () -> void
|
||||
def log!
|
||||
@logger = ->(msg) { puts msg }
|
||||
end
|
||||
|
||||
# Returns true if the argument has been configured to be ignored, or is a
|
||||
# descendant of an ignored directory.
|
||||
#
|
||||
# @sig (String) -> bool
|
||||
internal def ignores?(abspath)
|
||||
# Common use case.
|
||||
return false if ignored_paths.empty?
|
||||
|
||||
walk_up(abspath) do |abspath|
|
||||
return true if ignored_path?(abspath)
|
||||
return false if roots.key?(abspath)
|
||||
end
|
||||
|
||||
false
|
||||
end
|
||||
|
||||
# @sig (String) -> bool
|
||||
private def ignored_path?(abspath)
|
||||
ignored_paths.member?(abspath)
|
||||
end
|
||||
|
||||
# @sig () -> Array[String]
|
||||
private def actual_roots
|
||||
roots.reject do |root_dir, _root_namespace|
|
||||
!dir?(root_dir) || ignored_path?(root_dir)
|
||||
end
|
||||
end
|
||||
|
||||
# @sig (String) -> bool
|
||||
private def root_dir?(dir)
|
||||
roots.key?(dir)
|
||||
end
|
||||
|
||||
# @sig (String) -> bool
|
||||
private def excluded_from_eager_load?(abspath)
|
||||
# Optimize this common use case.
|
||||
return false if eager_load_exclusions.empty?
|
||||
|
||||
walk_up(abspath) do |abspath|
|
||||
return true if eager_load_exclusions.member?(abspath)
|
||||
return false if roots.key?(abspath)
|
||||
end
|
||||
|
||||
false
|
||||
end
|
||||
|
||||
# @sig (String) -> bool
|
||||
private def collapse?(dir)
|
||||
collapse_dirs.member?(dir)
|
||||
end
|
||||
|
||||
# @sig (String | Pathname | Array[String | Pathname]) -> Array[String]
|
||||
private def expand_paths(paths)
|
||||
paths.flatten.map! { |path| File.expand_path(path) }
|
||||
end
|
||||
|
||||
# @sig (Array[String]) -> Array[String]
|
||||
private def expand_glob_patterns(glob_patterns)
|
||||
# Note that Dir.glob works with regular file names just fine. That is,
|
||||
# glob patterns technically need no wildcards.
|
||||
glob_patterns.flat_map { |glob_pattern| Dir.glob(glob_pattern) }
|
||||
end
|
||||
|
||||
# @sig () -> void
|
||||
private def recompute_ignored_paths
|
||||
ignored_paths.replace(expand_glob_patterns(ignored_glob_patterns))
|
||||
end
|
||||
|
||||
# @sig () -> void
|
||||
private def recompute_collapse_dirs
|
||||
collapse_dirs.replace(expand_glob_patterns(collapse_glob_patterns))
|
||||
end
|
||||
end
|
||||
@ -1,228 +0,0 @@
|
||||
module Zeitwerk::Loader::EagerLoad
|
||||
# Eager loads all files in the root directories, recursively. Files do not
|
||||
# need to be in `$LOAD_PATH`, absolute file names are used. Ignored and
|
||||
# shadowed files are not eager loaded. You can opt-out specifically in
|
||||
# specific files and directories with `do_not_eager_load`, and that can be
|
||||
# overridden passing `force: true`.
|
||||
#
|
||||
# @sig (true | false) -> void
|
||||
def eager_load(force: false)
|
||||
mutex.synchronize do
|
||||
break if @eager_loaded
|
||||
raise Zeitwerk::SetupRequired unless @setup
|
||||
|
||||
log("eager load start") if logger
|
||||
|
||||
actual_roots.each do |root_dir, root_namespace|
|
||||
actual_eager_load_dir(root_dir, root_namespace, force: force)
|
||||
end
|
||||
|
||||
autoloaded_dirs.each do |autoloaded_dir|
|
||||
Zeitwerk::Registry.unregister_autoload(autoloaded_dir)
|
||||
end
|
||||
autoloaded_dirs.clear
|
||||
|
||||
@eager_loaded = true
|
||||
|
||||
log("eager load end") if logger
|
||||
end
|
||||
end
|
||||
|
||||
# @sig (String | Pathname) -> void
|
||||
def eager_load_dir(path)
|
||||
raise Zeitwerk::SetupRequired unless @setup
|
||||
|
||||
abspath = File.expand_path(path)
|
||||
|
||||
raise Zeitwerk::Error.new("#{abspath} is not a directory") unless dir?(abspath)
|
||||
|
||||
cnames = []
|
||||
|
||||
root_namespace = nil
|
||||
walk_up(abspath) do |dir|
|
||||
return if ignored_path?(dir)
|
||||
return if eager_load_exclusions.member?(dir)
|
||||
|
||||
break if root_namespace = roots[dir]
|
||||
|
||||
unless collapse?(dir)
|
||||
basename = File.basename(dir)
|
||||
cnames << inflector.camelize(basename, dir).to_sym
|
||||
end
|
||||
end
|
||||
|
||||
raise Zeitwerk::Error.new("I do not manage #{abspath}") unless root_namespace
|
||||
|
||||
return if @eager_loaded
|
||||
|
||||
namespace = root_namespace
|
||||
cnames.reverse_each do |cname|
|
||||
# Can happen if there are no Ruby files. This is not an error condition,
|
||||
# the directory is actually managed. Could have Ruby files later.
|
||||
return unless cdef?(namespace, cname)
|
||||
namespace = cget(namespace, cname)
|
||||
end
|
||||
|
||||
# A shortcircuiting test depends on the invocation of this method. Please
|
||||
# keep them in sync if refactored.
|
||||
actual_eager_load_dir(abspath, namespace)
|
||||
end
|
||||
|
||||
# @sig (Module) -> void
|
||||
def eager_load_namespace(mod)
|
||||
raise Zeitwerk::SetupRequired unless @setup
|
||||
|
||||
unless mod.is_a?(Module)
|
||||
raise Zeitwerk::Error, "#{mod.inspect} is not a class or module object"
|
||||
end
|
||||
|
||||
return if @eager_loaded
|
||||
|
||||
mod_name = real_mod_name(mod)
|
||||
return unless mod_name
|
||||
|
||||
actual_roots.each do |root_dir, root_namespace|
|
||||
if mod.equal?(Object)
|
||||
# A shortcircuiting test depends on the invocation of this method.
|
||||
# Please keep them in sync if refactored.
|
||||
actual_eager_load_dir(root_dir, root_namespace)
|
||||
elsif root_namespace.equal?(Object)
|
||||
eager_load_child_namespace(mod, mod_name, root_dir, root_namespace)
|
||||
else
|
||||
root_namespace_name = real_mod_name(root_namespace)
|
||||
if root_namespace_name.start_with?(mod_name + "::")
|
||||
actual_eager_load_dir(root_dir, root_namespace)
|
||||
elsif mod_name == root_namespace_name
|
||||
actual_eager_load_dir(root_dir, root_namespace)
|
||||
elsif mod_name.start_with?(root_namespace_name + "::")
|
||||
eager_load_child_namespace(mod, mod_name, root_dir, root_namespace)
|
||||
else
|
||||
# Unrelated constant hierarchies, do nothing.
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Loads the given Ruby file.
|
||||
#
|
||||
# Raises if the argument is ignored, shadowed, or not managed by the receiver.
|
||||
#
|
||||
# The method is implemented as `constantize` for files, in a sense, to be able
|
||||
# to descend orderly and make sure the file is loadable.
|
||||
#
|
||||
# @sig (String | Pathname) -> void
|
||||
def load_file(path)
|
||||
abspath = File.expand_path(path)
|
||||
|
||||
raise Zeitwerk::Error.new("#{abspath} does not exist") unless File.exist?(abspath)
|
||||
raise Zeitwerk::Error.new("#{abspath} is not a Ruby file") if dir?(abspath) || !ruby?(abspath)
|
||||
raise Zeitwerk::Error.new("#{abspath} is ignored") if ignored_path?(abspath)
|
||||
|
||||
basename = File.basename(abspath, ".rb")
|
||||
base_cname = inflector.camelize(basename, abspath).to_sym
|
||||
|
||||
root_namespace = nil
|
||||
cnames = []
|
||||
|
||||
walk_up(File.dirname(abspath)) do |dir|
|
||||
raise Zeitwerk::Error.new("#{abspath} is ignored") if ignored_path?(dir)
|
||||
|
||||
break if root_namespace = roots[dir]
|
||||
|
||||
unless collapse?(dir)
|
||||
basename = File.basename(dir)
|
||||
cnames << inflector.camelize(basename, dir).to_sym
|
||||
end
|
||||
end
|
||||
|
||||
raise Zeitwerk::Error.new("I do not manage #{abspath}") unless root_namespace
|
||||
|
||||
namespace = root_namespace
|
||||
cnames.reverse_each do |cname|
|
||||
namespace = cget(namespace, cname)
|
||||
end
|
||||
|
||||
raise Zeitwerk::Error.new("#{abspath} is shadowed") if shadowed_file?(abspath)
|
||||
|
||||
cget(namespace, base_cname)
|
||||
end
|
||||
|
||||
# The caller is responsible for making sure `namespace` is the namespace that
|
||||
# corresponds to `dir`.
|
||||
#
|
||||
# @sig (String, Module, Boolean) -> void
|
||||
private def actual_eager_load_dir(dir, namespace, force: false)
|
||||
honour_exclusions = !force
|
||||
return if honour_exclusions && excluded_from_eager_load?(dir)
|
||||
|
||||
log("eager load directory #{dir} start") if logger
|
||||
|
||||
queue = [[dir, namespace]]
|
||||
while to_eager_load = queue.shift
|
||||
dir, namespace = to_eager_load
|
||||
|
||||
ls(dir) do |basename, abspath|
|
||||
next if honour_exclusions && eager_load_exclusions.member?(abspath)
|
||||
|
||||
if ruby?(abspath)
|
||||
if (cref = autoloads[abspath]) && !shadowed_file?(abspath)
|
||||
cget(*cref)
|
||||
end
|
||||
else
|
||||
if collapse?(abspath)
|
||||
queue << [abspath, namespace]
|
||||
else
|
||||
cname = inflector.camelize(basename, abspath).to_sym
|
||||
queue << [abspath, cget(namespace, cname)]
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
log("eager load directory #{dir} end") if logger
|
||||
end
|
||||
|
||||
# In order to invoke this method, the caller has to ensure `child` is a
|
||||
# strict namespace descendant of `root_namespace`.
|
||||
#
|
||||
# @sig (Module, String, Module, Boolean) -> void
|
||||
private def eager_load_child_namespace(child, child_name, root_dir, root_namespace)
|
||||
suffix = child_name
|
||||
unless root_namespace.equal?(Object)
|
||||
suffix = suffix.delete_prefix(real_mod_name(root_namespace) + "::")
|
||||
end
|
||||
|
||||
# These directories are at the same namespace level, there may be more if
|
||||
# we find collapsed ones. As we scan, we look for matches for the first
|
||||
# segment, and store them in `next_dirs`. If there are any, we look for
|
||||
# the next segments in those matches. Repeat.
|
||||
#
|
||||
# If we exhaust the search locating directories that match all segments,
|
||||
# we just need to eager load those ones.
|
||||
dirs = [root_dir]
|
||||
next_dirs = []
|
||||
|
||||
suffix.split("::").each do |segment|
|
||||
while dir = dirs.shift
|
||||
ls(dir) do |basename, abspath|
|
||||
next unless dir?(abspath)
|
||||
|
||||
if collapse?(abspath)
|
||||
dirs << abspath
|
||||
elsif segment == inflector.camelize(basename, abspath)
|
||||
next_dirs << abspath
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return if next_dirs.empty?
|
||||
|
||||
dirs.replace(next_dirs)
|
||||
next_dirs.clear
|
||||
end
|
||||
|
||||
dirs.each do |dir|
|
||||
actual_eager_load_dir(dir, child)
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,143 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Zeitwerk::Loader::Helpers
|
||||
# --- Logging -----------------------------------------------------------------------------------
|
||||
|
||||
# @sig (String) -> void
|
||||
private def log(message)
|
||||
method_name = logger.respond_to?(:debug) ? :debug : :call
|
||||
logger.send(method_name, "Zeitwerk@#{tag}: #{message}")
|
||||
end
|
||||
|
||||
# --- Files and directories ---------------------------------------------------------------------
|
||||
|
||||
# @sig (String) { (String, String) -> void } -> void
|
||||
private def ls(dir)
|
||||
children = Dir.children(dir)
|
||||
|
||||
# The order in which a directory is listed depends on the file system.
|
||||
#
|
||||
# Since client code may run in different platforms, it seems convenient to
|
||||
# order directory entries. This provides consistent eager loading across
|
||||
# platforms, for example.
|
||||
children.sort!
|
||||
|
||||
children.each do |basename|
|
||||
next if hidden?(basename)
|
||||
|
||||
abspath = File.join(dir, basename)
|
||||
next if ignored_path?(abspath)
|
||||
|
||||
if dir?(abspath)
|
||||
next if roots.key?(abspath)
|
||||
next if !has_at_least_one_ruby_file?(abspath)
|
||||
else
|
||||
next unless ruby?(abspath)
|
||||
end
|
||||
|
||||
# We freeze abspath because that saves allocations when passed later to
|
||||
# File methods. See #125.
|
||||
yield basename, abspath.freeze
|
||||
end
|
||||
end
|
||||
|
||||
# @sig (String) -> bool
|
||||
private def has_at_least_one_ruby_file?(dir)
|
||||
to_visit = [dir]
|
||||
|
||||
while dir = to_visit.shift
|
||||
ls(dir) do |_basename, abspath|
|
||||
if dir?(abspath)
|
||||
to_visit << abspath
|
||||
else
|
||||
return true
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
false
|
||||
end
|
||||
|
||||
# @sig (String) -> bool
|
||||
private def ruby?(path)
|
||||
path.end_with?(".rb")
|
||||
end
|
||||
|
||||
# @sig (String) -> bool
|
||||
private def dir?(path)
|
||||
File.directory?(path)
|
||||
end
|
||||
|
||||
# @sig (String) -> bool
|
||||
private def hidden?(basename)
|
||||
basename.start_with?(".")
|
||||
end
|
||||
|
||||
# @sig (String) { (String) -> void } -> void
|
||||
private def walk_up(abspath)
|
||||
loop do
|
||||
yield abspath
|
||||
abspath, basename = File.split(abspath)
|
||||
break if basename == "/"
|
||||
end
|
||||
end
|
||||
|
||||
# --- Constants ---------------------------------------------------------------------------------
|
||||
|
||||
# The autoload? predicate takes into account the ancestor chain of the
|
||||
# receiver, like const_defined? and other methods in the constants API do.
|
||||
#
|
||||
# For example, given
|
||||
#
|
||||
# class A
|
||||
# autoload :X, "x.rb"
|
||||
# end
|
||||
#
|
||||
# class B < A
|
||||
# end
|
||||
#
|
||||
# B.autoload?(:X) returns "x.rb".
|
||||
#
|
||||
# We need a way to strictly check in parent ignoring ancestors.
|
||||
#
|
||||
# @sig (Module, Symbol) -> String?
|
||||
if method(:autoload?).arity == 1
|
||||
private def strict_autoload_path(parent, cname)
|
||||
parent.autoload?(cname) if cdef?(parent, cname)
|
||||
end
|
||||
else
|
||||
private def strict_autoload_path(parent, cname)
|
||||
parent.autoload?(cname, false)
|
||||
end
|
||||
end
|
||||
|
||||
# @sig (Module, Symbol) -> String
|
||||
if Symbol.method_defined?(:name)
|
||||
# Symbol#name was introduced in Ruby 3.0. It returns always the same
|
||||
# frozen object, so we may save a few string allocations.
|
||||
private def cpath(parent, cname)
|
||||
Object == parent ? cname.name : "#{real_mod_name(parent)}::#{cname.name}"
|
||||
end
|
||||
else
|
||||
private def cpath(parent, cname)
|
||||
Object == parent ? cname.to_s : "#{real_mod_name(parent)}::#{cname}"
|
||||
end
|
||||
end
|
||||
|
||||
# @sig (Module, Symbol) -> bool
|
||||
private def cdef?(parent, cname)
|
||||
parent.const_defined?(cname, false)
|
||||
end
|
||||
|
||||
# @raise [NameError]
|
||||
# @sig (Module, Symbol) -> Object
|
||||
private def cget(parent, cname)
|
||||
parent.const_get(cname, false)
|
||||
end
|
||||
|
||||
# @raise [NameError]
|
||||
# @sig (Module, Symbol) -> Object
|
||||
private def crem(parent, cname)
|
||||
parent.__send__(:remove_const, cname)
|
||||
end
|
||||
end
|
||||
@ -1,22 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Zeitwerk::RealModName
|
||||
UNBOUND_METHOD_MODULE_NAME = Module.instance_method(:name)
|
||||
private_constant :UNBOUND_METHOD_MODULE_NAME
|
||||
|
||||
# Returns the real name of the class or module, as set after the first
|
||||
# constant to which it was assigned (or nil).
|
||||
#
|
||||
# The name method can be overridden, hence the indirection in this method.
|
||||
#
|
||||
# @sig (Module) -> String?
|
||||
if UnboundMethod.method_defined?(:bind_call)
|
||||
def real_mod_name(mod)
|
||||
UNBOUND_METHOD_MODULE_NAME.bind_call(mod)
|
||||
end
|
||||
else
|
||||
def real_mod_name(mod)
|
||||
UNBOUND_METHOD_MODULE_NAME.bind(mod).call
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,138 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Zeitwerk
|
||||
module Registry # :nodoc: all
|
||||
class << self
|
||||
# Keeps track of all loaders. Useful to broadcast messages and to prevent
|
||||
# them from being garbage collected.
|
||||
#
|
||||
# @private
|
||||
# @sig Array[Zeitwerk::Loader]
|
||||
attr_reader :loaders
|
||||
|
||||
# Registers gem loaders to let `for_gem` be idempotent in case of reload.
|
||||
#
|
||||
# @private
|
||||
# @sig Hash[String, Zeitwerk::Loader]
|
||||
attr_reader :gem_loaders_by_root_file
|
||||
|
||||
# Maps absolute paths to the loaders responsible for them.
|
||||
#
|
||||
# This information is used by our decorated `Kernel#require` to be able to
|
||||
# invoke callbacks and autovivify modules.
|
||||
#
|
||||
# @private
|
||||
# @sig Hash[String, Zeitwerk::Loader]
|
||||
attr_reader :autoloads
|
||||
|
||||
# This hash table addresses an edge case in which an autoload is ignored.
|
||||
#
|
||||
# For example, let's suppose we want to autoload in a gem like this:
|
||||
#
|
||||
# # lib/my_gem.rb
|
||||
# loader = Zeitwerk::Loader.new
|
||||
# loader.push_dir(__dir__)
|
||||
# loader.setup
|
||||
#
|
||||
# module MyGem
|
||||
# end
|
||||
#
|
||||
# if you require "my_gem", as Bundler would do, this happens while setting
|
||||
# up autoloads:
|
||||
#
|
||||
# 1. Object.autoload?(:MyGem) returns `nil` because the autoload for
|
||||
# the constant is issued by Zeitwerk while the same file is being
|
||||
# required.
|
||||
# 2. The constant `MyGem` is undefined while setup runs.
|
||||
#
|
||||
# Therefore, a directory `lib/my_gem` would autovivify a module according to
|
||||
# the existing information. But that would be wrong.
|
||||
#
|
||||
# To overcome this fundamental limitation, we keep track of the constant
|
||||
# paths that are in this situation ---in the example above, "MyGem"--- and
|
||||
# take this collection into account for the autovivification logic.
|
||||
#
|
||||
# Note that you cannot generally address this by moving the setup code
|
||||
# below the constant definition, because we want libraries to be able to
|
||||
# use managed constants in the module body:
|
||||
#
|
||||
# module MyGem
|
||||
# include MyConcern
|
||||
# end
|
||||
#
|
||||
# @private
|
||||
# @sig Hash[String, [String, Zeitwerk::Loader]]
|
||||
attr_reader :inceptions
|
||||
|
||||
# Registers a loader.
|
||||
#
|
||||
# @private
|
||||
# @sig (Zeitwerk::Loader) -> void
|
||||
def register_loader(loader)
|
||||
loaders << loader
|
||||
end
|
||||
|
||||
# @private
|
||||
# @sig (Zeitwerk::Loader) -> void
|
||||
def unregister_loader(loader)
|
||||
loaders.delete(loader)
|
||||
gem_loaders_by_root_file.delete_if { |_, l| l == loader }
|
||||
autoloads.delete_if { |_, l| l == loader }
|
||||
inceptions.delete_if { |_, (_, l)| l == loader }
|
||||
end
|
||||
|
||||
# This method returns always a loader, the same instance for the same root
|
||||
# file. That is how Zeitwerk::Loader.for_gem is idempotent.
|
||||
#
|
||||
# @private
|
||||
# @sig (String) -> Zeitwerk::Loader
|
||||
def loader_for_gem(root_file, warn_on_extra_files:)
|
||||
gem_loaders_by_root_file[root_file] ||= GemLoader._new(root_file, warn_on_extra_files: warn_on_extra_files)
|
||||
end
|
||||
|
||||
# @private
|
||||
# @sig (Zeitwerk::Loader, String) -> String
|
||||
def register_autoload(loader, abspath)
|
||||
autoloads[abspath] = loader
|
||||
end
|
||||
|
||||
# @private
|
||||
# @sig (String) -> void
|
||||
def unregister_autoload(abspath)
|
||||
autoloads.delete(abspath)
|
||||
end
|
||||
|
||||
# @private
|
||||
# @sig (String, String, Zeitwerk::Loader) -> void
|
||||
def register_inception(cpath, abspath, loader)
|
||||
inceptions[cpath] = [abspath, loader]
|
||||
end
|
||||
|
||||
# @private
|
||||
# @sig (String) -> String?
|
||||
def inception?(cpath)
|
||||
if pair = inceptions[cpath]
|
||||
pair.first
|
||||
end
|
||||
end
|
||||
|
||||
# @private
|
||||
# @sig (String) -> Zeitwerk::Loader?
|
||||
def loader_for(path)
|
||||
autoloads[path]
|
||||
end
|
||||
|
||||
# @private
|
||||
# @sig (Zeitwerk::Loader) -> void
|
||||
def on_unload(loader)
|
||||
autoloads.delete_if { |_path, object| object == loader }
|
||||
inceptions.delete_if { |_cpath, (_path, object)| object == loader }
|
||||
end
|
||||
end
|
||||
|
||||
@loaders = []
|
||||
@gem_loaders_by_root_file = {}
|
||||
@autoloads = {}
|
||||
@inceptions = {}
|
||||
end
|
||||
end
|
||||
@ -1,5 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Zeitwerk
|
||||
VERSION = "2.6.7"
|
||||
end
|
||||
Loading…
x
Reference in New Issue
Block a user