Module: Lich::Util
- Includes:
- Enumerable
- Defined in:
- documented/util/deep_freeze.rb,
documented/update.rb,
documented/util/opts.rb,
documented/util/util.rb,
documented/magic-info.rb,
documented/util/textstripper.rb,
documented/util/gtk_compaction.rb,
documented/util/memoryreleaser.rb,
documented/common/update/file_writer.rb,
documented/common/update/script_sync.rb,
documented/common/update/custom_repos.rb,
documented/common/update/file_updater.rb,
documented/common/update/github_client.rb,
documented/common/update/status_reporter.rb,
documented/common/update/tracked_scripts.rb,
documented/common/update/branch_installer.rb,
documented/common/update/channel_resolver.rb,
documented/common/update/snapshot_manager.rb,
documented/common/update/release_installer.rb
Overview
Namespace for Lich utility modules and classes.
Defined Under Namespace
Modules: GtkCompaction, Magicinfo, MemoryReleaser, TextStripper, Update Classes: Opts
Constant Summary collapse
- QUIET_STATE_TAGS =
Self-closing tags that toggle persistent client display state (as opposed to e.g.
, which self-heals on the next prompt). The raw server chunk handed to a DownstreamHook proc is not split on line boundaries, so the server is free to bundle one of these onto the same chunk as text that quiet: true is about to drop. Silently discarding that chunk would discard the tag with it -- e.g. dropping a trailing mono-closing that rode in on the same chunk as the a quiet-filtered range ends on leaves the frontend stuck in mono mode until an unrelated, later mono tag happens to close it. Only the mono/formatting
[ /<output class="[^"]*"\s*\/>/ # mono/formatting state toggle ].freeze
- QUIET_STATE_TAG_PATTERN =
Combines QUIET_STATE_TAGS into a single alternation, scanned once per chunk. Scanning each pattern separately and concatenating the results (the original approach) groups matches by pattern rather than by where they actually appear -- invisible with a single pattern, but as soon as a second entry is added, two tags from different patterns on the same chunk would come back in pattern order instead of source order, which matters when the tags are an open/close pair. A single combined scan preserves the chunk's real left-to-right order regardless of how many patterns are registered.
Regexp.union(QUIET_STATE_TAGS).freeze
Class Method Summary collapse
-
.anon_hook(prefix = '') ⇒ String
Generates a unique anonymous hook identifier string.
-
.deep_freeze(value) ⇒ Object
Recursively freezes Arrays, Hashes, and their nested contents.
-
.install_gem_requirements(gems_to_install, user_install: false) ⇒ Object
Installs and optionally requires a set of Ruby gems specified in a Hash.
-
.issue_command(command, start_pattern, end_pattern = /<prompt/, include_end: true, timeout: 5, silent: nil, usexml: true, quiet: false, use_fput: true) ⇒ Array<String>
Issues a command to the game and captures output between start and end patterns.
-
.normalize_lookup(effect, val) ⇒ Boolean
Normalizes and performs a lookup for an effect based on the provided value.
-
.normalize_name(name) ⇒ String
Normalizes a given name by converting it to a lowercase string and replacing or removing certain characters.
-
.preserve_quiet_state_tags(chunk) ⇒ String?
Pulls any QUIET_STATE_TAGS matches out of a chunk that quiet: true is about to drop, so callers can forward just the tags instead of the whole chunk.
-
.quiet_command(command, start_pattern, end_pattern, include_end = true, timeout = 5, silent = true) ⇒ Array<String>
Executes a game command and captures output between start and end patterns, suppressing output to the front-end.
-
.quiet_command_xml(command, start_pattern, end_pattern = /<prompt/, include_end = true, timeout = 5, silent = true) ⇒ Array<String>
Executes a game command and captures output between start and end patterns, suppressing output to the front-end.
-
.silver_count(timeout = 3) ⇒ Integer
Retrieves the current silver count from the game output by issuing the 'info' command and parsing the response.
Class Method Details
.anon_hook(prefix = '') ⇒ String
Generates a unique anonymous hook identifier string.
74 75 76 77 |
# File 'documented/util/util.rb', line 74 def self.anon_hook(prefix = '') now = Time.now "Util::#{prefix}-#{now}-#{Random.rand(10000)}" end |
.deep_freeze(value) ⇒ Object
Recursively freezes Arrays, Hashes, and their nested contents.
11 12 13 |
# File 'documented/util/deep_freeze.rb', line 11 def self.deep_freeze(value) deep_freeze_value(value, {}.compare_by_identity) end |
.install_gem_requirements(gems_to_install, user_install: false) ⇒ Object
Installs and optionally requires a set of Ruby gems specified in a Hash.
This method will attempt to install any gems that are not already installed. If a gem is installed and its value is true, it will be required. If installation fails for any gem, an error will be raised listing all failed gems.
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 |
# File 'documented/util/util.rb', line 342 def self.install_gem_requirements(gems_to_install, user_install: false) raise ArgumentError, "install_gem_requirements must be passed a Hash" unless gems_to_install.is_a?(Hash) require "rubygems" require "rubygems/dependency_installer" installer = Gem::DependencyInstaller.new({ :user_install => user_install, :document => nil }) installed_gems = Gem::Specification.map { |gem| gem.name }.sort.uniq failed_gems = [] gems_to_install.each do |gem_name, should_require| unless gem_name.is_a?(String) && (should_require.is_a?(TrueClass) || should_require.is_a?(FalseClass)) raise ArgumentError, "install_gem_requirements must be passed a Hash with String key and TrueClass/FalseClass as value" end begin unless installed_gems.include?(gem_name) respond("--- Lich: Installing missing ruby gem '#{gem_name}' now, please wait!") if defined?(Script) Lich.log("--- Lich: Installing missing ruby gem '#{gem_name}' now, please wait!") result = installer.install(gem_name) Gem.clear_paths Gem::Specification.reset Gem::Specification.find_by_name(gem_name).activate Lich.log("RubyGem Installer Result: #{result.inspect}") unless Gem::Specification.map { |gem| gem.name }.sort.uniq.include?(gem_name) Lich.log("RubyGems failed, attempting system method instead!") result = system(File.join(RbConfig::CONFIG['bindir'], 'gem'), 'install', gem_name) Lich.log("SYSTEM Call Result: #{result.inspect}") Gem.clear_paths Gem::Specification.reset Gem::Specification.find_by_name(gem_name).activate end respond("--- Lich: Done installing '#{gem_name}' gem!") if defined?(Script) Lich.log("--- Lich: Done installing '#{gem_name}' gem!") end require gem_name if should_require rescue LoadError, StandardError respond("--- Lich: error: Failed to install/require Ruby gem: #{gem_name}") if defined?(Script) respond("--- Lich: error: #{$!}") if defined?(Script) Lich.log("installed_gems.include?(#{gem_name}): #{installed_gems.include?(gem_name)} - #{installed_gems.find_all { |gem| gem == gem_name }.inspect}") Lich.log("error: Failed to install/require Ruby gem: #{gem_name}") Lich.log("error: #{$!}") failed_gems.push(gem_name) end end unless failed_gems.empty? if defined?(Script.current.name) && Script.current.name != "unknown" raise("Please install the failed gems: #{failed_gems.join(', ')} manually to run #{$lich_char}#{Script.current.name}") else raise("Please install the failed gems: #{failed_gems.join(', ')} manually to continue.") end end end |
.issue_command(command, start_pattern, end_pattern = /<prompt/, include_end: true, timeout: 5, silent: nil, usexml: true, quiet: false, use_fput: true) ⇒ Array<String>
Issues a command to the game and captures output between start and end patterns.
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 |
# File 'documented/util/util.rb', line 156 def self.issue_command(command, start_pattern, end_pattern = /<prompt/, include_end: true, timeout: 5, silent: nil, usexml: true, quiet: false, use_fput: true) result = [] name = self.anon_hook filter = false ignore_end = end_pattern.eql?(:ignore) save_script_silent = Script.current.silent save_want_downstream = Script.current.want_downstream save_want_downstream_xml = Script.current.want_downstream_xml Script.current.silent = silent if !silent.nil? Script.current.want_downstream = !usexml Script.current.want_downstream_xml = usexml begin Timeout::timeout(timeout, Interrupt) { DownstreamHook.add(name, proc { |line| if filter if ignore_end || line =~ end_pattern DownstreamHook.remove(name) filter = false if quiet && !ignore_end next((line)) else line end else if quiet next((line)) else line end end elsif line =~ start_pattern filter = true if quiet next((line)) else line end else line end }, persist: false) # scoped to this command; removed in the ensure below use_fput ? fput(command) : put(command) until (line = get) =~ start_pattern; end result << line.rstrip unless ignore_end until (line = get) =~ end_pattern result << line.rstrip end end unless ignore_end if include_end result << line.rstrip end end } rescue Interrupt nil ensure DownstreamHook.remove(name) Script.current.silent = save_script_silent if !silent.nil? Script.current.want_downstream = save_want_downstream Script.current.want_downstream_xml = save_want_downstream_xml end return result end |
.normalize_lookup(effect, val) ⇒ Boolean
Normalizes and performs a lookup for an effect based on the provided value.
Depending on the type of val, this method will:
- For String: Check if the normalized string matches any key in the effect's hash (case-insensitive, underscores/colons replaced with spaces).
- For Integer: Check if the effect is active for the given integer value.
- For Symbol: Check if the normalized symbol matches any key in the effect's hash (case-insensitive, underscores/colons replaced with spaces).
Both the lookup value and the effect's hash keys are normalized the same way, so a punctuation-free lookup (e.g. PSM feat names like "covert_art_escape_artist") still matches an effect key that contains punctuation (e.g. "Covert Art: Escape Artist").
27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'documented/util/util.rb', line 27 def self.normalize_lookup(effect, val) caller_type = "Effects::#{effect}" case val when String, Symbol normalize = ->(str) { str.to_s.downcase.gsub(':', ' ').gsub('_', ' ').squeeze(' ').strip } (eval caller_type).to_h.transform_keys { |k| normalize.call(k) }.include?(normalize.call(val)) when Integer # seek = mappings.fetch(val, nil) (eval caller_type).active?(val) else fail "invalid lookup case #{val.class.name}" end end |
.normalize_name(name) ⇒ String
Normalizes a given name by converting it to a lowercase string and replacing or removing certain characters.
The normalization process handles the following cases:
- Converts spaces and hyphens to underscores.
- Removes colons and apostrophes.
- Converts symbols to strings.
- Converts all characters to lowercase.
Examples:
normalize_name("vault_kick") #=> "vault_kick"
normalize_name("vault kick") #=> "vault_kick"
normalize_name("vault-kick") #=> "vault_kick"
normalize_name(:vault_kick) #=> "vault_kick"
normalize_name(:vaultkick) #=> "vaultkick"
normalize_name("predator's eye") #=> "predators_eye"
59 60 61 62 63 64 65 66 |
# File 'documented/util/util.rb', line 59 def self.normalize_name(name) normal_name = name.to_s.downcase normal_name.gsub!(' ', '_') if name =~ (/\s/) normal_name.gsub!('-', '_') if name =~ (/-/) normal_name.gsub!(":", '') if name =~ (/:/) normal_name.gsub!("'", '') if name =~ (/'/) normal_name end |
.preserve_quiet_state_tags(chunk) ⇒ String?
Pulls any QUIET_STATE_TAGS matches out of a chunk that quiet: true is about to drop, so callers can forward just the tags instead of the whole chunk.
The returned string is newline-terminated even though the matched tags themselves never include one. Every other chunk that reaches this pipeline is newline/CRLF-terminated as part of the game server's line-oriented stream framing; a bare, unterminated tag is not a shape of line this pipeline produced before this method existed. For sentinel-supporting frontends (currently only Saga -- see Frontend::ORIGIN_SENTINEL and Game#prefix_origin_sentinel), every forwarded line gets a leading origin-marker byte that the client is expected to consume as routing metadata and strip before display. That worked here once the segment was given the same line termination as everything else the client already handles; without it, the client had nothing to delimit an otherwise content-only segment, and the marker byte fell through to the display as a literal, visible character.
137 138 139 140 141 142 |
# File 'documented/util/util.rb', line 137 def self.(chunk) = chunk.to_s.scan(QUIET_STATE_TAG_PATTERN) return nil if .empty? "#{.join}\n" end |
.quiet_command(command, start_pattern, end_pattern, include_end = true, timeout = 5, silent = true) ⇒ Array<String>
Executes a game command and captures output between start and end patterns, suppressing output to the front-end.
Wraps issue_command with XML downstream disabled and quiet output suppression. Output lines matching the start and end patterns are silenced at the front-end, though state-toggling tags embedded in those lines are preserved.
264 265 266 |
# File 'documented/util/util.rb', line 264 def self.quiet_command(command, start_pattern, end_pattern, include_end = true, timeout = 5, silent = true) return issue_command(command, start_pattern, end_pattern, include_end: include_end, timeout: timeout, silent: silent, usexml: false, quiet: true) end |
.quiet_command_xml(command, start_pattern, end_pattern = /<prompt/, include_end = true, timeout = 5, silent = true) ⇒ Array<String>
Executes a game command and captures output between start and end patterns, suppressing output to the front-end.
Wraps issue_command with XML downstream enabled and quiet output suppression. Output lines matching the start and end patterns are silenced at the front-end, though state-toggling tags (e.g., mono mode) embedded in those lines are preserved.
243 244 245 |
# File 'documented/util/util.rb', line 243 def self.quiet_command_xml(command, start_pattern, end_pattern = /<prompt/, include_end = true, timeout = 5, silent = true) return issue_command(command, start_pattern, end_pattern, include_end: include_end, timeout: timeout, silent: silent, usexml: true, quiet: true) end |
.silver_count(timeout = 3) ⇒ Integer
Retrieves the current silver count from the game output by issuing the 'info' command and parsing the response. Uses a downstream hook to filter and extract the silver value.
This method temporarily silences output, sets up a downstream hook to capture the relevant lines, and restores the previous silence state after completion.
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 |
# File 'documented/util/util.rb', line 279 def self.silver_count(timeout = 3) silence_me unless (undo_silence = silence_me) result = '' name = self.anon_hook filter = false start_pattern = /^\s*Name\:/ end_pattern = /^\s*Mana\:\s+\-?[0-9]+\s+Silver\:\s+([0-9,]+)/ ttl = Time.now + timeout begin # main thread DownstreamHook.add(name, proc { |line| if filter if line =~ end_pattern result = $1.dup DownstreamHook.remove(name) filter = false else next(nil) end elsif line =~ start_pattern filter = true next(nil) else line end }, persist: false) # scoped to this command; removed in the ensure below # script thread fput 'info' loop { # non-blocking check, this allows us to # check the time even when the buffer is empty line = get? break if line && line =~ end_pattern break if Time.now > ttl sleep(0.01) # prevent a tight-loop } ensure DownstreamHook.remove(name) silence_me if undo_silence end return result.gsub(',', '').to_i end |