-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathbuiltin.sh
More file actions
1618 lines (1402 loc) · 32.6 KB
/
builtin.sh
File metadata and controls
1618 lines (1402 loc) · 32.6 KB
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
#!/bin/bash
# Copyright 2018 Juliano Santos [SHAMAN]
#
# This file is part of bashsrc.
#
# bashsrc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# bashsrc 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 bashsrc. If not, see <http://www.gnu.org/licenses/>.
[ -v __BUILTIN_SH__ ] && return 0
if ! awk "BEGIN { exit ${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]} < 4.3 }"; then
echo "${0##*/}: erro: bashsrc requer o interpretador de comandos 'bash 4.3' ou superior." 1>&2
exit 1
fi
# Inicializa.
readonly __BUILTIN_SH__=1
# BASH (config)
shopt -s checkwinsize \
cmdhist \
complete_fullquote \
expand_aliases \
extglob \
extquote \
force_fignore \
histappend \
interactive_comments \
progcomp \
promptvars \
sourcepath
# Mapa de padrões e protótipos.
readonly -A __BUILTIN__=(
[objname]='[a-zA-Z_][a-zA-Z0-9_]*'
[vector]='\[(0|[1-9][0-9]*)?\]'
[varname]="^${__BUILTIN__[objname]}$"
[vartype]="^(${__BUILTIN__[objname]})(${__BUILTIN__[vector]})?$"
[slice]='^(\[((0|-?[1-9][0-9]*):?|:?(0|-?[1-9][0-9]*)|(0|-?[1-9][0-9]*):(0|-?[1-9][0-9]*))\])+$'
)
# __BUILTIN_TYPES__
#
# Tipos básicos que são validados automaticamente pela função 'getopt.parse'.
#
# Tipos: (bool, str, char, int, uint, float, var, array, map e function)
#
readonly -A __BUILTIN_TYPES__=(
[bool]='^(true|false)$'
[str]='^.*$'
[char]='^.$'
[int]='^(0|-?[1-9][0-9]*)$'
[uint]='^(0|[1-9][0-9]*)$'
[float]='^(0|-?[1-9][0-9]*)\.[0-9]+$'
# Tipos com validação condicional.
[var]=
[array]=
[map]=
[function]=
)
# __REF_TYPES__
#
# Determina os tipos básicos implementados por referência.
#
# XXX ATENÇÃO XXX
#
# É altamente recomendado manter a configuração padrão.
# Qualquer alteração pode comprometer todo ecossistema
# do 'bashsrc' e a implementação das funções nas
# bibliotecas existentes.
#
readonly -a __REF_TYPES__=(
var
array
map
function
)
# __BUILTIN_METHODS__
#
# Métodos implementados por padrão por todos os tipos.
#
readonly -a __BUILTIN_METHODS__=(
__imp__
__size__
__type__
__del__
__func__
__src__
__comp__
)
# Objetos/Tipos
declare -Ag __OBJ_INIT__ \
__SOURCE_TYPES__
# Tipos suportados
declare -g __ALL_TYPE_NAMES__=${!__BUILTIN_TYPES__[@]}' '${!__SOURCE_TYPES__[@]}
# .NAME
#
# builtin.sh
#
# .SYNOPSIS
#
# Implementa funções para inicialização e manipulação de objetos e tipos básicos.
#
# .DESCRIPTION
#
# A biblioteca 'builtin' é o coração do ecossistema 'bashsrc', através da qual
# os tipos são inicializados e gerenciados, cuja as funções e tipos não possuem
# composição, ou seja, o protótipo de declaração não é prefixada pela nomenclatura
# da biblioteca a qual pertence.
#
# Por padrão ela é e deve ser importada antes de qualquer outra biblioteca, seja em
# scripts ou outras bibliotecas afim de prover recursos, compatibilidade de objetos,
# tipos, protótipos, validações e etc.
#
# .VERSION
#
# 1.0.0
#
# .AUTHORS
#
# Juliano Santos [SHAMAN] <[email protected]>
#
# .FUNCTION var <obj[var]> ... <type[type]> -> [bool]
#
# Inicializa o objeto com o tipo especificado e implementa seus métodos.
#
# obj - O identificador do objeto. (Suporta array)
# type - Tipo do objeto a ser implementado.
#
# Obs: Pode ser especificado mais de um objeto na mesma instancia.
#
# == EXEMPLO ==
#
# # Inicializa um objeto do tipo 'var_t'
# var my_obj var_t
# my_obj='linux' # Atribuir valor
#
# # Chama método
# my_obj.upper
#
# == SAÍDA ==
# LINUX
#
# # Inicializar um array com '3' dimensões.
# var obj var_t[3]
# obj[0]='shell'
# obj[1]='script'
# obj[2]='LINUX'
#
# # Chamando métodos
# obj[0].upper
# obj[1].upper
# obj[2].lower
#
# == SAÍDA ==
# SHELL
# SCRIPT
# linux
#
function var()
{
local type var i func funcs method size proto methods reftypes
[[ ${*: -1} =~ ${__BUILTIN__[vartype]} ]] || error.fatal "'${*: -1}' erro de sintaxe"
# Extrai tipo e comprimento.
type=${BASH_REMATCH[1]}
size=${BASH_REMATCH[3]}
# Analisa sintaxe.
[[ -v __SOURCE_TYPES__[$type] ]] || error.fatal "'$type' tipo desconhecido"
# Tipos definidos
reftypes=${__REF_TYPES__[@]}' '${!__SOURCE_TYPES__[@]}
# Lista os identificadores.
for var in ${*:1:${#*}-1}; do
# Verifica identificador da variável.
[[ $var =~ ${__BUILTIN__[varname]} ]] || error.fatal "'$var' não é um identificador válido"
[[ -v __OBJ_INIT__[$var] ]] && error.fatal "'$var' o objeto já foi inicializado"
methods=()
for ((i=0; i < ${size:-1}; i++)); do
# Extrai as funções vinculadas ao tipo.
IFS='|' read _ funcs _ <<< ${__SOURCE_TYPES__[$type]}
for func in $funcs; do
# Define o nome do método com base no comprimento do tipo.
# Caso o tipo seja um array anexa o indíce do elemento ao
# identificador do método.
#
# Exemplo:
#
# var -> varname.method
# array -> varname[n].method
#
method=${var}${size:+[$i]}.${func#*.}
# Se há conflitos entre métodos implementados.
[[ $(type -t $method) == function ]] && error.fatal "conflito de método: '$method' o método já foi implementado"
# Verifica o protótipo da função para determinar o método de immplementação.
# Se o primeiro argumento da função for um tipo definido a implementação é realizada por 'referência',
# ou seja, a função irá receber o identificador do objeto implementado, caso contrário a função recebe
# o valor armazenado.
[[ $(declare -fp $func 2>/dev/null) =~ ${__GETOPT__[parse]}(${reftypes// /|})(\[[^]]*\])?: ]] &&
proto='%s(){ %s "%s" "$@"; return $?; }' || # referência
proto='%s(){ %s "${%s}" "$@"; return $?; }' # valor
# Implementa o método
printf -v proto "$proto" $method $func ${var}${size:+[$i]}
eval "$proto" 2>/dev/null || error.fatal "'$method' não foi possível implementar o método"
# Anexa o novo método.
methods+=($method)
# Define a função como somente-leitura protegendo o método
# implementado de uma chamada inválida.
readonly -f $func
done
done
# Funções (builtin)
#
# As funções builtin são implementas por todos os tipos (type_t) recebendo seu
# identificador literal (sem vetores).
for func in ${__BUILTIN_METHODS__[@]}; do
method=${var}.${func#.*}
[[ $(declare -fp $func 2>/dev/null) =~ ${__GETOPT__[parse]}(${reftypes// /|})(\[[^]]*\])?: ]] &&
proto='%s(){ %s "%s" "$@"; return $?; }' ||
proto='%s(){ %s "${%s}" "$@"; return $?; }'
printf -v proto "$proto" $method $func $var
eval "$proto" 2>/dev/null || error.fatal "'$method' não foi possível implementar o método"
methods+=($method)
readonly -f $func
done
# Registra a variável e define os seus atributos:
#
# * tipo
# * comprimento
# * métodos implementados
#
__OBJ_INIT__[$var]="$type|${size:-0}|${methods[*]}"
done
return $?
}
# .FUNCTION typedef <typename[str]> <func[str]> ... -> [bool]
#
# Define o tipo e os métodos de implementação.
#
# obj - Identificador do tipo.
# func - Identificador da função a ser implementada.
#
# Obs: Pode ser especificada mais de uma função.
#
# == EXEMPLO ==
#
# #!/bin/bash
#
# source builtin.sh
#
# # Criando as funções
# somar(){ echo $(($1+$2)); }
# subtrair(){ echo $(($1-$2)); }
# dividir(){ echo $(($1/$2)); }
# multiplicar() echo $(($1*$2)); }
#
# # Definindo o tipo 'calc_t' que implementa as funções aritméticas acima.
# typedef calc_t somar subtrair dividir multiplicar
#
# # Cria um objeto com o novo tipo.
# var num calc_t
#
# # Atribui o valor para operação.
# num=10
#
# # Chama cada método passando o valor armazenado em 'num' e executa a
# # respectiva operação arimética.
# num.somar 30
# num.subtrair 5
# num.dividir 2
# num.multiplicar 10
#
# == SAÍDA ==
#
# 40
# 5
# 5
# 100
#
function typedef()
{
getopt.parse -1 "typename:str:$1" "func:function:$2" ... "${@:3}"
local type srctypes src
type=$1
# Carrega os tipos já inicializados
srctypes=${!__SOURCE_TYPES__[@]}
# Verifica conflitos.
if [[ $type == @(${srctypes// /|}) ]]; then
IFS='|' read src _ <<< ${__SOURCE_TYPES__[$type]}
error.fatalf "conflito de tipos\n\ntipo: $type\n\nsource: ${BASH_SOURCE[-2]}\nsource: $src\n"
fi
# Registra/atualiza tipos suportados.
__SOURCE_TYPES__[$type]=${BASH_SOURCE[-1]}'|'${@:2}
__ALL_TYPE_NAMES__=${!__BUILTIN_TYPES__[@]}' '${!__SOURCE_TYPES__[@]}
return $?
}
# .FUNCTION del <obj[var]> ... -> [bool]
#
# Apaga da memória o objeto implementado.
# --
# Obs: Pode ser especificado mais de um objeto.
#
function del()
{
getopt.parse -1 "obj:var:$1" ... "${@:2}"
local __funcs__ __var__
for __var__ in $@; do
# Remove objeto da memória.
IFS='|' read _ _ __funcs__ _ <<< ${__OBJ_INIT__[$__var__]}
unset -f $__funcs__
unset $__var__ \
__OBJ_INIT__[$__var__] \
__SOURCE_TYPES__[$__var__]
done 2>/dev/null || error.fatal "'$__var__' não foi possível deletar o objeto"
return $?
}
# .FUNCTION len <obj[var]> -> [uint]|[bool]
#
# Retorna um inteiro sem sinal que representa o comprimento de uma
# cadeia de caracteres armazenados em 'obj'. Caso seja um array é
# retornado o total de elementos no container.
#
function len()
{
getopt.parse 1 "obj:var:$1" "${@:2}"
local -i __len__
local -n __ref__=$1
[[ $1 =~ ${__BUILTIN__[vector]} ]] &&
__len__=${#__ref__} ||
__len__=${#__ref__[@]}
echo $__len__
return $?
}
# .FUNCTION typeval <expr[str]> -> [str]|[bool]
#
# Retorna o tipo básico contido na expressão.
#
function typeval()
{
getopt.parse 1 "expr:str:$1" "${@:2}"
local type
for type in bool uint int float char str; do
[[ $1 =~ ${__BUILTIN_TYPES__[$type]} ]] && break
done
echo "$type"
return $?
}
# .FUNCTION typeof <obj[var]> -> [str]|[bool]
#
# Retorna o tipo do objeto.
#
function typeof()
{
getopt.parse 1 "obj:var:$1" "${@:2}"
local type
IFS='|' read type _ <<< ${__OBJ_INIT__[${1%[*}]}
echo "$type"
return $?
}
# .FUNCTION sizeof <obj[var]> -> [uint]|[bool]
#
# Retorna um inteiro sem sinal que indica o tamanho do objeto implementado.
# Se for '> 0' o objeto é um array.
#
function sizeof()
{
getopt.parse 1 "obj:var:$1" "${@:2}"
local -i size
IFS='|' read _ size _ <<< ${__OBJ_INIT__[${1%[*}]}
echo "$size"
return $?
}
# .FUNCTION assert <cond[str]> <error[str]> -> [str]|[bool]
#
# Testa a condição e dispara uma mensagem de erro caso seja falsa e interrompe
# a execução do programa com status '1'.
#
function assert()
{
getopt.parse 2 "cond:str:$1" "error:str:$2" "${@:3}"
[ $1 ] 2>/dev/null || error.fatal "$2"
return $?
}
# .FUNCTION iif <cond[str]> <true[str]> <false[str]> -> [str]|[bool]
#
# Testa a condição e retorna a expressão 'true' se for verdadeiro, caso
# contrário retorna a expressão 'false'.
#
function iif()
{
getopt.parse 3 "cond:str:$1" "true:str:$2" "false:str:$3" "${@:4}"
[ $1 ] 2>/dev/null && echo "$2" || echo "$3"
return $?
}
# .FUNCTION input <type[str]> <prompt[str]> -> [str]|[bool]
#
# Lê os dados da entrada padrão exibindo o prompt de inserção.
# Retorna nulo se o valor não satisfazer os critérios do tipo determinado.
# > São suportados somente os tipos básicos: char, str, int, uint, float ou bool.
#
# == EXEMPLO ==
#
# #!/bin/bash
#
# source builtin.sh
#
# # Lê os dados
# nome=$(input str 'nome:') <- Francisco
# idade=$(input uint 'idade:') <- 30f /* INVÁLIDO */
#
# # Imprimindo valores
# echo "Nome: " $nome
# echo "Idade: " $idade
#
# == SAÍDA ==
#
# Francisco
#
#
function input()
{
getopt.parse 2 "type:str:+:$1" "prompt:str:$2" "${@:3}"
[[ $1 != @(bool|str|char|int|uint|float) ]] && error.fatal "'$1' tipo básico desconhecido"
local val
read -rp "$2" val
[[ $val =~ ${__BUILTIN_TYPES__[$1]} ]] && echo "$val"
return $?
}
# .FUNCTION has <expr[str]> <substr[str]> -> [bool]
#
# Retorna true se 'expr' contém 'substr', caso contrário 'false'.
#
function has()
{
getopt.parse 2 "expr:str:$1" "substr:str:$2" "${@:3}"
[[ $1 == *$2* ]]
return $?
}
# .FUNCTION all <iterable[array]> <cond[str]> -> [bool]
#
# Retorna 'true' se todos os elementos em iterable satisfazer os critérios
# estabelecidos, caso contrário 'false'.
#
# > Utilize a variável '$?' para receber o elemento iterável.
# > Suporta todos os operadores lógicos. Para mais informações: 'man test'
# > Obs: Use aspas simples (') na passagem dos argumentos para suprimir
# a expansão da variável '$?'.
#
# == EXEMPLO ==
#
# source builtin.sh
#
# # Arquivos
# arqs=('/etc/group' '/etc/passwd' '/etc/shadow')
#
# # Verifica se todos os arquivos contidos na lista existem.
# if all arqs '-e $?'; then
# echo "Todos existem"
# else
# echo "Nem todos"
# fi
#
# == SAÍDA ==
#
# Todos existem
#
function all()
{
getopt.parse 2 "iterable:array:$1" "cond:str:$2" "${@:3}"
local -n __ref__=$1
local __iter__ __ret__
for __iter__ in "${__ref__[@]}"; do
[ ${2//$\?/$__iter__} ]
__ret__+="$?|"
done 2>/dev/null
return $((${__ret__%|}))
}
# .FUNCTION any <iterable[array]> <cond[str]> -> [bool]
#
# Retorna 'true' se pelo menos um elemento em iterable satisfazer o critério
# condicional estabelecido, caso contrário 'false'.
#
# > Utilize a variável '$?' para receber o elemento iterável.
# > Suporta todos os operadores lógicos. Para mais informações: 'man test'
# > Obs: Use aspas simples (') na passagem dos argumentos para suprimir
# a expansão prematura da variável '$?'.
#
function any()
{
getopt.parse 2 "iterable:array:$1" "cond:str:$2" "${@:3}"
local -n __ref__=$1
local __iter__
for __iter__ in "${__ref__[@]}"; do
[ ${2//$\?/$__iter__} ] && break
done 2>/dev/null
return $?
}
# .FUNCTION bin <num[int]> -> [str]|[bool]
#
# Retorna a representação binária de um inteiro.
#
# == EXEMPLO ==
#
# $ bin 27325
# 110101010111101
#
function bin()
{
getopt.parse 1 "num:int:$1" "${@:2}"
local i bit
for ((i=${1#-}; i > 0; i >>= 1)); do bit=$((i&1))$bit; done
echo ${1//[^-]/}${bit:-0}
return $?
}
# .FUNCTION swap <obj1[var]> <obj2[var]> -> [bool]
#
# Troca os valores entre 'obj1' e 'obj2'.
#
function swap()
{
getopt.parse 2 "obj1:var:$1" "obj2:var:$2" "${@:3}"
local -n __ref1__=$1 __ref2__=$2
local __tmp__=$__ref1__
__ref1__=$__ref2__
__ref2__=$__tmp__
return $?
}
# .FUNCTION sum <interable[array]> -> [int]|[bool]
#
# Soma todos os valores em 'iterable'. Elementos não numéricos são ignorados.
#
# == EXEMPLO ==
#
# $ nums=({10..100})
# $ sum nums
# 5005
#
function sum()
{
getopt.parse 1 "iterable:array:$1" "${@:2}"
local -n __ref__=$1
local __val__
printf -v __val__ '+%d' "${__ref__[@]}" 2>/dev/null
echo $((__val__))
return $?
}
# .FUNCTION fnfilter <iterable[array]> <func[function]> [str]|[bool]
#
# Executa a função filtro passando o elemento iterável e imprime somente
# se o retorno da função for 'true'.
#
# == EXEMPLO ==
#
# #!/bin/bash
#
# source builtin.sh
#
# # Função (filtro)
# func_iniciais()
# {
# # '$1' Contém o elemento atual na chamada da função.
#
# [[ $1 == J* ]] # Verifica se o nome inicia com a letra 'J'.
# return $? # Retorna o status da expressão condicional.
# }
#
# # Lista de nomes
# nomes=('Juliano' 'Francisco' 'Adriana' 'Janice' 'Jader' 'Maria')
#
# # Filtra o array
# fnfilter nomes func_iniciais
#
# == SAÍDA ==
#
# Juliano
# Janice
# Jader
#
function fnfilter()
{
getopt.parse 2 "iterable:array:$1" "func:function:$2" "${@:3}"
local -n __ref__=$1
local __iter__
for __iter__ in "${__ref__[@]}"; do
$2 "$__iter__" && echo "$__iter__"
done
return $?
}
# .FUNCTION chr <code[uint]> -> [char]|[bool]
#
# Retorna uma string unicode de um caractere ordinal.
#
function chr()
{
getopt.parse 1 "code:uint:$1" "${@:2}"
printf \\$(printf '%03o' $1)'\n'
return $?
}
# .FUNCTION ord <ch[char]> -> [uint]|[bool]
#
# Retorna código Unicode de um caractere.
#
function ord()
{
getopt.parse 1 "ch:char:$1" "${@:2}"
printf '%d\n' "'$1"
return $?
}
# .FUNCTION hex <num[int]> -> [str]|[bool]
#
# Retorna a representação hexadecimal de um inteiro.
#
function hex()
{
getopt.parse 1 "num:int:$1" "${@:2}"
printf '0x%x\n' $1
return $?
}
# .FUNCTION oct <num[int]> -> [int]|[bool]
#
# Retorna a representação octal de um inteiro.
#
function oct()
{
getopt.parse 1 "num:int:$1" "${@:2}"
printf '0%o\n' $1
return $?
}
# .FUNCTION htoi <hex[str]> -> [int]|[bool]
#
# Converte base hexadecimal para inteiro.
#
function htoi()
{
getopt.parse 1 "hex:str:$1" "${@:2}"
printf '%d\n' $1
return $?
}
# .FUNCTION btoi <bin[str]> -> [int]|[bool]
#
# Converte base binária para inteiro.
#
function btoi()
{
getopt.parse 1 "bin:str:$1" "${@:2}"
echo $((2#$1))
return $?
}
# .FUNCTION otoi <oct[str]> -> [int]|[bool]
#
# Converte base octal para inteiro.
#
function otoi()
{
getopt.parse 1 "oct:str:$1" "${@:2}"
echo $((8#$1))
return $?
}
# .FUNCTION range <start[int]> <stop[int]> <step[int]> -> [int]|[bool]
#
# Retorna uma sequência de inteiros entre 'start' e 'stop' com 'step' saltos.
#
function range()
{
getopt.parse 3 "start:int:$1" "stop:int:$2" "max:int:$3" "${@:4}"
local i op
[[ $3 -lt 0 ]] && op='>=' || op='<='
for ((i=$1; i $op $2; i=i+$3)); do echo $i; done
return $?
}
# .FUNCTION isobj <obj[var]> -> [bool]
#
# Retorna 'true' se a variável for um objeto implementado, caso contrário 'false'.
#
# == EXEMPLO ==
#
# source builtin.sh
#
# var obj var_t # Objeto
# obj=20
#
# num=10 # Variável
#
# isobj obj && echo true || echo false
# isobj num && echo true || echo false
#
# == SAÍDA ==
#
# true
# false
#
function isobj()
{
getopt.parse 1 "obj:var:$1" "${@:2}"
[[ -v __OBJ_INIT__[${1:--}] ]]
return $?
}
# .FUNCTION fnmap <iterable[array]> <func[function]> <args[str]> ... -> [bool]
#
# Executa a função passando o elemento iterável com 'N' args (opcional).
#
function fnmap()
{
getopt.parse -1 "iterable:array:$1" "func:function:$2" "args:str:$3" ... "${@:4}"
local -n __ref__=$1
local __iter__
for __iter__ in "${__ref__[@]}"; do
$2 "$__iter__" "${@:3}"
done
return $?
}
# .FUNCTION iter <obj[var]> <expr[str]> -> [bool]
#
# Converte a expressão delimitada por '\n' nova-linha em uma
# lista iterável apontada por 'obj'.
#
# == EXEMPLO ==
#
# source builtin.sh
#
# # Cria lista iterável.
# iter lista "$(< /etc/passwd)"
#
# # Exibindo a linha 10.
# echo ${lista[9]}
#
# == SAÍDA ==
#
# lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
#
function iter()
{
getopt.parse 2 "obj:var:$1" "expr:str:$2" "${@:3}"
mapfile -t $1 <<< "$2"
return $?
}
# .FUNCTION enum <iterable[array]> <start[int]> -> [str]|[bool]
#
# Enumera os elementos de uma lista iterável a partir de 'start'.
#
function enum()
{
getopt.parse 2 "iterable:array:$1" "start:int:$2" "${@:3}"
local -n __ref__=$1
local __iter__ __i__=$2
for __iter__ in "${__ref__[@]}"; do
echo "$((__i__++)) $__iter__"
done
return $?
}
# .FUNCTION listobj -> [str]|[bool]
#
# Retorna uma lista iterável com os objetos implementados no formato 'nome:tipo'.
#
function listobj()
{
getopt.parse 0 "$@"
local obj type objs
for obj in ${!__OBJ_INIT__[@]}; do
IFS='|' read type _ <<< ${__OBJ_INIT__[$obj]}
objs+=($obj:$type)
done
printf '%s\n' "${objs[@]}"
return $?
}
# .FUNCTION min <iterable[array]> -> [str]|[bool]
#
# Retorna o menor item em uma lista iterável.
#
function min()
{
getopt.parse 1 "iterable:array:$1" "${@:2}"
local -n __ref__=$1
local __iter__ __min__
__min__=${__ref__[0]}
for __iter__ in "${__ref__[@]}"; do
[[ $__iter__ < $__min__ ]] && __min__=$__iter__
done
echo "$__min__"
return $?
}
# .FUNCTION max <iterable[array]> -> [str]|[bool]
#
# Retorna o maior item em uma lista iterável.
#
function max()
{
getopt.parse 1 "iterable:array:$1" "${@:2}"
local -n __ref__=$1
local __iter__ __max__
__max__=${__ref__[0]}
for __iter__ in "${__ref__[@]}"; do
[[ $__iter__ > $__max__ ]] && __max__=$__iter__
done
echo "$__max__"
return $?
}
# .FUNCTION count <iterable[array]> -> [int]|[bool]
#
# Retorna o total de elementos em uma lista iterável.
#
function count()
{
getopt.parse 1 "iterable:array:$1" "${@:2}"
local -n __ref__=$1
echo ${#__ref__[@]}
return $?
}
# .FUNCTION reversed <iterable[array]> -> [str]|[bool]
#
# Inverter o iterador sobre os valores da sequência.
#
function reversed()
{
getopt.parse 1 "iterable:array:$1" "${@:2}"
local -n __ref__=$1
printf '%s\n' "${__ref__[@]}" | tac
return $?
}
# .FUNCTION unique <iterable[array]> -> [str]|[bool]
#
# Emite somente itens únicos em uma lista iterável.
#
function unique()
{
getopt.parse 1 "iterable:array:$1" "${@:2}"
local -n __ref__=$1
printf '%s\n' "${__ref__[@]}" | sort -du
return $?
}
# .FUNCTION sorted <iterable[array]> -> [str]|[bool]
#
# Retorna uma lista classificada do objeto iterável especificado.
# Cadeias contendo somente números são ordenadas numericamente, caso
# contrário são ordenadas alfabéticamente.
#
function sorted()
{
getopt.parse 1 "iterable:array:$1" "${@:2}"
local -n __ref__=$1
local __opt__ __re__
__re__='^(\s*[+-]?[0-9]+(.[0-9]+)?\s*)+$'
[[ ${__ref__[@]} =~ $__re__ ]] && __opt__=n
printf '%s\n' "${__ref__[@]}" | sort -${__opt__:-d}
return $?
}
# .FUNCTION isnull <obj[var]> -> [bool]
#
# Retorna 'true' se o valor de 'var' for nulo, caso contrário 'false'.
#
function isnull()
{
getopt.parse 1 "obj:var:$1" "${@:2}"
[[ -z ${!1} ]]
return $?
}