-
Notifications
You must be signed in to change notification settings - Fork 40
/
sedsed
1506 lines (1302 loc) · 49.9 KB
/
sedsed
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
# sedsed - the SED mastering script
# Since 27 November 2001, by Aurelio Marinho Jargas
# For ChangeLog and Documentation, see http://sedsed.sf.net
import sys, re, os, getopt, string, tempfile
myname = 'sedsed'
myversion = '1.0'
myhome = 'http://sedsed.sf.net'
#-------------------------------------------------------------------------------
# User Configuration
#-------------------------------------------------------------------------------
# Default config - Changeable, but you won't need to do it
sedbin = 'sed' # name (or full path) of the sed program
color = 1 # colored output or not? (--color, --nocolor)
dump_debug = 0 # dump debug script to screen? (--dump-debug)
indent_prefix = ' '*4 # default indent prefix for blocks (--prefix)
debug_prefix = '\t\t' # default prefix for debug commands
action = 'indent' # default action if none specified (-d,-i,-t,-H)
DEBUG = 0 # set developper's debug level [0-3]
EMUDEBUG = 0 # emulator have it's own debug [0-3]
# HTML colors for --htmlize
# You may edit here to change the default colors
html_colors = {
'addr1' : '#8080ff',
'addr1flag': '#ff6060',
'addr2' : '#8080ff',
'addr2flag': '#ff6060',
'lastaddr' : '',
'modifier' : '#ff6060',
'id' : '#ffff00',
'content' : '#ff00ff',
'delimiter': '#ff6060',
'pattern' : '#8080ff',
'replace' : '',
'flag' : '#00ff00',
'extrainfo': '',
'comment' : '#00ffff',
'escape' : '#ff6060',
'special' : '#00ff00',
'pattmeta' : '#ff00ff',
'plaintext': '',
'branch' : '',
'BGCOLOR' : '#000000',
'TEXT' : '#ffffff',
'LINK' : '#ff00ff',
'ALINK' : '#ff00ff',
'VLINK' : '#ff00ff'
}
#-------------------------------------------------------------------------------
# General Functions
#-------------------------------------------------------------------------------
def printUsage(exitcode=1):
print """
Usage: sedsed OPTION [-e sedscript] [-f sedscriptfile] [inputfile]
OPTIONS:
-f, --file add file contents to the commands to be parsed
-e, --expression add the script to the commands to be parsed
-n, --quiet suppress automatic printing of pattern space
--silent alias to --quiet
-d, --debug debug the sed script
--hide hide some debug info (options: PATT,HOLD,COMM)
--color shows debug output in colors (default: ON)
--nocolor no colors on debug output
--dump-debug dumps to screen the debugged sed script
--emu emulates GNU sed (INCOMPLETE)
--emudebug emulates GNU sed debugging the sed script (INCOMPLETE)
-i, --indent script beautifier, prints indented and
one-command-per-line output do STDOUT
--prefix indent prefix string (default: 4 spaces)
-t, --tokenize script tokenizer, prints extensive
command by command information
-H, --htmlize converts sed script to a colorful HTML page
-V, --version prints the program version and exit
-h, --help prints this help message and exit
NOTE: The --emu and --emudebug options are still INCOMPLETE and must
be used with care. Mainly regexes and address $ (last line)
are not handled right by the emulator.
"""
print "Homepage: %s\n"%myhome
sys.exit(exitcode)
def Error(msg):
"All error messages are handled by me"
print 'ERROR:',msg ; sys.exit(1)
def echo(msg): print "\033[33;1m%s\033[m"%msg
def Debug(msg, level=1):
if DEBUG and DEBUG >= level: print '+++ DEBUG%d: %s'%(level,msg)
def read_file(file):
"Reads a file into a list, removing line breaks"
if file == '-':
try: data = sys.stdin.readlines()
except: Error('I was expecting data on STDIN!')
else:
try: f = open(file); data = f.readlines() ; f.close()
except: Error("Cannot read file: %s"%file)
return map(lambda x:re.sub('[\n\r]+$','',x), data)
def write_file(file, lines=[]):
"Writes a list contents into file, adding correct line breaks"
try: f = open(file, 'wb')
except: Error("Cannot open file for writing: %s"%file)
#TODO maybe use os.linesep? - all this is really necessary?
# ensuring line break
lines = map(lambda x:re.sub('\n$','',x)+'\n', lines)
f.writelines(lines); f.close()
def runCommand(cmd): # Returns a (#exit_code, program_output[]) tuple
#TODO dont use popen()
list = [] ; fd = os.popen(cmd)
for line in fd.readlines():
list.append(string.rstrip(line)) # stripping \s*\n
ret = fd.close()
if ret: ret = ret/256 # 16bit number
return ret, list
#-------------------------------------------------------------------------------
# Command line & Config
#-------------------------------------------------------------------------------
# Here's all the valid command line options
short_options = 'he:f:ditVHn'
long_options = [
'debug', 'tokenize', 'htmlize', 'indent', # actions
'version', 'help', 'file=', 'expression=', 'silent', 'quiet', # sed-like
'nocolor', 'color', 'hide=', 'prefix=', 'emu', 'emudebug', # misc
'dump-debug', # other
'_debuglevel=','_emudebuglevel=','_stdout-only', 'dumpcute'] # admin
# Check it!
try: opt, args = getopt.getopt(sys.argv[1:], short_options, long_options)
except getopt.error, errmsg: Error("%s (try --help)"%errmsg)
# Turn color OFF on Windows because ANSI.SYS is not installed by default.
# Windows users who have ANSY.SYS configured, can use the --color option
# or comment the following line.
# ANSY.SYS ressources:
# http://www.evergreen.edu/biophysics/technotes/program/ansi_esc.htm#notes
# http://www3.sympatico.ca/rhwatson/dos7/v-ansi-escseq.html
if os.name == 'nt': color = 0
# Command Line is OK, now let's parse its values
action_modifiers = [] # --hide contents and others
sedscript = [] # join all scripts found here
script_file = '' # old sedscript filename for --htmlize
quiet_flag = 0 # tell if the #n is needed or not
for o in opt:
if o[0] in ('-d', '--debug') : action = 'debug'
elif o[0] in ('-i', '--indent') : action = 'indent'; color = 0
elif o[0] in ('-t', '--tokenize') : action = 'token' ; color = 0
elif o[0] in ('-H', '--htmlize') : action = 'html' ; color = 0
elif o[0] in ('-n', '--quiet') : quiet_flag = 1
elif o[0] in ('-e', '--expression'): sedscript.append(o[1])
elif o[0] in ('-f', '--file') :
sedscript.extend(read_file(o[1]))
script_file = o[1]
elif o[0] in ('-h', '--help') : printUsage(0)
elif o[0] in ('-V', '--version') :
print '%s v%s'%(myname,myversion)
sys.exit(0)
elif o[0] == '--emu' : action = 'emu'
elif o[0] == '--emudebug' : action = 'emudebug'
elif o[0] == '--dump-debug': action = 'debug' ; dump_debug=1 ; color=0
elif o[0] == '--nocolor' : color = 0
elif o[0] == '--color' : color = 1
elif o[0] == '--hide': # get hide options
for hide in string.split(o[1], ','): # save as no<OPT>
hide_me = string.lower(string.strip(hide))
action_modifiers.append('no'+hide_me)
elif o[0] == '--prefix':
if re.sub('\s', '', o[1]): # prefix is valid?
Error("--prefix: must be spaces and/or TABs")
indent_prefix = o[1]
# not documented admin options
elif o[0] == '--_debuglevel' : DEBUG = int(o[1])
elif o[0] == '--_emudebuglevel': EMUDEBUG = int(o[1])
elif o[0] == '--_stdout-only':
action = 'debug'
action_modifiers.append(o[0][2:])
elif o[0] == '--dumpcute':
action = 'dumpcute'; DEBUG = 0; color = 1
# Now all Command Line options were sucessfuly parsed
#-------------------------------------------------------------------------------
# Sanity Checkings
#-------------------------------------------------------------------------------
# There's a SED script?
if not sedscript:
if args: # the script is the only argument (echo | sed 's///')
sedscript.append(args.pop(0))
else: # :(
Error("there's no SED script to parse! (try --help)")
# Get all text files, if none, use STDIN (-)
textfiles = args or ['-']
# On --debug, check the given script syntax, runnig SED with it.
# We will not debug a broken script.
#XXX there is a problem with popen() and win9x machines
# so i'm skipping this check for those machines
#TODO redo this check using !runCommand
if action == 'debug' and os.name != 'nt':
tmpfile = tempfile.mktemp()
write_file(tmpfile, sedscript)
ret, msg = runCommand("%s -f '%s' /dev/null"%(sedbin,tmpfile))
if ret:
msg = 'syntax error on your SED script, please fix it before.'
Error('#%d: %s' % (ret,msg))
os.remove(tmpfile)
#-------------------------------------------------------------------------------
# Internal Config Adjustments and Magic
#-------------------------------------------------------------------------------
# Add the leading #n to the sed script, when using -n
if quiet_flag: sedscript.insert(0, '#n')
# Add the terminal escapes for color (or not)
if color:
color_YLW = '\033[33;1m' # yellow text
color_RED = '\033[31;1m' # red text
color_REV = '\033[7m' # reverse video
color_NO = '\033[m' # back to default
else:
color_YLW = color_RED = color_REV = color_NO = ''
### The SED debugger magic lines
#
# Here is where the 'magic' lives. The heart of this program are the
# following lines, which are the special SED commands responsable for
# the DEBUG behaviour. For *each* command of the original script,
# several commands are added before, to show buffers and command
# contents. Some tricks are needed to preserve script's original
# behaviour, they are explained ahead.
#
# 1. Show PATTERN SPACE contents:
# The 'PATT:' prefix is added, then the 'l' command shows the
# buffer contents, then the prefix is removed.
#
# 2. Show HOLD SPACE contents:
# Similar to PATTERN SPACE, but use the 'x' command to access and
# restore the HOLD buffer contents. The prefix used is 'HOLD:'.
#
# 3. Show current SED COMMAND:
# Uses a single 'i' command to show the full 'COMM:' line, as it
# does not depend on execution data. The color codes are added or
# not, depending on user options.
#
# 4. 'Last Address' trick:
# On SED, the empty address // refers to the last address matched.
# As this behaviour can be affected when several DEBUG lines are
# inserted before the command, sedsed uses a trick to force it.
# The last address used on the original script is repeated with a
# null command (/last-address/ y/!/!/). This way sedsed repeat the
# addressing, ensuring the next command will have it as the right
# 'last' address.
#
# 5. 't Status' trick:
# The 't' command behaviour, from SED manual page:
#
# If a s/// has done a successful substitution since the last
# input line was read and since the last t command, then branch
# to label
#
# As all the DEBUG commands use lots of 's///' commands, the 't'
# status is always true. The trick here is to add fake labels
# between *any* command and fake 't' commands to jump to them:
#
# <last command, possibly s///>
# t zzset001
# ... debug commands ...
# t zzclr001
# : zzset001
# ... debug commands ...
# : zzclr001
# <next command, possibly t>
#
# The DEBUG commands are repeated and placed into two distinct
# blocks: 'zzset' and 'zzclr', which represents the 't' status
# of the last command. The execution order follows:
#
# zzset: 1st jump (t), then debug (s///), t status is ON
# zzclr: 1st debug (s///), then jump (t), t status is OFF
#
# The 001 count is incremented on each command to have unique
# labels.
#
#
# --- THANK YOU VERY MUCH ---
#
# - Paolo Bonzini (GNU sed 4.x maintainer) for the idea of the
# 't status' trick.
#
# - Thobias Salazar Trevisan for the idea of using the 'i'
# command for the COMM: lines.
#
# show pattern space, show hold space, show sed command
# null sed command to restore last address, 't' status trick
showpatt = [ 's/^/PATT:/', 'l', 's/^PATT://' ]
showhold = ['x', 's/^/HOLD:/', 'l', 's/^HOLD://', 'x']
showcomm = ['i\\','COMM:%s\a%s'%(color_YLW, color_NO)]
nullcomm = ['y/!/!/']
save_t = ['t zzset\a\n#DEBUG#', 't zzclr\a',
':zzset\a\n#DEBUG#' , ':zzclr\a' ]
def format_debugcmds(cmds):
"One per line, with prefix (spaces)"
return debug_prefix + string.join(cmds, '\n'+debug_prefix) + '\n'
showpatt = format_debugcmds(showpatt)
showhold = format_debugcmds(showhold)
save_t = format_debugcmds(save_t )
showcomm = debug_prefix+string.join(showcomm, '\n')+'\n'
nullcomm = nullcomm[0]
# If user specified --hide, unset DEBUG commands for them
if action_modifiers.count('nopatt'): showpatt = '' # don't show!
if action_modifiers.count('nohold'): showhold = '' # don't show!
if action_modifiers.count('nocomm'): showcomm = '' # don't show!
# Compose HTML page header and footer info for --htmlize.
# The SCRIPTNAME is added then removed from html_colors for
# code convenience only.
#
html_colors['SCRIPTNAME'] = os.path.basename(script_file)
html_data = {
'header': """\
<html>
<head><meta name="Generator" content="sedsed --htmlize">
<title>Colorized %(SCRIPTNAME)s</title></head>
<body bgcolor="%(BGCOLOR)s" text="%(TEXT)s"
link="%(LINK)s" alink="%(ALINK)s" vlink="%(VLINK)s">
<pre>
"""%html_colors,
'footer': """
<font color="%s"><b>### colorized by <a \
href="http://sedsed.sf.net">sedsed</a>, a SED script \
debugger/indenter/tokenizer/HTMLizer</b></font>\n
</pre></body></html>\
"""%html_colors['comment']
}
del html_colors['SCRIPTNAME']
#-------------------------------------------------------------------------------
# SED Machine Data
#-------------------------------------------------------------------------------
# All SED commands grouped by kind
sedcmds = {
'file' : 'rw' ,
'addr' : '/$0123456789\\',
'multi': 'sy' ,
'solo' : 'nNdDgGhHxpPlq=',
'text' : 'aci' ,
'jump' : ':bt' ,
'block': '{}' ,
'flag' : 'gpIi0123456789w'
}
# Regex patterns to identify special entities
patt = {
'jump_label': r'[^\s;}#]*' , # _any_ char except those, or None
'filename' : r'[^\s]+' , # _any_ not blank char (strange..)
'flag' : r'[%s]+'%sedcmds['flag'] , # list of all flags
'topopts' : r'#!\s*/[^\s]+\s+-([nf]+)' # options on #!/bin/sed header
}
# All fields used by the internal SED command dictionary
cmdfields = [
'linenr',
'addr1', 'addr1flag', 'addr2', 'addr2flag', 'lastaddr', 'modifier',
'id', 'content', 'delimiter', 'pattern', 'replace', 'flag',
'extrainfo', 'comment'
]
#XXX Don't change the order! There is a piggy cmdfields[6:] ahead
#-------------------------------------------------------------------------------
# Auxiliar Functions - Tools
#-------------------------------------------------------------------------------
def escapeTextCommandsSpecials(str):
str = string.replace(str, '\\', '\\\\') # escape escape
return str
def isOpenBracket(str):
# bracket open: [ \\[ \\\\[ ...
# not bracket : \[ \\\[ \\\\\[ ...
isis = 0
delim = '['
str = re.sub('\[:[a-z]+:]', '', str) # del [:charclasses:]
if string.find(str, delim) == -1: return 0 # hey, no brackets!
# Only the last two count
patterns = string.split(str, delim)[-2:]
Debug('bracketpatts: %s'%patterns,3)
possibleescape, bracketpatt = patterns
# Maybe the bracket is escaped, and is not a metachar?
m = re.search(r'\\+$', possibleescape) # escaped bracket
if m and len(m.group(0))%2: # odd number of escapes
Debug('bracket INVALID! - escaped',2)
isis = 0
elif string.find(bracketpatt, ']') == -1: # not closed by ]
Debug('bracket OPEN! - found! found!',2)
isis = 1 # it is opened! &:)
return isis
def paintHtml(id, txt=''):
# Escape HTML special chars
if txt:
txt = string.replace(txt, '&', '&')
txt = string.replace(txt, '>', '>')
txt = string.replace(txt, '<', '<')
# Some color adjustments and emphasis
if id == 'id' and txt in sedcmds['block']:
id = 'delimiter'
elif id == 'id' and txt == ':':
id = 'content'
elif id == 'replace': # highlight \n, & and \$
newtxt = paintHtml('special', '\\'+linesep)
txt = string.replace(txt, '\\'+linesep, newtxt)
txt = re.sub(
'(\\\\[1-9]|&)', paintHtml('special', '\\1'), txt)
elif id == 'pattern': # highlight ( and |
txt = re.sub(
'(\\\\)([(|])', '\\1'+paintHtml('pattmeta', '\\2'), txt)
elif id == 'plaintext': # highlight \$
newtxt = paintHtml('special', '\\'+linesep)
txt = string.replace(txt, '\\'+linesep, newtxt)
elif id == 'branch': # nice link to the label!
txt = '<a href="#%s">%s</a>'%(txt,txt)
elif id == 'target': # link target
txt = '<a name="%s">%s</a>'%(txt,txt)
id = 'content'
# Paint it!
if html_colors.get(id) and txt:
font_color = html_colors[id]
txt = '<font color="%s"><b>%s</b></font>'%(font_color, txt)
return txt
#-------------------------------------------------------------------------------
# SedCommand class - Know All About Commands
#-------------------------------------------------------------------------------
# TIP: SedCommand already receives lstrip()ed data and data != None
class SedCommand:
def __init__(self, abcde):
self.id = abcde[0] # s
self.content = '' # txt, filename
self.modifier = '' # !
self.full = '' # !s/abc/def/g
# for s/// & y///
self.pattern = '' # abc
self.replace = '' # def
self.delimiter = '' # /
self.flag = '' # g
self.isok = 0
self.comment = ''
self.rest = self.junk = abcde
self.extrainfo = ''
if self.id == '!':
self.modifier = self.id # set modifier
self.junk = string.lstrip(self.junk[1:]) # del !@junk
self.id = self.junk[0] # set id again
self.junk = self.junk[1:] # del id@junk
#self.setId()
self.doItAll()
def doItAll(self):
# here, junk arrives without the id, but not lstripped (s///)
id = self.id
#TODO put pending comment on the previous command (h ;#comm)
if id == '#':
Debug('type: comment',3)
self.comment = self.id+self.junk
self.junk = ''
self.isok = 1
elif id in sedcmds['solo']:
Debug('type: solo',3)
self.isok = 1
elif id in sedcmds['block']:
Debug('type: block',3)
self.isok = 1
elif id in sedcmds['text']:
Debug('type: text',3)
if self.junk[-1] != '\\': # if not \ at end, finished
# ensure \LineSep at begining
self.content = re.sub(
r'^\\%s'%linesep, '', self.junk)
self.content = '\\%s%s'%(linesep,self.content)
self.isok = 1
elif id in sedcmds['jump']:
Debug('type: jump',3)
self.junk = string.lstrip(self.junk)
m = re.match(patt['jump_label'], self.junk)
if m:
self.content = m.group()
self.junk = self.junk[m.end():]
self.isok = 1
elif id in sedcmds['file']:
#TODO deal with valid cmds like 'r bla;bla' and 'r bla ;#comm'
#TODO spaces and ; are valid as filename chars
Debug('type: file',3)
self.junk = string.lstrip(self.junk)
m = re.match(patt['filename'], self.junk)
if m:
self.content = m.group()
self.junk = self.junk[m.end():]
self.isok = 1
elif id in sedcmds['multi']: # s/// & y///
Debug('type: multi',3)
self.delimiter = self.junk[0]
ps = SedAddress(self.junk)
hs = ''
if ps.isok:
self.pattern = ps.pattern
self.junk = ps.rest
# 'replace' opt to avoid openbracket check,
# because 's/bla/[/' is ok
hs = SedAddress(self.delimiter+self.junk,
'replace')
if hs.isok:
self.replace = hs.pattern
self.junk = string.lstrip(hs.rest)
# great, s/patt/rplc/ sucessfully taken
if hs and hs.isok and self.junk: # there are flags?
Debug('possible s/// flag: %s'%self.junk,3)
m = re.match('(%s\s*)+'%patt['flag'],self.junk)
if m:
self.flag = m.group()
self.junk = string.lstrip(
self.junk[m.end():]) # del flag
self.flag = re.sub(
'\s','',self.flag) # del blanks@flag
Debug('FOUND s/// flag: %s'%(
string.strip(self.flag)))
### now we've got flags also
if 'w' in self.flag: # write file flag
m = re.match(patt['filename'],self.junk)
if m:
self.content = m.group()
Debug('FOUND s///w filename: %s'%self.content)
self.junk = string.lstrip(
self.junk[m.end():])
### and now, s///w filename
### is saved also
if hs and hs.isok: self.isok = 1
else:
Error("invalid SED command '%s' at line %d"%(id,linenr))
if self.isok:
self.full = composeSedCommand(vars(self))
self.full = string.replace(self.full, '\n', linesep)
self.rest = string.lstrip(self.junk)
Debug('FOUND command: %s'%self.full)
Debug('rest left: %s'%self.rest,2)
possiblecomment = self.rest
if possiblecomment and possiblecomment[0] == '#':
self.comment = possiblecomment
Debug('FOUND comment: %s'%self.comment)
Debug('SedCommand: %s'%vars(self),3)
#-------------------------------------------------------------------------------
# SedAddress class - Know All About Addresses
#-------------------------------------------------------------------------------
#TIP an address is NOT multiline
class SedAddress:
def __init__(self, abcde, context='addr'):
self.delimiter = ''
self.pattern = ''
self.flag = ''
self.full = ''
self.html = ''
self.isline = 0
self.isok = 0
self.escape = ''
self.rest = self.junk = abcde
self.context = context
self.setType() # numeric or pattern?
self.doItAll()
Debug('SedAddress: %s'%vars(self),3)
def doItAll(self):
if self.isline: self.setLineAddr()
else : self.setPattAddr()
if self.isok:
self.full = '%s%s%s%s'%(
self.escape,
self.delimiter,
self.pattern,
self.delimiter)
if action == 'html':
self.html = '%s%s%s%s'%(
paintHtml('escape' , self.escape ),
paintHtml('delimiter', self.delimiter),
paintHtml('pattern' , self.pattern ),
paintHtml('delimiter', self.delimiter))
Debug('FOUND addr: %s'%self.full)
cutlen = len(self.full)+len(self.flag)
self.rest = self.rest[cutlen:] # del junk's addr
self.flag = string.strip(self.flag) # del flag's blank
Debug('rest left: %s'%self.rest,2)
else:
Debug('OH NO! partial addr: %s'%self.rest)
def setType(self):
id = self.junk[0]
if re.match('[0-9$]', id): # numeric addr, easy!
self.isline = 1
else: # oh no, pattern
if id == '\\': # strange delimiter (!/)
self.escape = '\\'
self.junk = self.junk[1:] # del escape
self.delimiter = self.junk[0] # set delimiter
self.junk = self.junk[1:] # del delimiter@junk
def setLineAddr(self):
m = re.match(r'[0-9]+|\$', self.junk)
self.pattern = m.group(0)
self.isok = 1
def setPattAddr(self):
###
# similar to command finder:
# - split at pattern delimiter
# - if address not terminated, join with next split chunk (loop)
# - address found, return it
#
# We can deal with really catchy valid addresses like:
# /\/[/]\\/ and \;\;[;;]\\;
incompleteaddr = ''
Debug('addr delimiter: '+self.delimiter,2)
patterns = string.split(self.junk, self.delimiter)
Debug('addr patterns: %s'%patterns,2)
while patterns:
possiblepatt = patterns.pop(0)
# if address not terminated, join next
if incompleteaddr:
possiblepatt = string.join(
[incompleteaddr, possiblepatt],
self.delimiter)
incompleteaddr = ''
Debug('possiblepatt: '+possiblepatt,2)
# maybe splitted at a (valid) escaped delimiter?
if re.search(r'\\+$', possiblepatt):
m = re.search(r'\\+$', possiblepatt)
if len(m.group(0))%2:
Debug('address INCOMPLETE! - ends with \\ alone')
incompleteaddr = possiblepatt
continue
if self.context != 'replace':
# maybe splitted at a delimiter inside
# char class []?
# BUG: []/[] is not catched - WONTFIX
if isOpenBracket(possiblepatt):
Debug('address INCOMPLETE! - open bracket')
incompleteaddr = possiblepatt
continue
break # it's an address!
if patterns: # must have something left
if patterns[0]: # the rest is a flag?
Debug('possible addr flag: %s'%patterns[0],3)
m = re.match('\s*I\s*', patterns[0])
if m: # yes, a flag!
self.flag = m.group() # set addr flag
Debug('FOUND addr flag: %s'%(
string.strip(self.flag)))
self.pattern = possiblepatt
self.isok = 1
#-------------------------------------------------------------------------------
# Hardcore Address/Command Composer Functions
#-------------------------------------------------------------------------------
def composeSedAddress(dict):
addr1 = ''
if action == 'html':
if dict['addr1']: addr1 = dict['addr1html']
if dict['addr2']: addr2 = dict['addr2html']
else:
addr1 = '%s%s'%(dict['addr1'],dict['addr1flag'])
if dict['addr2']:
addr2 = '%s%s'%(dict['addr2'],dict['addr2flag'])
if dict['addr2']: addr = '%s,%s'%(addr1,addr2)
else: addr = addr1
if addr: addr = '%s '%(addr) # visual addr/cmd separation
return addr
def composeSedCommand(dict):
if dict['delimiter']: # s///
if action != 'html':
cmd = '%s%s%s%s%s%s%s%s'%(
dict['modifier'] ,dict['id'],
dict['delimiter'],dict['pattern'],
dict['delimiter'],dict['replace'],
dict['delimiter'],dict['flag'])
if dict['content']: # s///w filename
cmd = cmd+' '+dict['content']
else:
cmd = """%s%s%s%s%s%s%s%s"""%(
paintHtml('modifier' , dict['modifier'] ),
paintHtml('id' , dict['id'] ),
paintHtml('delimiter', dict['delimiter']),
paintHtml('pattern' , dict['pattern'] ),
paintHtml('delimiter', dict['delimiter']),
paintHtml('replace' , dict['replace'] ),
paintHtml('delimiter', dict['delimiter']),
paintHtml('flag' , dict['flag'] ))
if dict['content']: # s///w filename
painted = paintHtml('content', dict['content'])
cmd = '%s %s'%(cmd, painted)
else:
idsep=''
# spacer on r,w,b,t commands only
spaceme = sedcmds['file']+sedcmds['jump']
spaceme = string.replace(spaceme,':','') # : label (no space!)
if dict['id'] in spaceme: idsep=' '
cmd = '%s%s%s%s'%(
dict['modifier'],
dict['id'],
idsep,
dict['content'])
if action == 'html':
if dict['id'] in sedcmds['text']:
content_type = 'plaintext'
elif dict['id'] in 'bt':
content_type = 'branch'
elif dict['id'] == ':':
content_type = 'target'
else:
content_type = 'content'
cmd = '%s%s%s%s'%(
paintHtml('modifier' , dict['modifier']),
paintHtml('id' , dict['id'] ),
idsep,
paintHtml(content_type, dict['content'] ))
cmd = string.replace(cmd, linesep, '\n')
return cmd
#-------------------------------------------------------------------------------
# The dump* Functions - They 4mat 4you!
#-------------------------------------------------------------------------------
def dumpKeyValuePair(datalist):
"Shows field:value command data line by line (lots of lines!)"
for data in datalist[1:]: # skip headers at 0
if not data['id']: continue # blank line
for key in datalist[0]['fields']:
if key == 'replace':
data[key] = string.replace(
data[key],
linesep,
newlineshow)
print "%10s:%s"%(key,data[key])
print
# Format: line:ad1:ad1f:ad2:ad2f:mod:cmd:content:delim:patt:rplc:flag:comment
def dumpOneliner(datalist, fancy=0):
"Shows a command per line, elements separated by : (looooong lines)"
r = n = ''
if fancy: r = '\033[7m'; n = '\033[m'
for data in datalist[1:]: # skip headers at 0
outline = data['linenr']
if data['id']:
for key in datalist[0]['fields'][1:]: # skip linenr
outline = '%s:%s%s%s'%(outline,r,data[key],n)
print outline
def dumpCute(datalist):
"Shows a strange representation of SED commands. Use --dumpcute."
r = color_REV; n = color_NO
for data in datalist[1:]: # skip headers at 0
if not data['id']:
print '%40s'%'[blank]'
elif data['id'] == '#' :
print data['comment']
else:
idsep=''
if data['id'] in 'bt': idsep=' '
cmd = '%s%s%s%s'%(
data['modifier'],
data['id'],
idsep,
data['content'])
if data['delimiter']:
cmd = '%s%s%s%s%s%s%s'%(cmd,
data['delimiter'],data['pattern'],
data['delimiter'],data['replace'],
data['delimiter'],data['flag'])
cmd = string.replace(cmd, linesep, n+newlineshow+r)
print '%s'%'-'*40
print 'adr: %s%s%s%s ::: %s%s%s%s'%(
r,data['addr1'],data['addr1flag'],n,
r,data['addr2'],data['addr2flag'],n)
print 'cmd: %s%s%s [%s]'%(r,cmd,n,data['comment'])
# dumpScript: This is a handy function, used by --indent AND --htmlize
# It formats the SED script in a humam-friendly way, with one command
# per line and adding spaces on the right places. If --htmlize, it
# also adds the HTML code to the script.
#
def dumpScript(datalist, indent_prefix):
"Shows the indented script in plain text or HTML!"
indfmt = { 'string' : indent_prefix, 'initlevel' : 0,
'addrsep': ',' , 'joinaddrcmd': 0 }
outlist = []
adsep = indfmt['addrsep']
indent = indfmt['initlevel']
if action == 'html': outlist.append(html_data['header'])
for data in datalist[1:]: # skip headers at 0
if not data['id']:
outlist.append('\n')
continue # blank line
if data['id'] == '#' :
indentstr = indfmt['string']*indent
if action != 'html':
outlist.append('%s%s\n'%(
indentstr,
data['comment']))
else:
outlist.append('%s%s\n'%(
indentstr,
paintHtml('comment',
data['comment'])))
else:
if data['id'] == '}': indent = indent - 1
# only indent++ after open {
indentstr = indfmt['string']*indent
if data['id'] == '{': indent = indent + 1
cmd = composeSedCommand(data)
addr = composeSedAddress(data)
# saving full line
comm = ''
if data['comment']: comm = ';'+data['comment']
cmd = '%s%s%s'%(indentstr,addr,cmd)
outlist.append('%-39s%s\n'%(cmd,comm))
if action == 'html':
outlist.append(html_data['footer'])
for line in outlist: print line, # print the result
#-------------------------------------------------------------------------------
# doDebug - Here is where the fun begins
#-------------------------------------------------------------------------------
#
### doDebug
#
# This function performs the --debug action.
#
# After the SED script was parsed by the parsed (below), this function
# is called with the script data found. It loops, shouts and screems,
# inserting the nice DEBUG lines between the SED script commands.
#
# After all lines are composed, it call the system's SED to run the
# script, and SED will do it's job, but this time showing you all the
# secrets that the PATTERN SPACE and HOLD SPACE buffers holds.
#
def doDebug(datalist):
outlist = []
cmdlineopts = 'f'
t_count = 0
hideregisters = 0
if datalist[0].has_key('topopts'):
cmdlineopts = datalist[0]['topopts']
# If we have one or more t commands on the script, we need to save
# the t command status between debug commands. As they perform
# s/// commands, the t status of the "last substitution" is lost.
# So, we save the status doing a nice loop trick before *every*
# command (necessary overhead). This loops uses the :zzsetNNN and
# zzclrNNN labels, where NNN is the label count.
# TIP: t status resets: line read, t call
if datalist[0]['has_t']: t_count = 1
for i in range(len(datalist)):
if i == 0: continue # skip headers at 0
data = datalist[i]
if not data['id']: continue # ignore blank line
if data['id'] == '#': outlist.append('%s\n'%(data['comment']))
else:
cmd = composeSedCommand(data)
addr = composeSedAddress(data)
cmdshow = string.replace(cmd, '\n',
newlineshow+color_YLW)
cmdshow = escapeTextCommandsSpecials(addr+cmdshow)
showsedcmd = string.replace(showcomm, '\a', cmdshow)
registers = showpatt + showhold
if hideregisters: registers = ''
showall = '%s%s'%(registers,showsedcmd)
# Add the 't status' trick to commands.
# Exception: read-next-line commands (n,d,q)
# Exception: no PATT/HOLD registers to show (no s///)
if t_count and showall:
if data['id'] not in 'ndq' and registers:
tmp = string.replace(save_t, '\a',
'%03d'%t_count)
showall = string.replace(tmp, '#DEBUG#',
showall)
t_count = t_count + 1
# null cmd to restore last addr: /addr/y/!/!/
if data['lastaddr']:
showall = showall+debug_prefix+\
data['lastaddr']+nullcomm+'\n'
# after jump or block commands don't show
# registers, because they're not affected.
# exception: after b or t without target
# (read next line)
hideregisters = 0
if data['id'] in sedcmds['jump'] and data['content']:
hideregisters = 1
elif data['id'] in sedcmds['block']:
hideregisters = 1
outlist.append("%s#%s\n%s\n"%(showall,'-'*50,addr+cmd))
outlist.append(showpatt + showhold) # last line status
# executing sed script