-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyp
2185 lines (1789 loc) · 90.2 KB
/
pyp
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
#!/usr/bin/env python
#version 2.12
#author tobyrosen@gmail.com
"""
Copyright (c) 2011, Sony Pictures Imageworks
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import optparse
import sys
import os
import time
import json
import glob
import tempfile
import datetime
import getpass
import re
#try to import user customized classes if they exist. default is null class.
try:
from PypCustom import PypCustom
except ImportError:
class PypCustom():
pass
try:
from PypCustom import PowerPipeListCustom
except ImportError :
class PowerPipeListCustom():
pass
try:
from PypCustom import PypStrCustom
except ImportError :
class PypStrCustom():
pass
try :
from PypCustom import PypListCustom
except ImportError:
class PypListCustom():
pass
try:
from PypCustom import PypFunctionCustom
except ImportError:
class PypFunctionCustom():
pass
class Colors(object):
'''defines basic color scheme'''
OFF = chr(27) + '[0m'
RED = chr(27) + '[31m'
GREEN = chr(27) + '[32m'
YELLOW = chr(27) + '[33m'
MAGENTA = chr(27) + '[35m'
CYAN = chr(27) + '[36m'
WHITE = chr(27) + '[37m'
BLUE = chr(27) + '[34m'
BOLD = chr(27) + '[1m'
COLORS = [OFF, RED, GREEN, YELLOW, MAGENTA, CYAN, WHITE, BLUE, BOLD]
class NoColors(object):
'''defines basic null color scheme'''
OFF = ''
RED = ''
GREEN =''
YELLOW = ''
MAGENTA = ''
CYAN = ''
WHITE =''
BLUE = ''
BOLD = ''
COLORS = [OFF, RED, GREEN, YELLOW, MAGENTA, CYAN, WHITE, BLUE, BOLD]
class PowerPipeList(list,PowerPipeListCustom):
'''
defines pp object, allows manipulation of entire input using python list methods
'''
def __init__(self, *args):
super(PowerPipeList, self).__init__(*args)
try:
PowerPipeListCustom.__init__(self)
except AttributeError:
pass
self.pyp = Pyp()
def divide(self, n_split):
'''
splits list into subarrays with n_split members
@param n_split: number of members produced by split
@type n_split: int
@return : new array split up by n_split
@rtype : list<str>
'''
sub_out = []
out = []
n = 0
pyp = Pyp()
inputs = self.pyp.flatten_list(self)
while inputs:
input = inputs.pop(0)
n = n + 1
sub_out.append(input)
if not n % n_split or not inputs:
out.append([sub_out])
sub_out = []
return out
def delimit(self, delimiter):
'''
splits up array based on delimited instead of newlines
@param delimiter: delimiter used for split
@type delimiter: str
@return: new string split by delimiter and joined by ' '
@rtype: list<str>
'''
return ' '.join(self.pyp.flatten_list(self)).split(delimiter)
def oneline(self,delimiter = ' '):
'''
combines list to one line with optional delimeter
@param delimiter: delimiter used for joining to one line
@type delimiter: str
@return: one line output joined by delimiter
@rtype: list<str>
'''
flat_list = self.flatten_list(self)
return delimiter.join(flat_list)
def uniq(self):
'''
returns only unique elements from list
@return: unique items
@rtype: list<str>
'''
strings= self.pyp.flatten_list(self)
return list(set(strings))
def flatten_list(self, iterables):
'''
returns a list of strings from nested lists
@param iterables: nested lists containing strs or PypStrs
@type iterables: list
@return: unnested list of strings
@rtype: list<str>
'''
return self.pyp.flatten_list(iterables)
def unlist(self):
'''
splits a list into one element per line
@param self: nested list
@type self: list<str>
@return: unnested list
@rtype: list<str>
'''
return self.pyp.flatten_list(self)
def after(self, target, after_n=1):
'''
consolidates after_n lines after matching target text to 1 line
@param target: target string to find
@type target: str
@param after_n: number of lines to consolidate
@type after_n: int
@return: list of after_n members
@rtype: list<str>
'''
out = []
n = 0
inputs = self.pyp.flatten_list(self)
for input in inputs:
n = n + 1
if target in input:
out.append([ [input] + inputs[n:n + after_n] ])
return out
def before(self, target, before_n=1):
'''
consolidates before_n lines before matching target text to 1 line
@param target: target string to find
@type target: str
@param before_n: number of lines to consolidate
@type before_n: int
@return: list of before_n members
@rtype: list<str>
'''
out = []
n = 0
inputs = self.pyp.flatten_list(self)
for input in inputs:
n = n + 1
if target in input:
out.append([ [input] + inputs[n - before_n - 1:n - 1] ])
return out
def matrix(self, target, matrix_n=1):
'''
consolidates matrix_n lines surrounding matching target text to 1 line
@param target: target string to find
@type target: str
@param matrix_n: number of lines to consolidate
@type matrix_n: int
@return: list of matrix_n members
@rtype: list<str>
'''
out = []
n = 0
inputs = self.pyp.flatten_list(self)
for input in inputs:
n = n + 1
if target in input:
out.append([ inputs[n - matrix_n - 1:n - 1] + [input] + inputs[n:n + matrix_n] ])
return out
class PypStr(str,PypStrCustom):
'''
defines p string object, allows manipulation of input line by line using python
string methods
'''
def __init__(self, *args):
super(PypStr, self).__init__()
try:
PypStrCustom.__init__(self)
except AttributeError:
pass
try:
self.dir = os.path.split(self.rstrip('/'))[0]
self.file = os.path.split(self)[1]
self.ext = self.split('.')[-1]
except:
pass
def trim(self,delim='/'):
'''
returns everything but the last directory/file
@param self: directory path
@type self: str
@return: directory path missing without last directory/file
@rtype: PypStr
'''
return PypStr(delim.join(self.split(delim)[0:-1]))
def kill(self, *args):
'''
replaces to_kill with '' in string
@param args: strings to remove
@type args : strs
@return: string without to_kill
@rtype: PypStr
'''
for arg in args:
self = self.replace(arg, '')
return PypStr(self)
def letters(self):
'''
returns only letters
@return: list of strings with only letters
@rtype: PypList
'''
new_string=''
for letter in list(self):
if letter.isalpha():
new_string = new_string + letter
else:
new_string = new_string + ' '
return [PypStr(x) for x in new_string.split() if x]
def punctuation(self):
'''
returns only punctuation
@return: list of strings with only punctuation
@rtype: PypList
'''
new_string=''
for letter in list(self):
if letter in """!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~""":
new_string = new_string + letter
else:
new_string = new_string + ' '
return [PypStr(x) for x in new_string.split() if x]
def digits(self):
'''
returns only digits
@return: list of string with only digits
@rtype: PypList
'''
new_string=''
for letter in list(self):
if letter.isdigit():
new_string = new_string + letter
else:
new_string = new_string + ' '
return [PypStr(x) for x in new_string.split() if x]
def clean(self,delim = '_'):
'''
returns a metacharater sanitized version of input. ignores underscores and slashes and dots.
@return: string with delim (default '_') replacing bad metacharacters
@rtype: PypStr
@param delim: delimeter to rejoin cleaned string with. default is "_"
@type delime: str
'''
for char in self:
if not char.isalnum() and char not in ['/','.',delim]:
self = self.replace(char, ' ')
return PypStr(delim.join([x for x in self.split() if x.strip()]))
def re(self,to_match):
'''
returns characters that match a regex using to_match
@return: portion of string that matches regex
@rtype: PypStr
@param to_match: regex used for matching
@type to_match: str
'''
match = re.search(to_match,self)
if match:
return PypStr(match.group(0))
else:
return ''
class PypList(list,PypListCustom):
'''
defines p list object, allows manipulation of input line by line using python
list methods
'''
def __init__(self, *args):
super(PypList, self).__init__(*args)
try:
PypListCustom.__init__(self)
except AttributeError:
pass
class Pyp(object):
'''
pyp engine. manipulates input stream using python methods
@ivar history: master record of all manipulations
@type history: dict<int:dict>
@ivar pwd: current directory
@type pwd: str
@ivar p: current input line being manipulated
@type p: str or list
@ivar n: current input line number
@type n: int
'''
def __init__(self):
self.history = {} #dictionary of all data organized input line by input line
try: #occasionally, python loses pwd info
self.pwd = os.getcwd()
except:
self.pwd =''
def get_custom_execute(self):
'''returns customized paths to macro files if they are setup'''
custom_ob = PypCustom()
custom_attrs = dir(custom_ob)
if 'custom_execute' in custom_attrs and custom_ob.custom_execute:
final_execute = custom_ob.custom_execute
else:
final_execute = self.default_final_execute
return final_execute
def default_final_execute(self,cmds):
for cmd in cmds:
os.system(cmd)
def get_custom_macro_paths(self):
'''returns customized paths to macro files if they are setup'''
home = os.path.expanduser('~')
custom_ob = PypCustom()
custom_attrs = dir(custom_ob)
if 'user_macro_path' in custom_attrs:
user_macro_path = custom_ob.user_macro_path
else:
user_macro_path = home + '/pyp_user_macros.json'
if 'group_macro_path' in custom_attrs:
group_macro_path = custom_ob.group_macro_path
else:
group_macro_path = home + '/pyp_group_macros.json'
return user_macro_path,group_macro_path
def cmds_split(self, cmds, macros):
'''
splits total commmand array based on pipes taking into account quotes,
parantheses and escapes. returns array of commands that will be processed procedurally.
Substitutes macros without executable commands.
@param cmds: user supplied command set
@type cmds: list<str>
@param macros: user defined marcros
@type macros: dict<str:dict>
@return: list of commands to be evaluated
@rtype: list<str>
'''
cmd_array = []
cmd = ''
open_single = False
open_double = False
open_parenth = 0
escape = False
letters = list(cmds)
while letters:
letter = letters.pop(0)
if cmd and cmd[-1] == '\\': escape = True
#COUNTS QUOTES
if letter == "'":
if open_single and not escape:
open_single = not open_single
else:
open_single = True
if letter == '"':
if open_double and not escape:
open_double = not open_double
else:
open_double = True
#COUNTS REAL PARANTHESES
if not open_single and not open_double:
if letter == '(' :
open_parenth = open_parenth + 1
if letter == ')':
open_parenth = open_parenth - 1
#MONEY MOVE--substitutes command for macro or starts building new command after adding command to cmd_array
if cmd.strip() in macros and letter in ['|', '[', '%', ',', '+', ' ']:
cmd = cmd.strip()
letters = list('|'.join(macros[cmd]['command']) + letter + ''.join(letters))
cmd = ''
elif letter == '|' and not open_single and not open_double and not open_parenth:#
cmd_array.append(cmd)
cmd = ''
else:
cmd = cmd + letter
escape = False
#for last command, either recursively run cmd_split or add last command to array
if cmd.strip() in macros and not options.macro_save_name: #allows macro be split and also to be correctly overwritten
return self.cmds_split('|'.join(cmd_array + macros[cmd]['command']), macros) #this is by definition the last cmd.
else:
cmd_array.append(cmd) #gets last cmd
return [x for x in cmd_array if x]
def load_macros(self,macro_path):
'''
loads macro file; returns macros dict
@param macro_path: file path to macro file
@type macro_path: str
@return: dictionary of user defined macros
@rtype: dict<str:dict>
'''
#macro_path = self.macro_path
if os.path.exists(macro_path):
macro_ob = open(macro_path)
macros = json.load(macro_ob)
macro_ob.close()
else:
macros = {}
return macros
def write_macros(self, macros,macro_path, cmds):
'''
writes macro file
@param macros: dictionary of user defined macros
@type macros: dict<str:dict>
@param macro_path: file path to macro file
@type macro_path: str
@param cmds: commands to be saved as a macro
@type cmds: list<str>
'''
if options.macro_save_name:
macro = options.macro_save_name
macro_name = macro.split('#')[0].strip()
macros[macro_name] = {}
macros[macro_name]['command'] = cmds
macros[macro_name]['user'] = getpass.getuser()
macros[macro_name]['date'] =str(datetime.datetime.now()).split('.')[0]
if '#' in macro: #deals with comments
macros[macro_name]['comments'] = '#' + macro.split('#')[1].strip()
else:
macros[macro_name]['comments'] = ''
macro_ob = open(macro_path, 'w')
json.dump(macros, macro_ob)
macro_ob.close()
self.load_macros(macro_path)
if macro_name in macros:
print Colors.YELLOW + macro_name , "successfully saved!" + Colors.OFF
sys.exit()
else:
print Colors.RED + macro_name, 'was not saved...unknown error!' + Colors.OFF
sys.exit(1)
def delete_macros(self, macros,macro_path):
'''
deletes macro from file
@param macros: dictionary of user defined macros
@type macros: dict<str:dict>
@param macro_path: file path to macro file
@type macro_path: str
'''
if options.macro_delete_name:
if options.macro_delete_name in macros:
del macros[options.macro_delete_name]
json_ob = open(macro_path, 'w')
json.dump(macros, json_ob)
json_ob.close()
print Colors.MAGENTA + options.macro_delete_name + " macro has been successfully obliterated" + Colors.OFF
sys.exit()
else:
print Colors.RED + options.macro_delete_name + " does not exist" + Colors.OFF
sys.exit(1)
def list_macros(self, macros):
'''
prints out formated macros, takes dictionary macros as input
@param macros: dictionary of user defined macros
@type macros: dict<str:dict>
'''
if options.macro_list or options.macro_find_name:
macros_sorted = [x for x in macros]
macros_sorted.sort()
for macro_name in macros_sorted:
if options.macro_list or options.macro_find_name in macro_name or options.macro_find_name in macros[macro_name]['user']:
print Colors.MAGENTA + macro_name + '\n\t ' + Colors.YELLOW+macros[macro_name]['user'] \
+ '\t' + macros[macro_name]['date']\
+'\n\t\t' + Colors.OFF + '"'\
+ '|'.join(macros[macro_name]['command']) + '"' + Colors.GREEN + '\n\t\t'\
+ macros[macro_name].get('comments', '') + Colors.OFF + '\n'
sys.exit()
def load_file(self):
'''
loads file for pyp processing
@return: file data
@rtype: list<str>
'''
if options.text_file:
if not os.path.exists(options.text_file):
print Colors.RED + options.text_file + " does not exist" + Colors.OFF
sys.exit()
else:
f = [x.rstrip() for x in open(options.text_file) ]
return f
else:
return []
def shell(self, command):
'''
executes a shell commands, returns output in array sh
@param command: shell command to be evaluated
@type command: str
@return: output of shell command
@rtype: list<str>
'''
sh = [x.strip() for x in os.popen(command).readlines()]
return sh
def shelld(self, command, *args):
'''
executes a shell commands, returns output in dictionary based on args
@param command: shell command to be evaluated
@type command: str
@param args: optional delimiter. default is ":".
@type args: list
@return: hashed output of shell command based on delimiter
@rtype: dict<str:str>
'''
if not args:
ofs = ':'
else:
ofs = args[0]
shd = {}
for line in [x.strip() for x in os.popen(command).readlines()]:
try:
key = line.split(ofs)[0]
value = ofs.join(line.split(ofs)[1:])
shd[key] = value
except IndexError:
pass
return shd
def rekeep(self,to_match):
'''
keeps lines based on regex string matches
@param to_match: regex
@type to_match: str
@return: True if any of the strings match regex else False
@rtype: bool
'''
match = []
flat_p = self.flatten_list(self.p)
for item in flat_p:
if re.search(to_match,item):
match.append(item)
if match:
return True
else:
return False
def relose(self,to_match):
'''
loses lines based on regex string matches
@param to_match: regex
@type to_match: str
@return: False if any of the strings match regex else True
@rtype: bool
'''
return not self.rekeep(to_match)
def keep(self,*args):
'''
keeps lines based on string matches
@param args: strings to search for
@type args: list<str>
@return: True if any of the strings are found else False
@rtype: bool
'''
kept = []
for arg in args:
flat_p = self.flatten_list(self.p)
for item in flat_p:
if arg in item:
kept.append(arg)
if kept:
return True
else:
return False
def lose(self,*args):
'''
removes lines based on string matches
@param args: strings to search for
@type args: list<str>
@return: True if any of the strings are not found else False
@rtype: bool
'''
return not self.keep(*args)
def array_tracer(self, input,power_pipe=''):
'''
generates colored, numbered output for lists and dictionaries and other types
@param input: one line of input from evaluted pyp command
@type input: any
@param power_pipe: Output from powerpipe (pp) evaluation
@type power_pipe: bool
@return: colored output based on input contents
@rtype: str
'''
if not input and input is not 0: #TRANSLATE FALSES TO EMPTY STRINGS OR ARRAYS. SUPPLIES DUMMY INPUT TO KEEP LINES IF NEEDED.
if options.keep_false or power_pipe:
input = ' '
else:
return ''
#BASIC VARIABLES
nf = 0
output = ''
if power_pipe:
n_index = Colors.MAGENTA + '[%s]' % (self.n) + Colors.GREEN
final_color = Colors.OFF
else:
n_index = ''
final_color=''
#DEALS WITH DIFFERENT TYPES OF INPUTS
if type(input) in [ list, PypList, PowerPipeList] :#deals with lists
for field in input:
if not nf == len(input):
if type(field) in [str, PypStr]:
COLOR = Colors.GREEN
else:
COLOR = Colors.MAGENTA
output = str(output) + Colors.BOLD + Colors.BLUE + "[%s]" % nf + Colors.OFF + COLOR + str(field) + Colors.GREEN
nf = nf + 1
return n_index + Colors.GREEN + Colors.BOLD + '[' + Colors.OFF + output + Colors.GREEN + Colors.BOLD + ']' + Colors.OFF
elif type(input) in [str, PypStr] :
return n_index + str(input) + final_color
elif type(input) in [int, float] :
return n_index + Colors.YELLOW + str(input) + Colors.OFF
elif type(input) is dict: #deals with dictionaries
for field in sorted(input,key=lambda x : x.lower()):
output = output + Colors.OFF + Colors.BOLD + Colors.BLUE + field + Colors.GREEN + ": " + Colors.OFF + Colors.GREEN + str(input[field]) + Colors.BOLD + Colors.GREEN + ',\n '
return n_index + Colors.GREEN + Colors.BOLD + '{' + output.strip().strip(' ,') + Colors.GREEN + Colors.BOLD + '}' + Colors.OFF
else: #catches every else
return n_index + Colors.MAGENTA + str(input) + Colors.OFF
def cmd_split(self, cmds):
'''
takes a command (as previously split up by pipes and input as array cmds),
and returns individual terms (cmd_array) that will be evaluated individually.
Also returns a string_format string that will be used to stitch together
the output with the proper spacing based on the presence of "+" and ","
@param cmds: individual commands separated by pipes
@type cmds: list<str>
@return: individual commands with corresponding string format
@rtype: list<str>
'''
string_format = '%s'
cmd_array = []
cmd = ''
open_quote = False
open_parenth = 0
open_bracket = 0
for letter in cmds:
if letter in [ "'" , '"']:
if cmd and cmd[-1] == '\\':
open_quote = True
else:
open_quote = not open_quote
if not open_quote: #this all ignores text in () or [] from being split by by , or +
if letter == '(' :
open_parenth = open_parenth + 1
elif letter == ')':
open_parenth = open_parenth - 1
elif letter == '[' :
open_bracket = open_bracket + 1
elif letter == ']':
open_bracket = open_bracket - 1
if not open_parenth and not open_bracket and letter in [',', '+']: #these are actual formatting characters
cmd_array.append(cmd)
cmd = ''
string_format = string_format + letter.replace('+', '%s').replace(',', ' %s')
continue
cmd = cmd + letter
cmd_array.append(cmd)
output = [(cmd_array, string_format)]
return output
def all_meta_split(self, input_str):
'''
splits a string on any metacharacter
@param input_str: input string
@type input_str: str
@return: list with no metacharacters
@rtype: list<str>
'''
for char in input_str:
if not char.isalnum():
input_str = input_str.replace(char, ' ')
return [x for x in input_str.split() if x.strip()]
def string_splitter(self):
'''
splits self.p based on common metacharacters. returns a
dictionary of this information.
@return: input split up by common metacharacters
@rtype: dict<str:list<str>>
'''
whitespace =self.p.split(None)
slash =self.p.split('/')
underscore =self.p.split('_')
colon =self.p.split(':')
dot =self.p.split('.')
minus =self.p.split('-')
all= self.all_meta_split(self.p)
comma = self.p.split(',')
split_variables_raw = {
'whitespace' :whitespace,
'slash' :slash,
'underscore' :underscore,
'colon' :colon,
'dot' :dot,
'minus' :minus,
'all' : all,
'comma' : comma,
'w' :whitespace,
's' :slash,
'u' :underscore,
'c' :colon,
'd' :dot,
'm' :minus,
'a' : all,
'mm' : comma,
}
#gets rid of empty fields
split_variables = dict((x, PypList([PypStr(y) for y in split_variables_raw[x]])) for x in split_variables_raw)
return split_variables
def join_and_format(self, join_type):
'''
joins self.p arrays with a specified metacharacter
@param join_type: metacharacter to join array
@type join_type: str
@return: string joined by metacharacter
@rtype: str
'''
temp_joins = []
derived_string_format = self.history[self.n]['string_format'][-1]
len_derived_str_format = len(derived_string_format.strip('%').split('%'))
if len(self.p) == len_derived_str_format:
string_format = derived_string_format #normal output
for sub_p in self.p:
if type(sub_p) in [list, PypList]:
temp_joins.append(join_type.join(sub_p))
else: #deals with printing lists and strings
temp_joins.append(sub_p)
return PypStr(string_format % tuple(temp_joins))
else: #deals with piping pure arrays to p
return PypStr(join_type.join(PypStr(x)for x in self.p))
def array_joiner(self):
'''
generates a dict of self.p arrays joined with various common metacharacters
@return: input joined by common metacharacters
@rtype: dict<str:str>
'''
whitespace = self.join_and_format(' ')
slash = self.join_and_format(os.sep)
underscore = self.join_and_format('_')
colon = self.join_and_format(':')
dot = self.join_and_format('.')
minus = self.join_and_format('-')
all = self.join_and_format(' ')
comma = self.join_and_format(',')
join_variables = {
'w' : whitespace,
's' : slash,
'u' : underscore,
'c' : colon,
'd' : dot,
'm' : minus,
'a' : all,
'mm' : comma,
'whitespace' : whitespace,
'slash' : slash,
'underscore' : underscore,
'colon' : colon,
'dot' : dot,
'minus' : minus,
'all' : all,
'comma' : comma
}
return join_variables
def translate_preset_variables(self, translate_preset_variables,file_input, second_stream_input):
'''
translates variables to protected namespace dictionary for feeding into eval command.
@param file_input: data from file
@type file_input: list
@param second_stream_input: input from second stream
@type second_stream_input: list<str>
@return: values of preset variable for direct use by users
@rtype: dict<str:str>
'''
#generic variables
presets = {
'n' : self.kept_n,
'on' : self.n,
'fpp' : file_input,
'spp' : second_stream_input,
'nk': 1000 + self.kept_n,
'shell': self.shell,
'shelld' : self.shelld,
'keep': self.keep,
'lose': self.lose,
'k': self.keep,
'l':self.lose,
'rekeep':self.rekeep,
'relose':self.relose,
'rek':self.rekeep,
'rel':self.relose,
'quote': '"',
'apost':"'",
'qu':'"',
'dollar': '$',
'pwd': self.pwd,
'date': datetime.datetime.now(),
'env': os.environ.get,
'glob' : glob.glob,
'letters': 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'digits': '0123456789',
'punctuation': """!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~""",
'str':(PypStr),
}
#removes nested entries from history
history = []
for hist in self.history[self.n]['history']:
if type(hist) in (list,PypList):
hist = self.unlist_p(hist)
history.append(hist)
presets['history'] = presets['h'] = history
# file
if options.text_file:
try:
fp = file_input[self.n]
except IndexError:
fp = ''
presets['fp'] = fp
# second stream
try:
sp = second_stream_input[self.n]
except IndexError:
sp = ''
presets['sp'] = sp
#original input
if self.history[self.n]['output']:
presets['o'] = self.history[self.n]['history'][0]
else:
presets['o'] = ''
presets['original'] = presets['o']