code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
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
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:
find_minimum_transition
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/transitions_data_timezone_info.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/transitions_data_timezone_info.rb
MIT
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
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`.
transition_on_or_after_timestamp?
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/transitions_data_timezone_info.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/transitions_data_timezone_info.rb
MIT
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
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.
process_search_path
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_data_source.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_data_source.rb
MIT
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
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.
initialize
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_data_source.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_data_source.rb
MIT
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
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.
load_timezone_info
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_data_source.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_data_source.rb
MIT
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
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`.
validate_zoneinfo_dir
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_data_source.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_data_source.rb
MIT
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
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.
resolve_tab_path
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_data_source.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_data_source.rb
MIT
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
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`.
find_zoneinfo_dir
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_data_source.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_data_source.rb
MIT
def load_timezone_identifiers index = [] enum_timezones([], EXCLUDED_FILENAMES) do |identifier| index << identifier.join('/').freeze end index.sort! 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.
load_timezone_identifiers
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_data_source.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_data_source.rb
MIT
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
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.
enum_timezones
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_data_source.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_data_source.rb
MIT
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
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.
load_countries
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_data_source.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_data_source.rb
MIT
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
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`.
dms_to_rational
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_data_source.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_data_source.rb
MIT
def initialize(posix_tz_parser, string_deduper) @posix_tz_parser = posix_tz_parser @string_deduper = string_deduper end
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.
initialize
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_reader.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_reader.rb
MIT
def read(file_path) File.open(file_path, 'rb') { |file| parse(file) } 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.
read
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_reader.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_reader.rb
MIT
def make_signed_int32(long) long >= 0x80000000 ? long - 0x100000000 : long end
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.
make_signed_int32
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_reader.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_reader.rb
MIT
def make_signed_int64(high, low) unsigned = (high << 32) | low unsigned >= 0x8000000000000000 ? unsigned - 0x10000000000000000 : unsigned 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.
make_signed_int64
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_reader.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_reader.rb
MIT
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
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.
check_read
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_reader.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_reader.rb
MIT
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
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.
derive_offsets
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_reader.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_reader.rb
MIT
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
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.
offset_matches_rule?
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_reader.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_reader.rb
MIT
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
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.
apply_rules_without_transitions
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_reader.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_reader.rb
MIT
def find_existing_offset(offsets, offset) offsets.find {|o| o == offset } 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.
find_existing_offset
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_reader.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_reader.rb
MIT
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
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.
replace_with_existing_offsets
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_reader.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_reader.rb
MIT
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
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.
validate_and_fix_last_defined_transition_offset
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_reader.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_reader.rb
MIT
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
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.
apply_rules_with_transitions
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_reader.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_reader.rb
MIT
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
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.
parse
ruby
tzinfo/tzinfo
lib/tzinfo/data_sources/zoneinfo_reader.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_sources/zoneinfo_reader.rb
MIT
def countries @description_deduper = nil @countries.freeze end
@return [Hash<String, DataSources::CountryInfo>] a frozen `Hash` of all the countries that have been defined in the index keyed by their codes.
countries
ruby
tzinfo/tzinfo
lib/tzinfo/format1/country_index_definition.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format1/country_index_definition.rb
MIT
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
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.
country
ruby
tzinfo/tzinfo
lib/tzinfo/format1/country_index_definition.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format1/country_index_definition.rb
MIT
def offset(id, utc_offset, std_offset, abbreviation) super(id, utc_offset, std_offset, abbreviation.to_s) end
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.
offset
ruby
tzinfo/tzinfo
lib/tzinfo/format1/timezone_definer.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format1/timezone_definer.rb
MIT
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
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.
transition
ruby
tzinfo/tzinfo
lib/tzinfo/format1/timezone_definer.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format1/timezone_definer.rb
MIT
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 data time zones. Identifiers are sorted according to `String#<=>`.
data_timezones
ruby
tzinfo/tzinfo
lib/tzinfo/format1/timezone_index_definition.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format1/timezone_index_definition.rb
MIT
def linked_timezones unless @linked_timezones.frozen? @linked_timezones = @linked_timezones.sort.freeze end @linked_timezones end
@return [Array<String>] a frozen `Array` containing the identifiers of all linked time zones. Identifiers are sorted according to `String#<=>`.
linked_timezones
ruby
tzinfo/tzinfo
lib/tzinfo/format1/timezone_index_definition.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format1/timezone_index_definition.rb
MIT
def timezone(identifier) identifier = StringDeduper.global.dedupe(identifier) @timezones << identifier @data_timezones << identifier end
Adds a data time zone to the index. @param identifier [String] the time zone identifier.
timezone
ruby
tzinfo/tzinfo
lib/tzinfo/format1/timezone_index_definition.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format1/timezone_index_definition.rb
MIT
def linked_timezone(identifier) identifier = StringDeduper.global.dedupe(identifier) @timezones << identifier @linked_timezones << identifier end
Adds a linked time zone to the index. @param identifier [String] the time zone identifier.
linked_timezone
ruby
tzinfo/tzinfo
lib/tzinfo/format1/timezone_index_definition.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format1/timezone_index_definition.rb
MIT
def initialize(shared_timezones, identifier_deduper, description_deduper) @shared_timezones = shared_timezones @identifier_deduper = identifier_deduper @description_deduper = description_deduper @timezones = [] end
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.
initialize
ruby
tzinfo/tzinfo
lib/tzinfo/format2/country_definer.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format2/country_definer.rb
MIT
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
@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.
timezone
ruby
tzinfo/tzinfo
lib/tzinfo/format2/country_definer.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format2/country_definer.rb
MIT
def initialize(identifier_deduper, description_deduper) @identifier_deduper = identifier_deduper @description_deduper = description_deduper @shared_timezones = {} @countries = {} end
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.
initialize
ruby
tzinfo/tzinfo
lib/tzinfo/format2/country_index_definer.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format2/country_index_definer.rb
MIT
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 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.
timezone
ruby
tzinfo/tzinfo
lib/tzinfo/format2/country_index_definer.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format2/country_index_definer.rb
MIT
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
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.
country
ruby
tzinfo/tzinfo
lib/tzinfo/format2/country_index_definer.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format2/country_index_definer.rb
MIT
def country_index definer = CountryIndexDefiner.new(StringDeduper.global, StringDeduper.new) yield definer @countries = definer.countries.freeze end
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.
country_index
ruby
tzinfo/tzinfo
lib/tzinfo/format2/country_index_definition.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format2/country_index_definition.rb
MIT
def initialize(string_deduper) @string_deduper = string_deduper @offsets = {} @transitions = [] end
Initializes a new TimezoneDefiner. @param string_deduper [StringDeduper] a {StringDeduper} instance to use when deduping abbreviations.
initialize
ruby
tzinfo/tzinfo
lib/tzinfo/format2/timezone_definer.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format2/timezone_definer.rb
MIT
def first_offset first = @offsets.first first && first.last 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.
first_offset
ruby
tzinfo/tzinfo
lib/tzinfo/format2/timezone_definer.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format2/timezone_definer.rb
MIT
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 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.
offset
ruby
tzinfo/tzinfo
lib/tzinfo/format2/timezone_definer.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format2/timezone_definer.rb
MIT
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 [email protected]? && @transitions.last.timestamp_value >= timestamp_value @transitions << TimezoneTransition.new(offset, @previous_offset, timestamp_value) @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.
transition
ruby
tzinfo/tzinfo
lib/tzinfo/format2/timezone_definer.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format2/timezone_definer.rb
MIT
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 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}.
timezone
ruby
tzinfo/tzinfo
lib/tzinfo/format2/timezone_definition.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format2/timezone_definition.rb
MIT
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
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).
linked_timezone
ruby
tzinfo/tzinfo
lib/tzinfo/format2/timezone_definition.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format2/timezone_definition.rb
MIT
def initialize(string_deduper) @string_deduper = string_deduper @data_timezones = [] @linked_timezones = [] end
Initializes a new TimezoneDefiner. @param string_deduper [StringDeduper] a {StringDeduper} instance to use when deduping identifiers.
initialize
ruby
tzinfo/tzinfo
lib/tzinfo/format2/timezone_index_definer.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format2/timezone_index_definer.rb
MIT
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 data time zone to the index. @param identifier [String] the time zone identifier.
data_timezone
ruby
tzinfo/tzinfo
lib/tzinfo/format2/timezone_index_definer.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format2/timezone_index_definer.rb
MIT
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
Adds a linked time zone to the index. @param identifier [String] the time zone identifier.
linked_timezone
ruby
tzinfo/tzinfo
lib/tzinfo/format2/timezone_index_definer.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format2/timezone_index_definer.rb
MIT
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
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.
timezone_index
ruby
tzinfo/tzinfo
lib/tzinfo/format2/timezone_index_definition.rb
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/format2/timezone_index_definition.rb
MIT
def for_test(*args) t = Timestamp.for(*args) assert_kind_of(Timestamp, t) yield t block_called = 0 block_result = Timestamp.for(*args) do |t2| block_called += 1 assert_kind_of(Timestamp, t2) yield t2 t2 end assert_equal(1, block_called) expected_class = case args[0] when TestTimestampSubclass Timestamp when TestUtils::TimeLike Time else args[0].class end assert_kind_of(expected_class, block_result) end
Test Timestamp.for with and without a block.
for_test
ruby
tzinfo/tzinfo
test/tc_timestamp.rb
https://github.com/tzinfo/tzinfo/blob/master/test/tc_timestamp.rb
MIT
def time_types_test(*required_features, &block) self.class.time_types_helpers(*required_features, &block) end
Runs tests with each of the supported time representation types (DateTime, Time or Timestamp). Types can be restricted by requiring features (:distinct_utc, :unspecified_offset or :utc).
time_types_test
ruby
tzinfo/tzinfo
test/test_utils.rb
https://github.com/tzinfo/tzinfo/blob/master/test/test_utils.rb
MIT
def without_warnings old_verbose = $VERBOSE begin $VERBOSE = nil yield ensure $-v = old_verbose end end
Suppresses any warnings raised in a specified block.
without_warnings
ruby
tzinfo/tzinfo
test/test_utils.rb
https://github.com/tzinfo/tzinfo/blob/master/test/test_utils.rb
MIT
def safe_test(options = {}) # Ruby >= 2.7, JRuby, Rubinius and TruffleRuby don't support SAFE levels. available = RUBY_VERSION < '2.7' && !%w(jruby rbx truffleruby).include?(RUBY_ENGINE) if !available && options[:unavailable] == :skip skip('Ruby >= 2.7, JRuby, Rubinius and TruffleRuby don\'t support SAFE levels') end thread = Thread.new do orig_diff = Minitest::Assertions.diff if available orig_safe = $SAFE $SAFE = options[:level] || 1 end begin # Disable the use of external diff tools during safe mode tests (since # safe mode will prevent their use). The initial value is retrieved # before activating safe mode because the first time # Minitest::Assertions.diff is called, it will attempt to find a diff # tool. Finding the diff tool will also fail in safe mode. Minitest::Assertions.diff = nil begin yield ensure Minitest::Assertions.diff = orig_diff end ensure if available # On Ruby < 2.6, setting $SAFE affects only the current thread # and the $SAFE level cannot be downgraded. Catch and ignore the # SecurityError. # On Ruby >= 2.6, setting $SAFE is global, and the $SAFE level # can be downgraded. Restore $SAFE back to the original level. begin $SAFE = orig_safe rescue SecurityError end end end end thread.join end
Runs a test with safe mode enabled ($SAFE = 1).
safe_test
ruby
tzinfo/tzinfo
test/test_utils.rb
https://github.com/tzinfo/tzinfo/blob/master/test/test_utils.rb
MIT
def time_types_helpers(*required_features) [ TestUtils::TimeTypesTimeHelper, TestUtils::TimeTypesDateTimeHelper, TestUtils::TimeTypesTimestampHelper, TestUtils::TimeTypesTimeLikeHelper, TestUtils::TimeTypesTimeLikeWithOffsetHelper ].each do |helper_class| if required_features.all? {|f| helper_class.supports?(f) } yield helper_class.new end end end
Yields instances of the TimeTypesHelper subclasses. Types can be restricted by requiring features (:distinct_utc, :unspecified_offset or :utc).
time_types_helpers
ruby
tzinfo/tzinfo
test/test_utils.rb
https://github.com/tzinfo/tzinfo/blob/master/test/test_utils.rb
MIT
def test_encodings(*names) names.map {|n| TestEncoding.new(n) } end
Gets instances of TestEncoding for the given names.
test_encodings
ruby
tzinfo/tzinfo
test/test_utils.rb
https://github.com/tzinfo/tzinfo/blob/master/test/test_utils.rb
MIT
def assert_array_same_items(expected, actual, msg = nil) full_message = message(msg, '') { diff(expected, actual) } condition = (expected.size == actual.size) && (expected - actual == []) assert(condition, full_message) end
Assert that an array contains the same items independent of ordering.
assert_array_same_items
ruby
tzinfo/tzinfo
test/test_utils.rb
https://github.com/tzinfo/tzinfo/blob/master/test/test_utils.rb
MIT
def assert_sub_process_returns(expected_lines, code, load_path = [], required = ['tzinfo']) if RUBY_ENGINE == 'jruby' && JRUBY_VERSION.start_with?('9.0.') && RbConfig::CONFIG['host_os'] =~ /mswin/ skip('JRuby 9.0 on Windows cannot handle writing to the IO instance returned by popen') end ruby = File.join(RbConfig::CONFIG['bindir'], RbConfig::CONFIG['ruby_install_name'] + RbConfig::CONFIG['EXEEXT']) if RUBY_ENGINE == 'rbx' # Stop Rubinius from operating as irb. args = ' -' else args = '' end @@assert_sub_process_returns_count += 1 IO.popen("\"#{ruby}\"#{args} 2>&1", 'r+') do |process| load_path.each do |p| process.puts("$:.unshift('#{p.gsub("'", "\\\\'")}')") end if RUBY_ENGINE == 'rbx' # Bundler doesn't get set up automatically on Rubinius. process.puts("require 'bundler/setup'") end if COVERAGE_ENABLED && defined?(COVERAGE_TYPE) process.puts("require 'simplecov'") process.puts('SimpleCov.start do') process.puts(" command_name '#{COVERAGE_TYPE.gsub("'", "\\\\'")}:sp#{@@assert_sub_process_returns_count}'") process.puts(" add_filter 'test'") process.puts(" nocov_token '#{COVERAGE_NOCOV_TOKEN.gsub("'", "\\\\'")}'") process.puts(" project_name 'TZInfo'") process.puts(' self.formatters = []') process.puts('end') end required.each do |r| process.puts("require '#{r.gsub("'", "\\\\'")}'") end process.puts(code) process.flush process.close_write actual_lines = process.readlines actual_lines = actual_lines.collect(&:chomp) # Ignore warnings from RubyGems >= 3.1.0 that cause test failures with # JRuby 9.2.9.0: # https://travis-ci.org/tzinfo/tzinfo/jobs/628170481#L2437 # # Ignore warnings from JRuby 1.7 and 9.0 on modern versions of Java: # https://github.com/tzinfo/tzinfo/runs/1664655982#step:8:1893 # # Ignore untaint deprecation warnings from Bundler 1 on Ruby 3.0. # # Ignore method redefined warnings from concurrent-ruby on JRuby 9.4. # # Ignore warnings about default gem removals. actual_lines = actual_lines.reject do |l| l.start_with?('Gem::Specification#rubyforge_project= called from') || l.start_with?('NOTE: Gem::Specification#rubyforge_project= is deprecated with no replacement.') || l.end_with?('warning: constant Gem::ConfigMap is deprecated') || l.start_with?('unsupported Java version') || l.start_with?('WARNING: An illegal reflective access operation has occurred') || l.start_with?('WARNING: Illegal reflective access by') || l.start_with?('WARNING: Please consider reporting this to the maintainers of') || l.start_with?('WARNING: All illegal access operations will be denied in a future release') || l.start_with?('WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations') || l.start_with?('io/console on JRuby shells out to stty for most operations') || l =~ /\/bundler-1\..*\/lib\/bundler\/.*\.rb:\d+: warning: (Object|Pathname)#untaint is deprecated and will be removed in Ruby 3\.2\.\z/ || l =~ /\/lib\/concurrent-ruby\/concurrent\/executor\/java_thread_pool_executor\.rb:\d+: warning: method redefined; discarding old to_(f|int)\z/ || l =~ /warning: .* was loaded from the standard library, but (will no longer be|is not) part of the default gems starting from Ruby (\d+\.){3}\z/ || l =~ /\AYou can add .* to your Gemfile or gemspec to silence this warning\.\z/ end if RUBY_ENGINE == 'jruby' && ENV['_JAVA_OPTIONS'] && actual_lines.first == "Picked up _JAVA_OPTIONS: #{ENV['_JAVA_OPTIONS']}" actual_lines.shift end assert_equal(expected_lines, actual_lines) end end
Assert that starting a Ruby sub process to run code returns the output contained in the expected_lines array. Directories in load_path are added to the start of the load path before running requires. Each item in required is passed to require before running the specified code.
assert_sub_process_returns
ruby
tzinfo/tzinfo
test/test_utils.rb
https://github.com/tzinfo/tzinfo/blob/master/test/test_utils.rb
MIT
def assert_nothing_raised(msg = nil) begin yield rescue => e full_message = message(msg) { exception_details(e, 'Exception raised: ') } assert(false, full_message) end end
Asserts that a block does not raise an exception.
assert_nothing_raised
ruby
tzinfo/tzinfo
test/test_utils.rb
https://github.com/tzinfo/tzinfo/blob/master/test/test_utils.rb
MIT
def assert_nil_or_equal(expected, actual, msg = nil) if expected.nil? assert_nil(actual, msg) else assert_equal(expected, actual, msg) end end
If expected is nil, asserts that actual is nil, otherwise asserts that expected equals actual.
assert_nil_or_equal
ruby
tzinfo/tzinfo
test/test_utils.rb
https://github.com/tzinfo/tzinfo/blob/master/test/test_utils.rb
MIT
def assert_equal_with_offset(expected, actual) assert_kind_of(expected.class, actual) assert_equal(expected, actual) # Time, DateTime and Timestamp don't require identical offsets for equality. # Test the offsets explicitly. if expected.respond_to?(:utc_offset) assert_nil_or_equal(expected.utc_offset, actual.utc_offset, 'utc_offset') elsif expected.respond_to?(:offset) assert_nil_or_equal(expected.offset, actual.offset, 'offset') end # Time (on MRI and Rubinius, but not JRuby) and Timestamp distinguish between # UTC and a local time with 0 offset from UTC. if expected.respond_to?(:utc?) assert_nil_or_equal(expected.utc?, actual.utc?, 'utc?') end end
Asserts that Time, DateTime or Timestamp instances are equal and that their offsets are equal. The actual instance is allowed to be a subclass of the expected class.
assert_equal_with_offset
ruby
tzinfo/tzinfo
test/test_utils.rb
https://github.com/tzinfo/tzinfo/blob/master/test/test_utils.rb
MIT
def assert_equal_with_offset_and_timezone_offset(expected, actual) assert_equal_with_offset(expected, actual) assert_kind_of(TZInfo::TimezoneOffset, actual.timezone_offset) assert_equal(expected.timezone_offset, actual.timezone_offset) end
Asserts that TimeWithOffset, DateTimeWithOffset or TimestampWithOffset instances are equal and that their associated TimezoneOffsets are also equal.
assert_equal_with_offset_and_timezone_offset
ruby
tzinfo/tzinfo
test/test_utils.rb
https://github.com/tzinfo/tzinfo/blob/master/test/test_utils.rb
MIT
def assert_equal_with_offset_and_class(expected, actual) assert_equal_with_offset(expected, actual) assert_equal(expected.class, actual.class) end
Asserts that Time, DateTime or Timestamp instances are equal and that their classes are identical.
assert_equal_with_offset_and_class
ruby
tzinfo/tzinfo
test/test_utils.rb
https://github.com/tzinfo/tzinfo/blob/master/test/test_utils.rb
MIT
def test_to_s_no_tzinfo_data_version code = <<-EOF $:.unshift('#{TZINFO_TEST_DATA_DIR}') require 'tzinfo/data' TZInfo::Data.send(:remove_const, :VERSION) TZInfo::Data::Version.send(:remove_const, :STRING) ds = TZInfo::DataSources::RubyDataSource.new puts ds.to_s EOF assert_sub_process_returns(['Ruby DataSource: tzdb v2023c'], code) end
The TZInfo::Data::VERSION and TZInfo::Data::Version::STRING constants are only available from v1.2014.8 onwards.
test_to_s_no_tzinfo_data_version
ruby
tzinfo/tzinfo
test/data_sources/tc_ruby_data_source.rb
https://github.com/tzinfo/tzinfo/blob/master/test/data_sources/tc_ruby_data_source.rb
MIT
def require_libs(*libs) libs.each do |lib| require "#{lib_path}/#{lib}" end end
Internal: Requires internal Faraday libraries. @param *libs One or more relative String names to Faraday classes. @return [nil]
require_libs
ruby
WeAreFarmGeek/diplomat
lib/diplomat.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat.rb
BSD-3-Clause
def configure self.configuration ||= Diplomat::Configuration.new yield(configuration) end
Build optional configuration by yielding a block to configure @yield [Diplomat::Configuration]
configure
ruby
WeAreFarmGeek/diplomat
lib/diplomat.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat.rb
BSD-3-Clause
def method_missing(name, *args, &block) Diplomat::Kv.new.send(name, *args, &block) || super end
Send all other unknown commands to Diplomat::Kv @deprecated Please use Diplomat::Kv instead. @param name [Symbol] Method to send to Kv @param *args List of arguments to send to Kv @param &block block to send to Kv @return [Object]
method_missing
ruby
WeAreFarmGeek/diplomat
lib/diplomat.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat.rb
BSD-3-Clause
def respond_to_missing?(meth_id, with_private = false) access_method?(meth_id) || super end
Make `respond_to_missing?` fall back to super @param meth_id [Symbol] the tested method @oaram with_private if private methods should be tested too
respond_to_missing?
ruby
WeAreFarmGeek/diplomat
lib/diplomat.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat.rb
BSD-3-Clause
def info(id, options = {}, not_found = :reject, found = :return) @id = id @options = options custom_params = [] custom_params << use_consistency(options) raw = send_get_request(@conn_no_err, ["/v1/acl/info/#{id}"], options, custom_params) if raw.status == 200 && raw.body.chomp != 'null' case found when :reject raise Diplomat::AclAlreadyExists, id when :return @raw = raw return parse_body end elsif raw.status == 200 && raw.body.chomp == 'null' case not_found when :reject raise Diplomat::AclNotFound, id when :return return nil end else raise Diplomat::UnknownStatus, "status #{raw.status}: #{raw.body}" end end
Get Acl info by ID @param id [String] ID of the Acl to get @param options [Hash] options parameter hash @return [Hash] rubocop:disable Metrics/PerceivedComplexity
info
ruby
WeAreFarmGeek/diplomat
lib/diplomat/acl.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/acl.rb
BSD-3-Clause
def list(options = {}) @raw = send_get_request(@conn_no_err, ['/v1/acl/list'], options) parse_body end
rubocop:enable Metrics/PerceivedComplexity List all Acls @param options [Hash] options parameter hash @return [List] list of [Hash] of Acls
list
ruby
WeAreFarmGeek/diplomat
lib/diplomat/acl.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/acl.rb
BSD-3-Clause
def update(value, options = {}) raise Diplomat::IdParameterRequired unless value['ID'] || value[:ID] custom_params = use_cas(@options) @raw = send_put_request(@conn, ['/v1/acl/update'], options, value, custom_params) parse_body end
Update an Acl definition, create if not present @param value [Hash] Acl definition, ID field is mandatory @param options [Hash] options parameter hash @return [Hash] The result Acl
update
ruby
WeAreFarmGeek/diplomat
lib/diplomat/acl.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/acl.rb
BSD-3-Clause
def create(value, options = {}) custom_params = use_cas(@options) @raw = send_put_request(@conn, ['/v1/acl/create'], options, value, custom_params) parse_body end
Create an Acl definition @param value [Hash] Acl definition, ID field is mandatory @param options [Hash] options parameter hash @return [Hash] The result Acl
create
ruby
WeAreFarmGeek/diplomat
lib/diplomat/acl.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/acl.rb
BSD-3-Clause
def destroy(id, options = {}) @id = id @raw = send_put_request(@conn, ["/v1/acl/destroy/#{@id}"], options, nil) @raw.body.chomp == 'true' end
Destroy an ACl token by its id @param ID [String] the Acl ID @param options [Hash] options parameter hash @return [Bool] true if operation succeeded
destroy
ruby
WeAreFarmGeek/diplomat
lib/diplomat/acl.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/acl.rb
BSD-3-Clause
def checks(options = {}) ret = send_get_request(@conn, ['/v1/agent/checks'], options) JSON.parse(ret.body).tap { |node| OpenStruct.new node } end
Get local agent checks @param options [Hash] options parameter hash @return [OpenStruct] all agent checks
checks
ruby
WeAreFarmGeek/diplomat
lib/diplomat/agent.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/agent.rb
BSD-3-Clause
def services(options = {}) ret = send_get_request(@conn, ['/v1/agent/services'], options) JSON.parse(ret.body).tap { |node| OpenStruct.new node } end
Get local agent services @param options [Hash] options parameter hash @return [OpenStruct] all agent services
services
ruby
WeAreFarmGeek/diplomat
lib/diplomat/agent.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/agent.rb
BSD-3-Clause
def members(options = {}) ret = send_get_request(@conn, ['/v1/agent/members'], options) JSON.parse(ret.body).map { |node| OpenStruct.new node } end
Get cluster members (as seen by the agent) @param options [Hash] options parameter hash @return [OpenStruct] all members
members
ruby
WeAreFarmGeek/diplomat
lib/diplomat/agent.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/agent.rb
BSD-3-Clause
def get_configuration(options = {}) custom_params = [] custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] ret = send_get_request(@conn, ['/v1/operator/autopilot/configuration'], options, custom_params) JSON.parse(ret.body) end
Get autopilot configuration @param options [Hash] options parameter hash @return [OpenStruct] all data associated with the autopilot configuration
get_configuration
ruby
WeAreFarmGeek/diplomat
lib/diplomat/autopilot.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/autopilot.rb
BSD-3-Clause
def get_health(options = {}) custom_params = [] custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] ret = send_get_request(@conn, ['/v1/operator/autopilot/health'], options, custom_params) JSON.parse(ret.body) end
Get health status from the autopilot @param options [Hash] options parameter hash @return [OpenStruct] all data associated with the health of the autopilot
get_health
ruby
WeAreFarmGeek/diplomat
lib/diplomat/autopilot.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/autopilot.rb
BSD-3-Clause
def checks(options = {}) ret = send_get_request(@conn, ['/v1/agent/checks'], options) JSON.parse(ret.body) end
Get registered checks @return [OpenStruct] all data associated with the service
checks
ruby
WeAreFarmGeek/diplomat
lib/diplomat/check.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/check.rb
BSD-3-Clause
def register_script(check_id, name, notes, args, interval, options = {}) unless args.is_a?(Array) raise(Diplomat::DeprecatedArgument, 'Script usage is deprecated, replace by an array of args') end definition = JSON.generate( 'ID' => check_id, 'Name' => name, 'Notes' => notes, 'Args' => args, 'Interval' => interval ) ret = send_put_request(@conn, ['/v1/agent/check/register'], options, definition) ret.status == 200 end
Register a check @param check_id [String] the unique id of the check @param name [String] the name @param notes [String] notes about the check @param args [String[]] command to be run for check @param interval [String] frequency (with units) of the check execution @param options [Hash] options parameter hash @return [Integer] Status code rubocop:disable Metrics/ParameterLists
register_script
ruby
WeAreFarmGeek/diplomat
lib/diplomat/check.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/check.rb
BSD-3-Clause
def register_ttl(check_id, name, notes, ttl, options = {}) definition = JSON.generate( 'ID' => check_id, 'Name' => name, 'Notes' => notes, 'TTL' => ttl ) ret = send_put_request(@conn, ['/v1/agent/check/register'], options, definition) ret.status == 200 end
rubocop:enable Metrics/ParameterLists Register a TTL check @param check_id [String] the unique id of the check @param name [String] the name @param notes [String] notes about the check @param ttl [String] time (with units) to mark a check down @param options [Hash] options parameter hash @return [Boolean] Success
register_ttl
ruby
WeAreFarmGeek/diplomat
lib/diplomat/check.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/check.rb
BSD-3-Clause
def deregister(check_id, options = {}) ret = send_put_request(@conn, ["/v1/agent/check/deregister/#{check_id}"], options, nil) ret.status == 200 end
Deregister a check @param check_id [String] the unique id of the check @param options [Hash] options parameter hash @return [Integer] Status code
deregister
ruby
WeAreFarmGeek/diplomat
lib/diplomat/check.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/check.rb
BSD-3-Clause
def update_ttl(check_id, status, output = nil, options = {}) definition = JSON.generate( 'Status' => status, 'Output' => output ) ret = send_put_request(@conn, ["/v1/agent/check/update/#{check_id}"], options, definition) ret.status == 200 end
Update a TTL check @param check_id [String] the unique id of the check @param status [String] status of the check. Valid values are "passing", "warning", and "critical" @param output [String] human-readable message will be passed through to the check's Output field @param options [Hash] options parameter hash @return [Integer] Status code
update_ttl
ruby
WeAreFarmGeek/diplomat
lib/diplomat/check.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/check.rb
BSD-3-Clause
def pass(check_id, output = nil, options = {}) update_ttl(check_id, 'passing', output, options) end
Pass a check @param check_id [String] the unique id of the check @param output [String] human-readable message will be passed through to the check's Output field @param options [Hash] options parameter hash @return [Integer] Status code
pass
ruby
WeAreFarmGeek/diplomat
lib/diplomat/check.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/check.rb
BSD-3-Clause
def warn(check_id, output = nil, options = {}) update_ttl(check_id, 'warning', output, options) end
Warn a check @param check_id [String] the unique id of the check @param output [String] human-readable message will be passed through to the check's Output field @param options [Hash] options parameter hash @return [Integer] Status code
warn
ruby
WeAreFarmGeek/diplomat
lib/diplomat/check.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/check.rb
BSD-3-Clause
def fail(check_id, output = nil, options = {}) update_ttl(check_id, 'critical', output, options) end
Fail a check @param check_id [String] the unique id of the check @param output [String] human-readable message will be passed through to the check's Output field @param options [Hash] options parameter hash @return [Integer] Status code
fail
ruby
WeAreFarmGeek/diplomat
lib/diplomat/check.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/check.rb
BSD-3-Clause
def initialize(url = Configuration.parse_consul_addr, acl_token = ENV['CONSUL_HTTP_TOKEN'], options = {}) @middleware = [] @url = url @acl_token = acl_token @options = options end
Override defaults for configuration @param url [String] consul's connection URL @param acl_token [String] a connection token used when making requests to consul @param options [Hash] extra options to configure Faraday::Connection
initialize
ruby
WeAreFarmGeek/diplomat
lib/diplomat/configuration.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/configuration.rb
BSD-3-Clause
def get(meta = nil, options = {}) ret = send_get_request(@conn, ['/v1/catalog/datacenters'], options) if meta && ret.headers meta[:index] = ret.headers['x-consul-index'] if ret.headers['x-consul-index'] meta[:knownleader] = ret.headers['x-consul-knownleader'] if ret.headers['x-consul-knownleader'] meta[:lastcontact] = ret.headers['x-consul-lastcontact'] if ret.headers['x-consul-lastcontact'] end JSON.parse(ret.body) end
Get an array of all avaliable datacenters accessible by the local consul agent @param meta [Hash] output structure containing header information about the request (index) @param options [Hash] options parameter hash @return [OpenStruct] all datacenters avaliable to this consul agent
get
ruby
WeAreFarmGeek/diplomat
lib/diplomat/datacenter.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/datacenter.rb
BSD-3-Clause
def fire(name, value = nil, service = nil, node = nil, tag = nil, dc = nil, options = {}) custom_params = [] custom_params << use_named_parameter('service', service) if service custom_params << use_named_parameter('node', node) if node custom_params << use_named_parameter('tag', tag) if tag custom_params << use_named_parameter('dc', dc) if dc send_put_request(@conn, ["/v1/event/fire/#{name}"], options, value, custom_params) nil end
Send an event @param name [String] the event name @param value [String] the payload of the event @param service [String] the target service name @param node [String] the target node name @param tag [String] the target tag name, must only be used with service @param dc [String] the dc to target @param options [Hash] options parameter hash @return [nil] rubocop:disable Metrics/ParameterLists
fire
ruby
WeAreFarmGeek/diplomat
lib/diplomat/event.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/event.rb
BSD-3-Clause
def get_all(name = nil, not_found = :reject, found = :return, options = {}) # Event list never returns 404 or blocks, but may return an empty list @raw = send_get_request(@conn, ['/v1/event/list'], options, use_named_parameter('name', name)) if JSON.parse(@raw.body).count.zero? case not_found when :reject raise Diplomat::EventNotFound, name when :return return [] end else case found when :reject raise Diplomat::EventAlreadyExists, name when :return @raw = parse_body return return_payload end end @raw = wait_for_next_event(['/v1/event/list'], options, use_named_parameter('name', name)) @raw = parse_body return_payload end
rubocop:enable Metrics/ParameterLists Get the list of events matching name @param name [String] the name of the event (regex) @param not_found [Symbol] behaviour if there are no events matching name; :reject with exception, :return degenerate value, or :wait for a non-empty list @param found [Symbol] behaviour if there are already events matching name; :reject with exception, :return its current value, or :wait for its next value @return [Array[hash]] The list of { :name, :payload } hashes @param options [Hash] options parameter hash @note Events are sent via the gossip protocol; there is no guarantee of delivery success or order, but the local agent will store up to 256 events that do arrive. This method lists those events. It has the same semantics as Kv::get, except the value returned is a list i.e. the current value is all events up until now, the next value is the current list plus the next event to arrive. To get a specific event in the sequence, @see #get When trying to get a list of events matching a name, there are two possibilities: - The list doesn't (yet) exist / is empty - The list exists / is non-empty The combination of not_found and found behaviour gives maximum possible flexibility. For X: reject, R: return, W: wait - X X - meaningless; never return a value - X R - "normal" non-blocking get operation. Default - X W - get the next value only (must have a current value) - R X - meaningless; never return a meaningful value - R R - "safe" non-blocking, non-throwing get-or-default operation - R W - get the next value or a default - W X - get the first value only (must not have a current value) - W R - get the first or current value; always return something, but block only when necessary - W W - get the first or next value; wait until there is an update
get_all
ruby
WeAreFarmGeek/diplomat
lib/diplomat/event.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/event.rb
BSD-3-Clause
def get(name = nil, token = :last, not_found = :wait, found = :return, options = {}) @raw = send_get_request(@conn, ['/v1/event/list'], options, use_named_parameter('name', name)) body = JSON.parse(@raw.body) # TODO: deal with unknown symbols, invalid indices (find_index will return nil) idx = case token when :first then 0 when :last then body.length - 1 when :next then body.length else body.find_index { |e| e['ID'] == token } + 1 end if JSON.parse(@raw.body).count.zero? || idx == body.length case not_found when :reject raise Diplomat::EventNotFound, name when :return event_name = '' event_payload = '' event_token = :last when :wait @raw = wait_for_next_event(['/v1/event/list'], options, use_named_parameter('name', name)) @raw = parse_body # If it's possible for two events to arrive at once, # this needs to #find again: event = @raw.last event_name = event['Name'] event_payload = Base64.decode64(event['Payload']) event_token = event['ID'] end else case found when :reject raise Diplomat::EventAlreadyExits, name when :return event = body[idx] event_name = event['Name'] event_payload = event['Payload'].nil? ? nil : Base64.decode64(event['Payload']) event_token = event['ID'] end end { value: { name: event_name, payload: event_payload }, token: event_token } end
Get a specific event in the sequence matching name @param name [String] the name of the event (regex) @param token [String|Symbol] the ordinate of the event in the sequence; String are tokens returned by previous calls to this function Symbols are the special tokens :first, :last, and :next @param not_found [Symbol] behaviour if there is no matching event; :reject with exception, :return degenerate value, or :wait for event @param found [Symbol] behaviour if there is a matching event; :reject with exception, or :return its current value @return [hash] A hash with keys :value and :token; :value is a further hash of the :name and :payload of the event, :token is the event's ordinate in the sequence and can be passed to future calls to get the subsequent event @param options [Hash] options parameter hash @note Whereas the consul API for events returns all past events that match name, this method allows retrieval of individual events from that sequence. However, because consul's API isn't conducive to this, we can offer first, last, next (last + 1) events, or arbitrary events in the middle, though these can only be identified relative to the preceding event. However, this is ideal for iterating through the sequence of events (while being sure that none are missed). rubocop:disable Metrics/PerceivedComplexity
get
ruby
WeAreFarmGeek/diplomat
lib/diplomat/event.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/event.rb
BSD-3-Clause
def node(n, options = {}) custom_params = [] custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] custom_params << use_named_parameter('filter', options[:filter]) if options[:filter] ret = send_get_request(@conn, ["/v1/health/node/#{n}"], options, custom_params) JSON.parse(ret.body).map { |node| OpenStruct.new node } end
Get node health @param n [String] the node @param options [Hash] :dc, :filter string for specific query @return [OpenStruct] all data associated with the node
node
ruby
WeAreFarmGeek/diplomat
lib/diplomat/health.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/health.rb
BSD-3-Clause
def checks(s, options = {}) custom_params = [] custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] custom_params << use_named_parameter('filter', options[:filter]) if options[:filter] ret = send_get_request(@conn, ["/v1/health/checks/#{s}"], options, custom_params) JSON.parse(ret.body).map { |check| OpenStruct.new check } end
Get service checks @param s [String] the service @param options [Hash] :dc, :filter string for specific query @return [OpenStruct] all data associated with the node
checks
ruby
WeAreFarmGeek/diplomat
lib/diplomat/health.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/health.rb
BSD-3-Clause
def service(s, options = {}, meta = nil) custom_params = [] custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] custom_params << ['passing'] if options[:passing] custom_params += [*options[:tag]].map { |value| use_named_parameter('tag', value) } if options[:tag] custom_params << use_named_parameter('near', options[:near]) if options[:near] custom_params << use_named_parameter('node-meta', options[:node_meta]) if options[:node_meta] custom_params << use_named_parameter('index', options[:index]) if options[:index] custom_params << use_named_parameter('filter', options[:filter]) if options[:filter] ret = send_get_request(@conn, ["/v1/health/service/#{s}"], options, custom_params) if meta && ret.headers meta[:index] = ret.headers['x-consul-index'] if ret.headers['x-consul-index'] meta[:knownleader] = ret.headers['x-consul-knownleader'] if ret.headers['x-consul-knownleader'] meta[:lastcontact] = ret.headers['x-consul-lastcontact'] if ret.headers['x-consul-lastcontact'] end JSON.parse(ret.body).map { |service| OpenStruct.new service } end
Get service health @param s [String] the service @param options [Hash] options parameter hash @param meta [Hash] output structure containing header information about the request (index) @return [OpenStruct] all data associated with the node rubocop:disable Metrics/PerceivedComplexity
service
ruby
WeAreFarmGeek/diplomat
lib/diplomat/health.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/health.rb
BSD-3-Clause
def state(s, options = {}) custom_params = [] custom_params << use_named_parameter('dc', options[:dc]) if options[:dc] custom_params << use_named_parameter('near', options[:near]) if options[:near] custom_params << use_named_parameter('filter', options[:filter]) if options[:filter] ret = send_get_request(@conn, ["/v1/health/state/#{s}"], options, custom_params) JSON.parse(ret.body).map { |status| OpenStruct.new status } end
rubocop:enable Metrics/PerceivedComplexity Get service health @param s [String] the state ("any", "passing", "warning", or "critical") @param options [Hash] :dc, :near, :filter string for specific query @return [OpenStruct] all data associated with the node
state
ruby
WeAreFarmGeek/diplomat
lib/diplomat/health.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/health.rb
BSD-3-Clause
def any(options = {}) state('any', options) end
Convenience method to get services in any state @param options [Hash] :dc, :near, :filter string for specific query @return [OpenStruct] all data associated with the node
any
ruby
WeAreFarmGeek/diplomat
lib/diplomat/health.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/health.rb
BSD-3-Clause
def passing(options = {}) state('passing', options) end
Convenience method to get services in passing state @param options [Hash] :dc, :near, :filter string for specific query @return [OpenStruct] all data associated with the node
passing
ruby
WeAreFarmGeek/diplomat
lib/diplomat/health.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/health.rb
BSD-3-Clause
def warning(options = {}) state('warning', options) end
Convenience method to get services in warning state @param options [Hash] :dc, :near, :filter string for specific query @return [OpenStruct] all data associated with the node
warning
ruby
WeAreFarmGeek/diplomat
lib/diplomat/health.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/health.rb
BSD-3-Clause
def critical(options = {}) state('critical', options) end
Convenience method to get services in critical state @param options [Hash] :dc, :near, :filter string for specific query @return [OpenStruct] all data associated with the node
critical
ruby
WeAreFarmGeek/diplomat
lib/diplomat/health.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/health.rb
BSD-3-Clause
def get(key, options = {}, not_found = :reject, found = :return) @options = options return_nil_values = @options && @options[:nil_values] transformation = @options && @options[:transformation] && @options[:transformation].methods.find_index(:call) ? @options[:transformation] : nil raw = get_raw(key, options) if raw.status == 404 case not_found when :reject raise Diplomat::KeyNotFound, key when :return return @value = '' when :wait index = raw.headers['x-consul-index'] end elsif raw.status == 200 case found when :reject raise Diplomat::KeyAlreadyExists, key when :return @raw = raw @raw = parse_body return @raw.first['ModifyIndex'] if @options && @options[:modify_index] return @raw.first['Session'] if @options && @options[:session] return decode_values if @options && @options[:decode_values] return convert_to_hash(return_value(return_nil_values, transformation, true)) if @options && @options[:convert_to_hash] return return_value(return_nil_values, transformation) when :wait index = raw.headers['x-consul-index'] end else raise Diplomat::UnknownStatus, "status #{raw.status}: #{raw.body}" end # Wait for first/next value @raw = wait_for_value(index, options) @raw = parse_body return_value(return_nil_values, transformation) end
Get a value by its key, potentially blocking for the first or next value @param key [String] the key @param options [Hash] the query params @option options [Boolean] :recurse If to make recursive get or not @option options [String] :consistency The read consistency type @option options [String] :dc Target datacenter @option options [Boolean] :keys Only return key names. @option options [Boolean] :modify_index Only return ModifyIndex value. @option options [Boolean] :session Only return Session value. @option options [Boolean] :decode_values Return consul response with decoded values. @option options [String] :separator List only up to a given separator. Only applies when combined with :keys option. @option options [Boolean] :nil_values If to return keys/dirs with nil values @option options [Boolean] :convert_to_hash Take the data returned from consul and build a hash @option options [Callable] :transformation function to invoke on keys values @param not_found [Symbol] behaviour if the key doesn't exist; :reject with exception, :return degenerate value, or :wait for it to appear @param found [Symbol] behaviour if the key does exist; :reject with exception, :return its current value, or :wait for its next value @return [String] The base64-decoded value associated with the key @note When trying to access a key, there are two possibilites: - The key doesn't (yet) exist - The key exists. This may be its first value, there is no way to tell The combination of not_found and found behaviour gives maximum possible flexibility. For X: reject, R: return, W: wait - X X - meaningless; never return a value - X R - "normal" non-blocking get operation. Default - X W - get the next value only (must have a current value) - R X - meaningless; never return a meaningful value - R R - "safe" non-blocking, non-throwing get-or-default operation - R W - get the next value or a default - W X - get the first value only (must not have a current value) - W R - get the first or current value; always return something, but block only when necessary - W W - get the first or next value; wait until there is an update rubocop:disable Metrics/PerceivedComplexity, Metrics/MethodLength, Layout/LineLength, Metrics/CyclomaticComplexity
get
ruby
WeAreFarmGeek/diplomat
lib/diplomat/kv.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/kv.rb
BSD-3-Clause
def get_all(key, options = {}, not_found = :reject, found = :return) @options = options @options[:recurse] = true return_nil_values = @options && @options[:nil_values] transformation = @options && @options[:transformation] && @options[:transformation].methods.find_index(:call) ? @options[:transformation] : nil raw = get_raw(key, options) if raw.status == 404 case not_found when :reject raise Diplomat::KeyNotFound, key when :return return @value = [] when :wait index = raw.headers['x-consul-index'] end elsif raw.status == 200 case found when :reject raise Diplomat::KeyAlreadyExists, key when :return @raw = raw @raw = parse_body return decode_values if @options && @options[:decode_values] return convert_to_hash(return_value(return_nil_values, transformation, true)) if @options && @options[:convert_to_hash] return return_value(return_nil_values, transformation, true) when :wait index = raw.headers['x-consul-index'] end else raise Diplomat::UnknownStatus, "status #{raw.status}: #{raw.body}" end # Wait for first/next value @raw = wait_for_value(index, options) @raw = parse_body return_value(return_nil_values, transformation, true) end
rubocop:enable Metrics/PerceivedComplexity, Layout/LineLength, Metrics/MethodLength, Metrics/CyclomaticComplexity Get all keys recursively, potentially blocking for the first or next value @param key [String] the key @param options [Hash] the query params @option options [String] :consistency The read consistency type @option options [String] :dc Target datacenter @option options [Boolean] :keys Only return key names. @option options [Boolean] :decode_values Return consul response with decoded values. @option options [String] :separator List only up to a given separator. Only applies when combined with :keys option. @option options [Boolean] :nil_values If to return keys/dirs with nil values @option options [Boolean] :convert_to_hash Take the data returned from consul and build a hash @option options [Callable] :transformation function to invoke on keys values @param not_found [Symbol] behaviour if the key doesn't exist; :reject with exception, :return degenerate value, or :wait for it to appear @param found [Symbol] behaviour if the key does exist; :reject with exception, :return its current value, or :wait for its next value @return [List] List of hashes, one hash for each key-value returned rubocop:disable Metrics/PerceivedComplexity, Metrics/MethodLength, Layout/LineLength, Metrics/CyclomaticComplexity
get_all
ruby
WeAreFarmGeek/diplomat
lib/diplomat/kv.rb
https://github.com/WeAreFarmGeek/diplomat/blob/master/lib/diplomat/kv.rb
BSD-3-Clause