Skip to content
Kward Search API index

Module: Kward::NativeShell::Fields

Defined in:
lib/kward/shell/native_fields.rb

Overview

Shared field splitting for word expansion and read. Quote provenance stays attached to characters; literal text is never split merely because it is IFS.

Defined Under Namespace

Classes: Character

Constant Summary collapse

DEFAULT_IFS =
" \t\n".freeze

Class Method Summary collapse

Class Method Details

.characters(value, quoted: false, split: false) ⇒ Object



9
10
11
12
13
# File 'lib/kward/shell/native_fields.rb', line 9

def self.characters(value, quoted: false, split: false)
  result = value.each_char.map { |text| Character.new(text: text, quoted: quoted, split: split) }
  result << Character.new(text: "", quoted: true, split: false) if value.empty? && quoted
  result
end

.pattern(characters, glob: false) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/kward/shell/native_fields.rb', line 53

def self.pattern(characters, glob: false)
  characters.map do |character|
    next character.text unless character.quoted || glob
    special = character.quoted ? /[\\*?\[\]{}!^\-]/ : /[{}]/
    character.text.gsub(special) { |text| "\\#{text}" }
  end.join
end

.ranges(characters, ifs, limit: nil) ⇒ Object

Ranges retain original separators for read's final, unsplit variable.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/kward/shell/native_fields.rb', line 24

def self.ranges(characters, ifs, limit: nil)
  result = []
  index = 0
  index += 1 while whitespace?(characters[index], ifs)
  while index < characters.length
    start = index
    if limit && result.length >= limit
      finish = characters.length
      finish -= 1 while finish > start && whitespace?(characters[finish - 1], ifs)
      result << (start...finish) if finish > start
      break
    end
    index += 1 while index < characters.length && !separator?(characters[index], ifs)
    result << (start...index)
    if whitespace?(characters[index], ifs)
      index += 1 while whitespace?(characters[index], ifs)
      index += 1 if separator?(characters[index], ifs)
    elsif separator?(characters[index], ifs)
      index += 1
    end
    index += 1 while whitespace?(characters[index], ifs)
  end
  result
end

.separator?(character, ifs) ⇒ Boolean

Returns:

  • (Boolean)


15
16
17
# File 'lib/kward/shell/native_fields.rb', line 15

def self.separator?(character, ifs)
  character && character.split && !character.text.empty? && ifs.include?(character.text)
end

.value(characters) ⇒ Object



49
50
51
# File 'lib/kward/shell/native_fields.rb', line 49

def self.value(characters)
  characters.map(&:text).join
end

.whitespace?(character, ifs) ⇒ Boolean

Returns:

  • (Boolean)


19
20
21
# File 'lib/kward/shell/native_fields.rb', line 19

def self.whitespace?(character, ifs)
  separator?(character, ifs) && DEFAULT_IFS.include?(character.text)
end