/
String.rb
1355 lines (1200 loc) · 44.6 KB
/
String.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# encoding: utf-8
# ***************************************************************************
#
# Copyright (c) 2002 - 2012 Novell, Inc.
# All Rights Reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Novell, Inc.
#
# To contact Novell about this file by physical or electronic mail,
# you may find current contact information at www.novell.com
#
# ***************************************************************************
# File: modules/String.ycp
# Package: yast2
# Summary: String manipulation routines
# Authors: Michal Svec <msvec@suse.cz>
#
# $Id$
require "yast"
module Yast
class StringClass < Module
def main
textdomain "base"
# character sets, suitable for ValidChars
@cupper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
@clower = "abcdefghijklmnopqrstuvwxyz"
@calpha = Ops.add(@cupper, @clower)
@cdigit = "0123456789"
@cxdigit = Ops.add(@cdigit, "ABCDEFabcdef")
@calnum = Ops.add(@calpha, @cdigit)
@cpunct = "!\"\#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
@cgraph = Ops.add(@calnum, @cpunct)
@cspace = "\f\r\n\t\v"
@cprint = Ops.add(@cspace, @cgraph)
# 64 characters is the base undeline length
@base_underline = "----------------------------------------------------------------"
end
# Quote a string with 's
#
# More precisely it protects single quotes inside the string but does not
# prepend or append single quotes.
#
# @param [String] var unquoted string
# @return quoted string
# @example quote("a'b") -> "a'\''b"
def Quote(var)
return "" if var.nil? || var == ""
Builtins.mergestring(Builtins.splitstring(var, "'"), "'\\''")
end
# Unquote a string with 's (quoted with quote)
# @param [String] var quoted string
# @return unquoted string
# @see #quote
def UnQuote(var)
return "" if var.nil? || var == ""
Builtins.y2debug("var=%1", var)
while Builtins.regexpmatch(var, "'\\\\''")
var = Builtins.regexpsub(var, "(.*)'\\\\''(.*)", "\\1'\\2")
Builtins.y2debug("var=%1", var)
end
var
end
# Optional formatted text
# @return sformat (f, s) if s is neither empty or nil, else ""
def OptFormat(f, s)
s == "" || s.nil? ? "" : Builtins.sformat(f, s)
end
# Optional parenthesized text
# @return " (Foo)" if Foo is neither empty or nil, else ""
def OptParens(s)
OptFormat(" (%1)", s)
end
# @param [Array<String>] l a list of strings
# @return only non-"" items
def NonEmpty(l)
l = deep_copy(l)
Builtins.filter(l) { |i| i != "" }
end
# @param [String] s \n-terminated items
# @return the items as a list, with empty lines removed
def NewlineItems(s)
NonEmpty(Builtins.splitstring(s, "\n"))
end
# @param [Boolean] value boolean
# @return [Boolean] value as "Yes" or "No"
def YesNo(value)
if value
# human text for Boolean value
return _("Yes")
else
# human text for Boolean value
return _("No")
end
end
# Return a pretty description of a byte count
#
# Return a pretty description of a byte count with required precision
# and using B, KiB, MiB, GiB or TiB as unit as appropriate.
#
# Uses the current locale defined decimal separator
# (i.e. the result is language dependant).
#
# @param [Fixnum] bytes size (e.g. free diskspace, memory size) in Bytes
# @param [Fixnum] precision number of fraction digits in output, if negative (less than 0) the precision is set automatically depending on the suffix
# @param [Boolean] omit_zeroes if true then do not add zeroes
# (useful for memory size - 128 MiB RAM looks better than 128.00 MiB RAM)
# @return formatted string
#
# @example FormatSizeWithPrecision(128, 2, true) -> "128 B"
# @example FormatSizeWithPrecision(4096, 2, true) -> "4 KiB"
# @example FormatSizeWithPrecision(4096, 2, false) -> "4.00 KiB"
# @example FormatSizeWithPrecision(1024*1024, 2, true) -> "1 MiB"
def FormatSizeWithPrecision(bytes, precision, omit_zeroes)
return "" if bytes.nil?
units = [
# Byte abbreviated
_("B"),
# KiloByte abbreviated
_("KiB"),
# MegaByte abbreviated
_("MiB"),
# GigaByte abbreviated
_("GiB"),
# TeraByte abbreviated
_("TiB")
]
index = 0
whole = Builtins.tofloat(bytes)
while (Ops.greater_or_equal(whole, 1024.0) ||
Ops.less_or_equal(whole, -1024.0)) &&
Ops.less_than(Ops.add(index, 1), Builtins.size(units))
whole = Ops.divide(whole, 1024.0)
index = Ops.add(index, 1)
end
if precision.nil?
precision = 0
elsif Ops.less_than(precision, 0)
# auto precision - depends on the suffix, but max. 3 decimal digits
precision = Ops.less_or_equal(index, 3) ? index : 3
end
if omit_zeroes == true
max_difference = 0.9
i = precision
while Ops.greater_than(i, 0)
max_difference = Ops.divide(
max_difference,
Convert.convert(10, from: "integer", to: "float")
)
i = Ops.subtract(i, 1)
end
if Ops.less_than(
Ops.subtract(
whole,
Convert.convert(
Builtins.tointeger(whole),
from: "integer",
to: "float"
)
),
max_difference
)
precision = 0
end
end
Ops.add(
Ops.add(Builtins::Float.tolstring(whole, precision), " "),
Ops.get_string(units, index, "")
)
end
# Return a pretty description of a byte count
#
# Return a pretty description of a byte count, with two fraction digits
# and using B, KiB, MiB, GiB or TiB as unit as appropriate.
#
# Uses the current locale defined decimal separator
# (i.e. the result is language dependant).
#
# @param [Fixnum] bytes size (e.g. free diskspace) in Bytes
# @return formatted string
#
# @example FormatSize(23456767890) -> "223.70 MiB"
def FormatSize(bytes)
return "" if bytes.nil?
# automatic precision, don't print trailing zeroes for sizes < 1MiB
FormatSizeWithPrecision(bytes, -1, Ops.less_than(bytes, 1 << 20))
end
# Return a pretty description of a download rate
#
# Return a pretty description of a download rate, with two fraction digits
# and using B/s, KiB/s, MiB/s, GiB/s or TiB/s as unit as appropriate.
#
# @param [Fixnum] bytes_per_second download rate (in B/s)
# @return formatted string
#
# @example FormatRate(6780) -> ""
# @example FormatRate(0) -> ""
# @example FormatRate(895321) -> ""
def FormatRate(bytes_per_second)
# covert a number to download rate string
# %1 is string - size in bytes, B, KiB, MiB, GiB or TiB
Builtins.sformat(_("%1/s"), FormatSize(bytes_per_second))
end
# Add a download rate status to a message.
#
# Add the current and the average download rate to the message.
#
# @param [String] text the message with %1 placeholder for the download rate string
# @param [Fixnum] avg_bps average download rate (in B/s)
# @param [Fixnum] curr_bps current download rate (in B/s)
#
# @return [String] formatted message
def FormatRateMessage(text, avg_bps, curr_bps)
rate = ""
if Ops.greater_than(curr_bps, 0)
rate = FormatRate(curr_bps)
if Ops.greater_than(avg_bps, 0)
# format download rate message: %1 = the current download rate (e.g. "242.6kB/s")
# %2 is the average download rate (e.g. "228.3kB/s")
# to translators: keep translation of "on average" as short as possible
rate = Builtins.sformat(
_("%1 (on average %2)"),
rate,
FormatRate(avg_bps)
)
end
end
# add download rate to the downloading message
# %1 is URL, %2 is formatted download rate, e.g. "242.6kB/s (avg. 228.3kB/s)"
# in ncurses UI the strings are exchanged (%1 is the rate, %2 is URL)
# due to limited space on the screen
Builtins.sformat(text, rate)
end
# Format an integer number as (at least) two digits; use leading zeroes if
# necessary.
# @param [Fixnum] x input
# @return [String] number as two-digit string
#
def FormatTwoDigits(x)
if Ops.less_than(x, 10) && Ops.greater_or_equal(x, 0)
Builtins.sformat("0%1", x)
else
Builtins.sformat("%1", x)
end
end
# Format an integer seconds value with min:sec or hours:min:sec
# @param [Fixnum] seconds time (in seconds)
# @return [String] formatted string (empty for negative values)
#
def FormatTime(seconds)
return "" if Ops.less_than(seconds, 0)
if Ops.less_than(seconds, 3600) # Less than one hour
return Builtins.sformat(
"%1:%2",
FormatTwoDigits(Ops.divide(seconds, 60)),
FormatTwoDigits(Ops.modulo(seconds, 60))
) # More than one hour - we don't hope this will ever happen, but who knows?
else
hours = Ops.divide(seconds, 3600)
seconds = Ops.modulo(seconds, 3600)
return Builtins.sformat(
"%1:%2:%3",
hours,
FormatTwoDigits(Ops.divide(seconds, 60)),
FormatTwoDigits(Ops.modulo(seconds, 60))
)
end
end
# Remove blanks at begin and end of input string.
# @param [String] input string to be stripped
# @return stripped string
# @example CutBlanks(" any input ") -> "any input"
def CutBlanks(input)
return "" if input.nil? || Ops.less_than(Builtins.size(input), 1)
pos1 = Builtins.findfirstnotof(input, " \t")
return "" if pos1.nil?
pos2 = Builtins.findlastnotof(input, " \t")
Builtins.substring(input, pos1, Ops.add(Ops.subtract(pos2, pos1), 1))
end
# Remove any leading zeros
#
# Remove any leading zeros that make tointeger inadvertently
# assume an octal number (e.g. "09" -> "9", "0001" -> "1",
# but "0" -> "0")
#
# @param [String] input number that might contain leadig zero
# @return [String] that has leading zeros removed
def CutZeros(input)
return "" if input.nil? || Ops.less_than(Builtins.size(input), 1)
return input if !Builtins.regexpmatch(input, "^0.*")
output = Builtins.regexpsub(input, "^0+(.*)$", "\\1")
return "0" if Ops.less_than(Builtins.size(output), 1)
output
end
# Repeat a string
#
# Repeat a string number of times.
#
# @param input string to repeat
# @param input number number of repetitions
# @return [String] repeated string
def Repeat(text, number)
text = "" if text.nil?
ret = ""
while Ops.greater_than(number, 0)
ret = Ops.add(ret, text)
number = Ops.subtract(number, 1)
end
ret
end
# Add the padding character around the text to make it long enough
#
# Add the padding character around the text to make it long enough. If the
# text is longer than requested, no changes are made.
#
# @param [String] text text to be padded
# @param [Fixnum] length requested length
# @param [String] padding padding character
# @param [Symbol] alignment alignment to use, either `left or `right
# @return padded text
def SuperPad(text, length, padding, alignment)
text = "" if text.nil?
pad = Repeat(padding, Ops.subtract(length, Builtins.size(text)))
if alignment == :right
return Ops.add(pad, text)
else
return Ops.add(text, pad)
end
end
# Add spaces after the text to make it long enough
#
# Add spaces after the text to make it long enough. If the text is longer
# than requested, no changes are made.
#
# @param [String] text text to be padded
# @param [Fixnum] length requested length
# @return padded text
def Pad(text, length)
SuperPad(text, length, " ", :left)
end
# Add zeros before the text to make it long enough.
#
# Add zeros before the text to make it long enough. If the text is longer
# than requested, no changes are made.
#
# @param [String] text text to be padded
# @param [Fixnum] length requested length
# @return padded text
def PadZeros(text, length)
SuperPad(text, length, "0", :right)
end
# Parse string of values
#
# Parse string of values - split string to values, quoting and backslash sequences are supported
# @param [String] options Input string
# @param [Hash] parameters Parmeter used at parsing - map with keys:
# "separator":<string> - value separator (default: " \t"),
# "unique":<boolean> - result will not contain any duplicates, first occurance of the string is stored into output (default: false),
# "interpret_backslash":<boolean> - convert backslash sequence into one character (e.g. "\\n" => "\n") (default: true)
# "remove_whitespace":<boolean> - remove white spaces around values (default: true),
# @return [Array<String>] List of strings
def ParseOptions(options, parameters)
parameters = deep_copy(parameters)
ret = []
# parsing options
separator = Ops.get_string(parameters, "separator", " \t")
unique = Ops.get_boolean(parameters, "unique", false)
interpret_backslash = Ops.get_boolean(
parameters,
"interpret_backslash",
true
)
remove_whitespace = Ops.get_boolean(parameters, "remove_whitespace", true)
Builtins.y2debug(
"Input: string: '%1', parameters: %2",
options,
parameters
)
Builtins.y2debug(
"Used values: separator: '%1', unique: %2, remove_whitespace: %3",
separator,
unique,
remove_whitespace
)
return [] if options.nil?
# two algorithms are used:
# first is much faster, but only usable if string
# doesn't contain any double qoute characters
# and backslash sequences are not interpreted
# second is more general, but of course slower
if Builtins.findfirstof(options, "\"").nil? &&
interpret_backslash == false
# easy case - no qouting, don't interpres backslash sequences => use splitstring
values = Builtins.splitstring(options, separator)
Builtins.foreach(values) do |v|
v = CutBlanks(v) if remove_whitespace == true
if unique == true
ret = Builtins.add(ret, v) if !Builtins.contains(ret, v)
else
ret = Builtins.add(ret, v)
end
end
else
# quoting is used or backslash interpretation is enabled
# so it' not possible to split input
# parsing each character is needed - use finite automaton
# state
state = :out_of_string
# position in the input string
index = 0
# parsed value - buffer
str = ""
while Ops.less_than(index, Builtins.size(options))
character = Builtins.substring(options, index, 1)
Builtins.y2debug(
"character: %1 state: %2 index: %3",
character,
state,
index
)
# interpret backslash sequence
if character == "\\" && interpret_backslash == true
if Ops.less_than(Ops.add(index, 1), Builtins.size(options))
nextcharacter = Builtins.substring(options, Ops.add(index, 1), 1)
index = Ops.add(index, 1)
# backslah sequences
backslash_seq = {
"a" => "\a", # alert
"b" => "\b", # backspace
"e" => "\e", # escape
"f" => "\f", # FF
"n" => "\n", # NL
"r" => "\r", # CR
"t" => "\t", # tab
"v" => "\v", # vertical tab
"\\" => "\\", # backslash
# backslash will be removed later,
# double quote and escaped double quote have to be different
# as it have different meaning
"\"" => "\\\""
}
if backslash_seq[nextcharacter]
character = backslash_seq[nextcharacter]
else
# ignore backslash in invalid backslash sequence
character = nextcharacter
end
Builtins.y2debug("backslash sequence: '%1'", character)
else
Builtins.y2warning(
"Missing character after backslash (\\) at the end of string"
)
end
end
if state == :out_of_string
# ignore separator or white space at the beginning of the string
if Builtins.issubstring(separator, character) == true ||
remove_whitespace == true &&
(character == " " || character == "\t")
index = Ops.add(index, 1)
next
# start of a quoted string
elsif character == "\""
state = :in_quoted_string
else
# start of a string
state = :in_string
if character == "\\\""
str = "\""
else
str = character
end
end
# after double quoted string - handle non-separator chars after double quote
elsif state == :in_quoted_string_after_dblqt
if Builtins.issubstring(separator, character) == true
ret = Builtins.add(ret, str) if !unique || !Builtins.contains(ret, str)
str = ""
state = :out_of_string
elsif character == "\\\""
str = Ops.add(str, "\"")
else
str = Ops.add(str, character)
end
elsif state == :in_quoted_string
if character == "\""
# end of quoted string
state = :in_quoted_string_after_dblqt
elsif character == "\\\""
str = Ops.add(str, "\"")
else
str = Ops.add(str, character)
end
elsif state == :in_string
if Builtins.issubstring(separator, character) == true
state = :out_of_string
str = CutBlanks(str) if remove_whitespace == true
ret = Builtins.add(ret, str) if !unique || !Builtins.contains(ret, str)
str = ""
elsif character == "\\\""
str = Ops.add(str, "\"")
else
str = Ops.add(str, character)
end
end
index = Ops.add(index, 1)
end
# error - still in quoted string
if state == :in_quoted_string || state == :in_quoted_string_after_dblqt
if state == :in_quoted_string
Builtins.y2warning(
"Missing trainling double quote character(\") in input: '%1'",
options
)
end
if unique == true
ret = Builtins.add(ret, str) if !Builtins.contains(ret, str)
else
ret = Builtins.add(ret, str)
end
end
# process last string in the buffer
if state == :in_string
str = CutBlanks(str) if remove_whitespace
if unique == true
ret = Builtins.add(ret, str) if !Builtins.contains(ret, str)
else
ret = Builtins.add(ret, str)
end
end
end
Builtins.y2debug("Parsed values: %1", ret)
deep_copy(ret)
end
# Remove first or every match of given regular expression from a string
#
# (e.g. CutRegexMatch( "abcdef12ef34gh000", "[0-9]+", true ) -> "abcdefefgh",
# CutRegexMatch( "abcdef12ef34gh000", "[0-9]+", false ) -> "abcdefef34gh000")
#
# @param [String] input string that might occur regex
# @param [String] regex regular expression to search for, must not contain brackets
# @param [Boolean] glob flag if only first or every occuring match should be removed
# @return [String] that has matches removed
def CutRegexMatch(input, regex, glob)
return "" if input.nil? || Ops.less_than(Builtins.size(input), 1)
output = input
if Builtins.regexpmatch(output, regex)
p = Builtins.regexppos(output, regex)
loop do
output = Ops.add(
Builtins.substring(output, 0, Ops.get_integer(p, 0, 0)),
Builtins.substring(
output,
Ops.add(Ops.get_integer(p, 0, 0), Ops.get_integer(p, 1, 0))
)
)
p = Builtins.regexppos(output, regex)
break unless glob
break unless Ops.greater_than(Builtins.size(p), 0)
end
end
output
end
# Function for escaping (replacing) (HTML|XML...) tags with their
# (HTML|XML...) meaning.
#
# Usable to present text "as is" in RichText.
#
# @param [String] text to escape
# @return [String] escaped text
def EscapeTags(text)
text = Builtins.mergestring(Builtins.splitstring(text, "&"), "&")
text = Builtins.mergestring(Builtins.splitstring(text, "<"), "<")
text = Builtins.mergestring(Builtins.splitstring(text, ">"), ">")
text
end
# Shorthand for select (splitstring (s, separators), 0, "")
# Useful now that the above produces a deprecation warning.
# @param [String] s string to be split
# @param [String] separators characters which delimit components
# @return first component or ""
def FirstChunk(s, separators)
l = Builtins.splitstring(s, separators)
Ops.get(l, 0, "")
end
# The 26 uppercase ASCII letters
def CUpper
@cupper
end
# The 26 lowercase ASCII letters
def CLower
@clower
end
# The 52 upper and lowercase ASCII letters
def CAlpha
@calpha
end
# Digits: 0123456789
def CDigit
@cdigit
end
# Hexadecimal digits: 0123456789ABCDEFabcdef
def CXdigit
@cxdigit
end
# The 62 upper and lowercase ASCII letters and digits
def CAlnum
@calnum
end
# The ASCII printable non-blank non-alphanumeric characters
def CPunct
@cpunct
end
# Printable ASCII charcters except whitespace, 33-126
def CGraph
@cgraph
end
# ASCII whitespace: SPACE CR LF HT VT FF
def CSpace
@cspace
end
# Printable ASCII characters including whitespace
def CPrint
@cprint
end
# Characters valid in a filename (not pathname).
# Naturally "/" is disallowed. Otherwise, the graphical ASCII
# characters are allowed.
# @return [String] for ValidChars
def ValidCharsFilename
Builtins.deletechars(CGraph(), "/")
end
# - hidden for documentation -
#
# Local function for finding longest records in the table.
#
# @param list <list <string> > table items
# @return list <integer> longest records by columns
def FindLongestRecords(items)
items = deep_copy(items)
longest = []
# searching all rows
Builtins.foreach(items) do |row|
# starting with column 0
col_counter = 0
# testing all columns on the row
Builtins.foreach(row) do |col|
col_size = Builtins.size(col)
# found longer record for this column
if Ops.greater_than(col_size, Ops.get(longest, col_counter, -1))
Ops.set(longest, col_counter, col_size)
end
# next column
col_counter = Ops.add(col_counter, 1)
end
end
deep_copy(longest)
end
# - hidden for documentation -
#
# Local function creates table row.
#
# @param list <string> row items
# @param list <integer> columns lengths
# @param integer record horizontal padding
# @return string padded table row
def CreateTableRow(row_items, cols_lenghts, horizontal_padding)
row_items = deep_copy(row_items)
cols_lenghts = deep_copy(cols_lenghts)
row = ""
col_counter = 0
records_count = Ops.subtract(Builtins.size(row_items), 1)
Builtins.foreach(row_items) do |record|
padding = Ops.get(cols_lenghts, col_counter, 0)
if Ops.less_than(col_counter, records_count)
padding = Ops.add(padding, horizontal_padding)
end
row = Ops.add(row, Pad(record, padding))
col_counter = Ops.add(col_counter, 1)
end
row
end
# - hidden for documentation -
#
# Local function returns underline string /length/ long.
#
# @param integer length of underline
# @return string /length/ long underline
def CreateUnderline(length)
underline = @base_underline
while Ops.less_than(Builtins.size(underline), length)
underline = Ops.add(underline, @base_underline)
end
underline = Builtins.substring(underline, 0, length)
underline
end
# - hidden for documentation -
#
# Local function for creating header underline for table.
# It uses maximal lengths of records defined in cols_lenghts.
#
# @param list <integer> maximal lengths of records in columns
# @param integer horizontal padding of records
# @return string table header underline
def CreateTableHeaderUnderline(cols_lenghts, horizontal_padding)
cols_lenghts = deep_copy(cols_lenghts)
col_counter = 0
# count of added paddings
records_count = Ops.subtract(Builtins.size(cols_lenghts), 1)
# total length of underline
total_size = 0
Builtins.foreach(cols_lenghts) do |col_size|
total_size = Ops.add(total_size, col_size)
# adding padding where necessary
if Ops.less_than(col_counter, records_count)
total_size = Ops.add(total_size, horizontal_padding)
end
col_counter = Ops.add(col_counter, 1)
end
CreateUnderline(total_size)
end
# Function creates text table without using HTML tags.
# (Useful for commandline)
# Undefined option uses the default one.
#
# @param [Array<String>] header
# @param [Array<Array<String>>] items
# @param [Hash{String => Object}] options
# @return [String] table
#
# Header: [ "Id", "Configuration", "Device" ]
# Items: [ [ "1", "aaa", "Samsung Calex" ], [ "2", "bbb", "Trivial Trinitron" ] ]
# Possible Options: horizontal_padding (for columns), table_left_padding (for table)
def TextTable(header, items, options)
header = deep_copy(header)
items = deep_copy(items)
options = deep_copy(options)
current_horizontal_padding = Ops.get_integer(
options,
"horizontal_padding",
2
)
current_table_left_padding = Ops.get_integer(
options,
"table_left_padding",
4
)
cols_lenghts = FindLongestRecords(Builtins.add(items, header))
# whole table is left-padded
table_left_padding = Pad("", current_table_left_padding)
# the last row has no newline
rows_count = Builtins.size(items)
table = ""
table = Ops.add(
Ops.add(
Ops.add(table, table_left_padding),
CreateTableRow(header, cols_lenghts, current_horizontal_padding)
),
"\n"
)
table = Ops.add(
Ops.add(
Ops.add(table, table_left_padding),
CreateTableHeaderUnderline(cols_lenghts, current_horizontal_padding)
),
"\n"
)
rows_counter = 1
Builtins.foreach(items) do |row|
table = Ops.add(
Ops.add(
Ops.add(table, table_left_padding),
CreateTableRow(row, cols_lenghts, current_horizontal_padding)
),
Ops.less_than(rows_counter, rows_count) ? "\n" : ""
)
rows_counter = Ops.add(rows_counter, 1)
end
table
end
# Function returns underlined text header without using HTML tags.
# (Useful for commandline)
#
# @param string header line
# @param integer left padding
# @return [String] underlined header line
def UnderlinedHeader(header_line, left_padding)
Ops.add(
Ops.add(
Ops.add(Ops.add(Pad("", left_padding), header_line), "\n"),
Pad("", left_padding)
),
CreateUnderline(Builtins.size(header_line))
)
end
# ////////////////////////////////////////
# sysconfig metadata related functions //
# ////////////////////////////////////////
# Get metadata lines from input string
# @param [String] input Input string - complete comment of a sysconfig variable
# @return [Array<String>] Metadata lines in list
def GetMetaDataLines(input)
return [] if input.nil? || input == ""
lines = Builtins.splitstring(input, "\n")
Builtins.filter(lines) { |line| Builtins.regexpmatch(line, "^##.*") }
end
# Get comment without metadata
# @param [String] input Input string - complete comment of a sysconfig variable
# @return [String] Comment used as variable description
def GetCommentLines(input)
return "" if input.nil? || input == ""
lines = Builtins.splitstring(input, "\n")
ret = ""
Builtins.foreach(lines) do |line|
com_line = Builtins.regexpsub(line, "^#([^#].*)", "\\1")
if com_line.nil?
# add empty lines
if Builtins.regexpmatch(line, "^#[ \t]*$") == true
ret = Ops.add(ret, "\n")
end
else
ret = Ops.add(Ops.add(ret, com_line), "\n")
end
end
ret
end
# Parse metadata from a sysconfig comment
# @param [String] comment comment of a sysconfig variable (single line or multiline string)
# @return [Hash] parsed metadata
def ParseSysconfigComment(comment)
ret = {}
# get metadata part of comment
metalines = GetMetaDataLines(comment)
joined_multilines = []
multiline = ""
Builtins.y2debug("metadata: %1", metalines)
# join multi line metadata lines
Builtins.foreach(metalines) do |metaline|
if Builtins.substring(
metaline,
Ops.subtract(Builtins.size(metaline), 1),
1
) != "\\"
if multiline != ""
# this not first multiline so remove comment mark
without_comment = Builtins.regexpsub(metaline, "^##(.*)", "\\1")
metaline = without_comment if !without_comment.nil?
end
joined_multilines = Builtins.add(
joined_multilines,
Ops.add(multiline, metaline)
)
multiline = ""
else
part = Builtins.substring(
metaline,
0,
Ops.subtract(Builtins.size(metaline), 1)
)
if multiline != ""
# this not first multiline so remove comment mark
without_comment = Builtins.regexpsub(part, "^##(.*)", "\\1")
part = without_comment if !without_comment.nil?
end
# add line to the previous lines
multiline = Ops.add(multiline, part)
end
end
Builtins.y2debug(
"metadata after multiline joining: %1",