Class: Aspera::Cli::ExtendedValue
- Inherits:
-
Object
- Object
- Aspera::Cli::ExtendedValue
- Includes:
- Singleton
- Defined in:
- lib/aspera/cli/extended_value.rb
Overview
Command line extended values
Constant Summary collapse
- DEFAULT_DECODERS =
First is default
%i[none json ruby yaml].freeze
- STDIN_MODES =
Modes of
@stdin:: text, binary, text without the last end of line, or the standard input read by the command (where a file is read) ['', 'bin', 'chomp', 'stream'].freeze
Instance Attribute Summary collapse
-
#default_decoder ⇒ Object
Returns the value of attribute default_decoder.
Class Method Summary collapse
-
.assert_no_value(value, ext_type) ⇒ Object
The value must be empty.
-
.decode_csvt(value) ⇒ Object
Decode comma separated table text.
-
.instance ⇒ ExtendedValue
Returns the singleton instance of ExtendedValue.
-
.JSON_parse(value) ⇒ Object
JSON Parser, with more information on error location extract a context: 10 chars before and after the error on the given line and display a pointer "^" :reek:UncommunicativeMethodName.
-
.read_secret(prompt) ⇒ String
Ask the user for a secret: on a web page if the user interface is graphical (option
ui), else on terminal. -
.read_stdin(mode) ⇒ String, StandardInput
The content of the standard input, or for mode
streamthe standard input itself, read by the command.
Instance Method Summary collapse
-
#description(name) ⇒ String?
Description of the method, for shell completion.
-
#disable(name, reason) ⇒ Object
Disable a handler: its use raises an error.
-
#evaluate(value, context:, allowed: nil) ⇒ String, ...
Parses a
Stringvalue to extended value. -
#evaluate_extend(value) ⇒ Object
Find inner extended values Evaluated values are inserted as is: not evaluated again Only used in above lambda.
-
#modifiers ⇒ Object
List of Extended Value methods.
-
#on(name, description: nil, &block) ⇒ Object
Add a new handler, or replace one.
Instance Attribute Details
#default_decoder ⇒ Object
Returns the value of attribute default_decoder.
178 179 180 |
# File 'lib/aspera/cli/extended_value.rb', line 178 def default_decoder @default_decoder end |
Class Method Details
.assert_no_value(value, ext_type) ⇒ Object
The value must be empty
81 82 83 |
# File 'lib/aspera/cli/extended_value.rb', line 81 def assert_no_value(value, ext_type) Aspera.assert(value.empty?, type: BadArgument) { "no value allowed for extended value type: #{ext_type}" } end |
.decode_csvt(value) ⇒ Object
Decode comma separated table text
42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/aspera/cli/extended_value.rb', line 42 def decode_csvt(value) col_titles = nil hash_array = [] CSV.parse(value).each do |values| next if values.empty? if col_titles.nil? col_titles = values else hash_array.push(col_titles.zip(values).to_h) end end Log.log.warn('Titled CSV file without any row') if hash_array.empty? return hash_array end |
.instance ⇒ ExtendedValue
Returns the singleton instance of ExtendedValue
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 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 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 |
# File 'lib/aspera/cli/extended_value.rb', line 32 class ExtendedValue include Singleton # First is default DEFAULT_DECODERS = %i[none json ruby yaml].freeze # Modes of `@stdin:`: text, binary, text without the last end of line, or the standard input read by the command (where a file is read) STDIN_MODES = ['', 'bin', 'chomp', 'stream'].freeze class << self # Decode comma separated table text def decode_csvt(value) col_titles = nil hash_array = [] CSV.parse(value).each do |values| next if values.empty? if col_titles.nil? col_titles = values else hash_array.push(col_titles.zip(values).to_h) end end Log.log.warn('Titled CSV file without any row') if hash_array.empty? return hash_array end # JSON Parser, with more information on error location # extract a context: 10 chars before and after the error on the given line and display a pointer "^" # :reek:UncommunicativeMethodName def JSON_parse(value) # rubocop:disable Naming/MethodName JSON.parse(value) rescue JSON::ParserError => e m = /at line (\d+) column (\d+)/.match(e.) raise if m.nil? line = m[1].to_i - 1 column = m[2].to_i - 1 lines = value.lines raise if line >= lines.size error_line = lines[line].chomp context_col_beg = [column - 10, 0].max context_col_end = [column + 10, error_line.length].min context = error_line[context_col_beg...context_col_end] cursor_pos = column - context_col_beg pointer = ' ' * cursor_pos + '^'.blink raise BadArgument, "#{e.}\n#{context}\n#{pointer}" end # The value must be empty # @param value [String] The value as parameter # @param ext_type [Symbol] The method of extended value def assert_no_value(value, ext_type) Aspera.assert(value.empty?, type: BadArgument) { "no value allowed for extended value type: #{ext_type}" } end # Ask the user for a secret: on a web page if the user interface is graphical (option `ui`), else on terminal # @param prompt [String] Name of the secret, empty for default # @return [String] The secret def read_secret(prompt) prompt = 'secret' if prompt.empty? return Prompt.prompt_user_input(prompt, sensitive: true) unless Environment.instance.url_method.eql?(:graphical) require_relative 'web_secret' WebSecret.ask(prompt) end # @param mode [String] one of `STDIN_MODES` # @return [String, StandardInput] the content of the standard input, or for mode `stream` the standard input itself, read by the command def read_stdin(mode) case mode when '' then $stdin.read when 'bin' then $stdin.binmode.read when 'chomp' then $stdin.read.chomp when 'stream' then StandardInput.new else raise BadArgument, "`stdin` supports only: #{STDIN_MODES.map(&:inspect).join(', ')}" end end end private def initialize # Base handlers # Other handlers can be set using `on` # e.g. `preset` is reader in config plugin # @type [Hash{Symbol => Proc}] @handlers = { val: lambda { |i| i }, base64: lambda { |i| Base64.decode64(i) }, csvt: lambda { |i| ExtendedValue.decode_csvt(i) }, date: lambda { |i| Units::Timestamp.parse(i).getutc.iso8601 }, env: lambda { |i| ENV.fetch(i) { raise BadArgument, "environment variable #{i} is not set" } }, file: lambda { |i| Security.instance.read_file(i) }, uri: lambda { |i| UriReader.read(i) }, json: lambda { |i| ExtendedValue.JSON_parse(i) }, lines: lambda { |i| i.split("\n") }, list: lambda { |i| i[1..].split(i[0]) }, none: lambda { |i| ExtendedValue.assert_no_value(i, :none); nil }, # rubocop:disable Style/Semicolon path: lambda { |i| File.(i) }, re: lambda { |i| Regexp.new(i, Regexp::MULTILINE) }, ruby: lambda { |i| Environment.secure_eval(i, __FILE__, __LINE__) }, s: lambda(&:to_s), secret: lambda { |i| ExtendedValue.read_secret(i) }, stdin: lambda { |i| ExtendedValue.read_stdin(i) }, yaml: lambda { |i| YAML.safe_load(i) }, zlib: lambda { |i| Zlib::Inflate.inflate(i) }, extend: lambda { |i| ExtendedValue.instance.evaluate_extend(i) } } # Descriptions of handlers, for shell completion # @type [Hash{Symbol => String}] @descriptions = { val: 'Value as is: modifiers on the right are not evaluated', base64: 'Decode Base64', csvt: 'Decode titled CSV: Array of Hash', date: 'Date in UTC, ISO 8601: a date, or now, today, yesterday, tomorrow, optionally followed by -<duration> or +<duration>, e.g. now-24h', env: 'Value of environment variable', file: 'Content of local file', uri: 'Content of URL: http:, https:, data:, file:', json: 'Decode JSON', lines: 'Split lines: Array', list: 'Split on first character: Array', none: 'Null value', path: 'Local path, with ~ expanded', re: 'Regular expression', ruby: 'Evaluate Ruby code', s: 'Convert to String', secret: 'Ask secret, with prompt', stdin: 'Read standard input: empty, bin, chomp, or stream (read by a command that reads a file)', yaml: 'Decode YAML', zlib: 'Decompress zlib', extend: 'Evaluate embedded @<modifier>:<value>@' } @regex_single = nil @regex_inner = nil @default_decoder = nil update_regex end # Update the Regex to match an extended value based on @handlers # Single: anchored on the whole value (`\A`, `\z`), not on lines: a multi-line value is extended only if it starts with a modifier. # Inner: an extended value embedded in a text, for `@extend:` def update_regex handler_regex = "#{MARKER_START}(#{Regexp.union(modifiers.map(&:to_s)).source})#{MARKER_END}" @regex_single = Regexp.new("\\A#{handler_regex}(.*)\\z", Regexp::MULTILINE) @regex_inner = Regexp.new("#{handler_regex}([^#{MARKER_IN_END}]*)#{MARKER_IN_END}") end public attr_reader :default_decoder def default_decoder=(value) Log.log.debug { "Setting default decoder to (#{value.class}) #{value}" } Aspera.assert_values(value, DEFAULT_DECODERS) value = nil if value.eql?(:none) @default_decoder = value end # List of Extended Value methods def modifiers; @handlers.keys; end # @param name [Symbol] Extended Value method # @return [String, nil] description of the method, for shell completion def description(name) = @descriptions[name] # Add a new handler, or replace one # @param name [Symbol] method, used as `@<name>:` # @param description [String, nil] description, for shell completion; `nil` keeps the current one def on(name, description: nil, &block) Aspera.assert_type(name, Symbol) { 'name' } Aspera.assert(block) { "block required when registering handler for #{name}" } Log.log.debug { "Setting handler for #{name}" } @handlers[name] = block @descriptions[name] = description unless description.nil? update_regex end # Disable a handler: its use raises an error. # e.g. `@stdin:` in MCP server mode, where the standard input is the JSON-RPC stream: also the argument `-`, which is `@stdin:stream`. # @param name [Symbol] Extended Value method # @param reason [String] Why it is disabled, for the error message, e.g. `in MCP server mode` def disable(name, reason) on(name) { |_| raise BadArgument, "@#{name}: extended value is disabled #{reason}" } end # Parses a `String` value to extended value. # If it is a String using supported extended value modifiers, then evaluate them. # Other value types are returned as is. # @param value [String] the value to parse # @param context [String] Context in which evaluation is done # @param allowed [Array<Class>,NilClass] Expected types # @return [String, Integer, Array, Hash, Boolean] Evaluated value def evaluate(value, context:, allowed: nil) return value unless value.is_a?(String) Aspera.assert_array_all(allowed, Class) unless allowed.nil? # use default decoder if not an extended value and expect complex types using_default_decoder = allowed&.all? { |t| DEFAULT_PARSER_TYPES.include?(t) } && !@regex_single.match?(value) && !@default_decoder.nil? value = [MARKER_START, @default_decoder, MARKER_END, value].join if using_default_decoder # First determine decoders, in reversed order handlers_reversed = [] while (m = value.match(@regex_single)) handler = m[1].to_sym handlers_reversed.unshift(handler) value = m[2] # `@val:` keeps the rest as is; `@extend:` too, unless the rest is a single extended value (e.g. `@extend:@file:x`): decoded first, then extended break if SPECIAL_HANDLERS.include?(handler) && (handler.eql?(:val) || @regex_inner.match?(value)) end Log.log.trace1 { "evaluating: #{handlers_reversed}, value: #{value.class}:#{Secret::Hider.instance.hidden_copy(value)}" } handlers_reversed.each_with_index do |handler, index| # The standard input read by the command is not a value raise BadArgument, '@stdin:stream is read by the command, it cannot be decoded: use @stdin:' if value.is_a?(StandardInput) Security.instance.check_extended_value(handler) # The value read by the previous handler may be a secret Security.instance.check_secret_processing("@#{handler}") { Secret::Hider.instance.contains_secret?(value) } if index.positive? value = @handlers[handler].call(value) # Values read from a secret source are hidden wherever they appear: logs, results if SECRET_HANDLERS.include?(handler) value.is_a?(String) ? Secret::Hider.instance.add_secret_values(value) : Secret::Hider.instance.add_secrets_in(value) end rescue => e raise BadArgument, "Evaluation of #{MARKER_START}#{handler}#{MARKER_END} for #{context}: #{e.}" end # Only where a command reads a file, see `Argument#stdin` raise BadArgument, "@stdin:stream is only for a command that reads a file, not for #{context}: use @stdin:" if value.is_a?(StandardInput) && !allowed&.include?(StandardInput) return value end # Find inner extended values # Evaluated values are inserted as is: not evaluated again # Only used in above lambda def evaluate_extend(value) value.gsub(@regex_inner) do m = Regexp.last_match sub_value = "@#{m[1]}:#{m[2]}" Log.log.debug { "evaluating #{sub_value}" } sub_value = evaluate(sub_value, context: 'composite extended value') # In a text, a secret is not the whole value Security.instance.check_secret_processing('@extend') { Secret::Hider.instance.contains_secret?(sub_value) } sub_value.to_s end end # marker "@" MARKER_START = '@' # marker ":" MARKER_END = ':' # marker "@" MARKER_IN_END = '@' # Special handlers stop processing of handlers on right # :extend includes processing of other handlers in itself, except if the value on right has no embedded value # :val keeps the value intact SPECIAL_HANDLERS = %i[extend val].freeze # Handlers that read a secret SECRET_HANDLERS = %i[secret vault].freeze # Array and Hash types: DEFAULT_PARSER_TYPES = [Array, Hash].freeze private_constant :MARKER_START, :MARKER_END, :MARKER_IN_END, :SPECIAL_HANDLERS, :SECRET_HANDLERS, :DEFAULT_PARSER_TYPES end |
.JSON_parse(value) ⇒ Object
JSON Parser, with more information on error location extract a context: 10 chars before and after the error on the given line and display a pointer "^" :reek:UncommunicativeMethodName
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/aspera/cli/extended_value.rb', line 60 def JSON_parse(value) # rubocop:disable Naming/MethodName JSON.parse(value) rescue JSON::ParserError => e m = /at line (\d+) column (\d+)/.match(e.) raise if m.nil? line = m[1].to_i - 1 column = m[2].to_i - 1 lines = value.lines raise if line >= lines.size error_line = lines[line].chomp context_col_beg = [column - 10, 0].max context_col_end = [column + 10, error_line.length].min context = error_line[context_col_beg...context_col_end] cursor_pos = column - context_col_beg pointer = ' ' * cursor_pos + '^'.blink raise BadArgument, "#{e.}\n#{context}\n#{pointer}" end |
.read_secret(prompt) ⇒ String
Ask the user for a secret: on a web page if the user interface is graphical (option ui), else on terminal
88 89 90 91 92 93 |
# File 'lib/aspera/cli/extended_value.rb', line 88 def read_secret(prompt) prompt = 'secret' if prompt.empty? return Prompt.prompt_user_input(prompt, sensitive: true) unless Environment.instance.url_method.eql?(:graphical) require_relative 'web_secret' WebSecret.ask(prompt) end |
.read_stdin(mode) ⇒ String, StandardInput
Returns the content of the standard input, or for mode stream the standard input itself, read by the command.
97 98 99 100 101 102 103 104 105 |
# File 'lib/aspera/cli/extended_value.rb', line 97 def read_stdin(mode) case mode when '' then $stdin.read when 'bin' then $stdin.binmode.read when 'chomp' then $stdin.read.chomp when 'stream' then StandardInput.new else raise BadArgument, "`stdin` supports only: #{STDIN_MODES.map(&:inspect).join(', ')}" end end |
Instance Method Details
#description(name) ⇒ String?
Returns description of the method, for shell completion.
192 |
# File 'lib/aspera/cli/extended_value.rb', line 192 def description(name) = @descriptions[name] |
#disable(name, reason) ⇒ Object
Disable a handler: its use raises an error.
e.g. @stdin: in MCP server mode, where the standard input is the JSON-RPC stream: also the argument -, which is @stdin:stream.
210 211 212 |
# File 'lib/aspera/cli/extended_value.rb', line 210 def disable(name, reason) on(name) { |_| raise BadArgument, "@#{name}: extended value is disabled #{reason}" } end |
#evaluate(value, context:, allowed: nil) ⇒ String, ...
Parses a String value to extended value.
If it is a String using supported extended value modifiers, then evaluate them.
Other value types are returned as is.
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 |
# File 'lib/aspera/cli/extended_value.rb', line 221 def evaluate(value, context:, allowed: nil) return value unless value.is_a?(String) Aspera.assert_array_all(allowed, Class) unless allowed.nil? # use default decoder if not an extended value and expect complex types using_default_decoder = allowed&.all? { |t| DEFAULT_PARSER_TYPES.include?(t) } && !@regex_single.match?(value) && !@default_decoder.nil? value = [MARKER_START, @default_decoder, MARKER_END, value].join if using_default_decoder # First determine decoders, in reversed order handlers_reversed = [] while (m = value.match(@regex_single)) handler = m[1].to_sym handlers_reversed.unshift(handler) value = m[2] # `@val:` keeps the rest as is; `@extend:` too, unless the rest is a single extended value (e.g. `@extend:@file:x`): decoded first, then extended break if SPECIAL_HANDLERS.include?(handler) && (handler.eql?(:val) || @regex_inner.match?(value)) end Log.log.trace1 { "evaluating: #{handlers_reversed}, value: #{value.class}:#{Secret::Hider.instance.hidden_copy(value)}" } handlers_reversed.each_with_index do |handler, index| # The standard input read by the command is not a value raise BadArgument, '@stdin:stream is read by the command, it cannot be decoded: use @stdin:' if value.is_a?(StandardInput) Security.instance.check_extended_value(handler) # The value read by the previous handler may be a secret Security.instance.check_secret_processing("@#{handler}") { Secret::Hider.instance.contains_secret?(value) } if index.positive? value = @handlers[handler].call(value) # Values read from a secret source are hidden wherever they appear: logs, results if SECRET_HANDLERS.include?(handler) value.is_a?(String) ? Secret::Hider.instance.add_secret_values(value) : Secret::Hider.instance.add_secrets_in(value) end rescue => e raise BadArgument, "Evaluation of #{MARKER_START}#{handler}#{MARKER_END} for #{context}: #{e.}" end # Only where a command reads a file, see `Argument#stdin` raise BadArgument, "@stdin:stream is only for a command that reads a file, not for #{context}: use @stdin:" if value.is_a?(StandardInput) && !allowed&.include?(StandardInput) return value end |
#evaluate_extend(value) ⇒ Object
Find inner extended values Evaluated values are inserted as is: not evaluated again Only used in above lambda
259 260 261 262 263 264 265 266 267 268 269 |
# File 'lib/aspera/cli/extended_value.rb', line 259 def evaluate_extend(value) value.gsub(@regex_inner) do m = Regexp.last_match sub_value = "@#{m[1]}:#{m[2]}" Log.log.debug { "evaluating #{sub_value}" } sub_value = evaluate(sub_value, context: 'composite extended value') # In a text, a secret is not the whole value Security.instance.check_secret_processing('@extend') { Secret::Hider.instance.contains_secret?(sub_value) } sub_value.to_s end end |
#modifiers ⇒ Object
List of Extended Value methods
188 |
# File 'lib/aspera/cli/extended_value.rb', line 188 def modifiers; @handlers.keys; end |
#on(name, description: nil, &block) ⇒ Object
Add a new handler, or replace one
197 198 199 200 201 202 203 204 |
# File 'lib/aspera/cli/extended_value.rb', line 197 def on(name, description: nil, &block) Aspera.assert_type(name, Symbol) { 'name' } Aspera.assert(block) { "block required when registering handler for #{name}" } Log.log.debug { "Setting handler for #{name}" } @handlers[name] = block @descriptions[name] = description unless description.nil? update_regex end |