forked from torhve/Weechat-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrep.py
1676 lines (1540 loc) · 59.6 KB
/
grep.py
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
# -*- coding: utf-8 -*-
###
# Copyright (c) 2009-2010 by Elián Hanisch <[email protected]>
#
# This program 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.
#
# 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, see <http://www.gnu.org/licenses/>.
###
###
# Search in Weechat buffers and logs (for Weechat 0.3.*)
#
# Inspired by xt's grep.py
# Originally I just wanted to add some fixes in grep.py, but then
# I got carried away and rewrote everything, so new script.
#
# Commands:
# * /grep
# Search in logs or buffers, see /help grep
# * /logs:
# Lists logs in ~/.weechat/logs, see /help logs
#
# Settings:
# * plugins.var.python.grep.clear_buffer:
# Clear the results buffer before each search. Valid values: on, off
#
# * plugins.var.python.grep.go_to_buffer:
# Automatically go to grep buffer when search is over. Valid values: on, off
#
# * plugins.var.python.grep.log_filter:
# Coma separated list of patterns that grep will use for exclude logs, e.g.
# if you use '*server/*' any log in the 'server' folder will be excluded
# when using the command '/grep log'
#
# * plugins.var.python.grep.show_summary:
# Shows summary for each log. Valid values: on, off
#
# * plugins.var.python.grep.max_lines:
# Grep will only print the last matched lines that don't surpass the value defined here.
#
# * plugins.var.python.grep.size_limit:
# Size limit in KiB, is used for decide whenever grepping should run in background or not. If
# the logs to grep have a total size bigger than this value then grep run as a new process.
# It can be used for force or disable background process, using '0' forces to always grep in
# background, while using '' (empty string) will disable it.
#
# * plugins.var.python.grep.default_tail_head:
# Config option for define default number of lines returned when using --head or --tail options.
# Can be overriden in the command with --number option.
#
#
# TODO:
# * try to figure out why hook_process chokes in long outputs (using a tempfile as a
# workaround now)
# * possibly add option for defining time intervals
#
#
# History:
# 2010-10-26
# version 0.7:
# * added templates.
# * using --only-match shows only unique strings.
# * fixed bug that inverted -B -A switches when used with -t
#
# 2010-10-14
# version 0.6.8: by xt <[email protected]>
# * supress highlights when printing in grep buffer
#
# 2010-10-06
# version 0.6.7: by xt <[email protected]>
# * better temporary file:
# use tempfile.mkstemp. to create a temp file in log dir,
# makes it safer with regards to write permission and multi user
#
# 2010-04-08
# version 0.6.6: bug fixes
# * use WEECHAT_LIST_POS_END in log file completion, makes completion faster
# * disable bytecode if using python 2.6
# * use single quotes in command string
# * fix bug that could change buffer's title when using /grep stop
#
# 2010-01-24
# version 0.6.5: disable bytecode is a 2.6 feature, instead, resort to delete the bytecode manually
#
# 2010-01-19
# version 0.6.4: bug fix
# version 0.6.3: added options --invert --only-match (replaces --exact, which is still available
# but removed from help)
# * use new 'irc_nick_color' info
# * don't generate bytecode when spawning a new process
# * show active options in buffer title
#
# 2010-01-17
# version 0.6.2: removed 2.6-ish code
# version 0.6.1: fixed bug when grepping in grep's buffer
#
# 2010-01-14
# version 0.6.0: implemented grep in background
# * improved context lines presentation.
# * grepping for big (or many) log files runs in a weechat_process.
# * added /grep stop.
# * added 'size_limit' option
# * fixed a infolist leak when grepping buffers
# * added 'default_tail_head' option
# * results are sort by line count
# * don't die if log is corrupted (has NULL chars in it)
# * changed presentation of /logs
# * log path completion doesn't suck anymore
# * removed all tabs, because I learned how to configure Vim so that spaces aren't annoying
# anymore. This was the script's original policy.
#
# 2010-01-05
# version 0.5.5: rename script to 'grep.py' (FlashCode <[email protected]>).
#
# 2010-01-04
# version 0.5.4.1: fix index error when using --after/before-context options.
#
# 2010-01-03
# version 0.5.4: new features
# * added --after-context and --before-context options.
# * added --context as a shortcut for using both -A -B options.
#
# 2009-11-06
# version 0.5.3: improvements for long grep output
# * grep buffer input accepts the same flags as /grep for repeat a search with different
# options.
# * tweaks in grep's output.
# * max_lines option added for limit grep's output.
# * code in update_buffer() optimized.
# * time stats in buffer title.
# * added go_to_buffer config option.
# * added --buffer for search only in buffers.
# * refactoring.
#
# 2009-10-12, omero
# version 0.5.2: made it python-2.4.x compliant
#
# 2009-08-17
# version 0.5.1: some refactoring, show_summary option added.
#
# 2009-08-13
# version 0.5: rewritten from xt's grep.py
# * fixed searching in non weechat logs, for cases like, if you're
# switching from irssi and rename and copy your irssi logs to %h/logs
# * fixed "timestamp rainbow" when you /grep in grep's buffer
# * allow to search in other buffers other than current or in logs
# of currently closed buffers with cmd 'buffer'
# * allow to search in any log file in %h/logs with cmd 'log'
# * added --count for return the number of matched lines
# * added --matchcase for case sensible search
# * added --hilight for color matches
# * added --head and --tail options, and --number
# * added command /logs for list files in %h/logs
# * added config option for clear the buffer before a search
# * added config option for filter logs we don't want to grep
# * added the posibility to repeat last search with another regexp by writing
# it in grep's buffer
# * changed spaces for tabs in the code, which is my preference
#
###
import sys, getopt, time, os, re
path = os.path
stat = os.stat
try:
import weechat
from weechat import WEECHAT_RC_OK, prnt, prnt_date_tags
import_ok = True
except ImportError:
import_ok = False
SCRIPT_NAME = "grep"
SCRIPT_AUTHOR = "Elián Hanisch <[email protected]>"
SCRIPT_VERSION = "0.7"
SCRIPT_LICENSE = "GPL3"
SCRIPT_DESC = "Search in buffers and logs"
SCRIPT_COMMAND = "grep"
### Default Settings ###
settings = {
'clear_buffer' : 'off',
'log_filter' : '',
'go_to_buffer' : 'on',
'max_lines' : '4000',
'show_summary' : 'on',
'size_limit' : '2048',
'default_tail_head' : '10',
}
### Class definitions ###
class linesDict(dict):
"""
Class for handling matched lines in more than one buffer.
linesDict[buffer_name] = matched_lines_list
"""
def __setitem__(self, key, value):
assert isinstance(value, list)
if key not in self:
dict.__setitem__(self, key, value)
else:
dict.__getitem__(self, key).extend(value)
def get_matches_count(self):
"""Return the sum of total matches stored."""
if dict.__len__(self):
return sum(map(lambda L: L.matches_count, self.itervalues()))
else:
return 0
def __len__(self):
"""Return the sum of total lines stored."""
if dict.__len__(self):
return sum(map(len, self.itervalues()))
else:
return 0
def __str__(self):
"""Returns buffer count or buffer name if there's just one stored."""
n = len(self.keys())
if n == 1:
return self.keys()[0]
elif n > 1:
return '%s logs' %n
else:
return ''
def items(self):
"""Returns a list of items sorted by line count."""
items = dict.items(self)
items.sort(key=lambda i: len(i[1]))
return items
def items_count(self):
"""Returns a list of items sorted by match count."""
items = dict.items(self)
items.sort(key=lambda i: i[1].matches_count)
return items
def strip_separator(self):
for L in self.itervalues():
L.strip_separator()
def get_last_lines(self, n):
total_lines = len(self)
#debug('total: %s n: %s' %(total_lines, n))
if n >= total_lines:
# nothing to do
return
for k, v in reversed(self.items()):
l = len(v)
if n > 0:
if l > n:
del v[:l-n]
v.stripped_lines = l-n
n -= l
else:
del v[:]
v.stripped_lines = l
class linesList(list):
"""Class for list of matches, since sometimes I need to add lines that aren't matches, I need an
independent counter."""
_sep = '...'
def __init__(self, *args):
list.__init__(self, *args)
self.matches_count = 0
self.stripped_lines = 0
def append(self, item):
"""Append lines, can be a string or a list with strings."""
if isinstance(item, str):
list.append(self, item)
else:
self.extend(item)
def append_separator(self):
"""adds a separator into the list, makes sure it doen't add two together."""
s = self._sep
if (self and self[-1] != s) or not self:
self.append(s)
def onlyUniq(self):
s = set(self)
del self[:]
self.extend(s)
def count_match(self, item=None):
if item is None or isinstance(item, str):
self.matches_count += 1
else:
self.matches_count += len(item)
def strip_separator(self):
"""removes separators if there are first or/and last in the list."""
if self:
s = self._sep
if self[0] == s:
del self[0]
if self[-1] == s:
del self[-1]
### Misc functions ###
now = time.time
def get_size(f):
try:
return stat(f).st_size
except OSError:
return 0
sizeDict = {0:'b', 1:'KiB', 2:'MiB', 3:'GiB', 4:'TiB'}
def human_readable_size(size):
power = 0
while size > 1024:
power += 1
size /= 1024.0
return '%.2f %s' %(size, sizeDict.get(power, ''))
def color_nick(nick):
"""Returns coloured nick, with coloured mode if any."""
if not nick: return ''
wcolor = weechat.color
config_string = lambda s : weechat.config_string(weechat.config_get(s))
config_int = lambda s : weechat.config_integer(weechat.config_get(s))
# prefix and suffix
prefix = config_string('irc.look.nick_prefix')
suffix = config_string('irc.look.nick_suffix')
prefix_c = suffix_c = wcolor(config_string('weechat.color.chat_delimiters'))
if nick[0] == prefix:
nick = nick[1:]
else:
prefix = prefix_c = ''
if nick[-1] == suffix:
nick = nick[:-1]
suffix = wcolor(color_delimiter) + suffix
else:
suffix = suffix_c = ''
# nick mode
modes = '@!+%'
if nick[0] in modes:
mode, nick = nick[0], nick[1:]
mode_color = wcolor(config_string('weechat.color.nicklist_prefix%d' \
%(modes.find(mode) + 1)))
else:
mode = mode_color = ''
# nick color
nick_color = weechat.info_get('irc_nick_color', nick)
if not nick_color:
# probably we're in WeeChat 0.3.0
#debug('no irc_nick_color')
color_nicks_number = config_int('weechat.look.color_nicks_number')
idx = (sum(map(ord, nick))%color_nicks_number) + 1
nick_color = wcolor(config_string('weechat.color.chat_nick_color%02d' %idx))
return ''.join((prefix_c, prefix, mode_color, mode, nick_color, nick, suffix_c, suffix))
### Config and value validation ###
boolDict = {'on':True, 'off':False}
def get_config_boolean(config):
value = weechat.config_get_plugin(config)
try:
return boolDict[value]
except KeyError:
default = settings[config]
error("Error while fetching config '%s'. Using default value '%s'." %(config, default))
error("'%s' is invalid, allowed: 'on', 'off'" %value)
return boolDict[default]
def get_config_int(config, allow_empty_string=False):
value = weechat.config_get_plugin(config)
try:
return int(value)
except ValueError:
if value == '' and allow_empty_string:
return value
default = settings[config]
error("Error while fetching config '%s'. Using default value '%s'." %(config, default))
error("'%s' is not a number." %value)
return int(default)
def get_config_log_filter():
filter = weechat.config_get_plugin('log_filter')
if filter:
return filter.split(',')
else:
return []
def get_home():
home = weechat.config_string(weechat.config_get('logger.file.path'))
return home.replace('%h', weechat.info_get('weechat_dir', ''))
def strip_home(s, dir=''):
"""Strips home dir from the begging of the log path, this makes them sorter."""
if not dir:
global home_dir
dir = home_dir
l = len(dir)
if s[:l] == dir:
return s[l:]
return s
### Messages ###
script_nick = SCRIPT_NAME
def debug(s, *args):
if not weechat.config_get_plugin('debug'): return
if not isinstance(s, basestring):
s = str(s)
if args:
s = s %args
prnt('', '%s\t%s' %(script_nick, s))
def error(s, buffer=''):
"""Error msg"""
prnt(buffer, '%s%s %s' %(weechat.prefix('error'), script_nick, s))
if weechat.config_get_plugin('debug'):
import traceback
if traceback.sys.exc_type:
trace = traceback.format_exc()
prnt('', trace)
def say(s, buffer=''):
"""normal msg"""
prnt_date_tags(buffer, 0, 'no_highlight', '%s\t%s' %(script_nick, s))
### Log files and buffers ###
cache_dir = {} # note: don't remove, needed for completion if the script was loaded recently
def dir_list(dir, filter_list=(), filter_excludes=True, include_dir=False):
"""Returns a list of files in 'dir' and its subdirs."""
global cache_dir
from os import walk
from fnmatch import fnmatch
#debug('dir_list: listing in %s' %dir)
key = (dir, include_dir)
try:
return cache_dir[key]
except KeyError:
pass
filter_list = filter_list or get_config_log_filter()
dir_len = len(dir)
if filter_list:
def filter(file):
file = file[dir_len:] # pattern shouldn't match home dir
for pattern in filter_list:
if fnmatch(file, pattern):
return filter_excludes
return not filter_excludes
else:
filter = lambda f : not filter_excludes
file_list = []
extend = file_list.extend
join = path.join
def walk_path():
for basedir, subdirs, files in walk(dir):
#if include_dir:
# subdirs = map(lambda s : join(s, ''), subdirs)
# files.extend(subdirs)
files_path = map(lambda f : join(basedir, f), files)
files_path = [ file for file in files_path if not filter(file) ]
extend(files_path)
walk_path()
cache_dir[key] = file_list
#debug('dir_list: got %s' %str(file_list))
return file_list
def get_file_by_pattern(pattern, all=False):
"""Returns the first log whose path matches 'pattern',
if all is True returns all logs that matches."""
if not pattern: return []
#debug('get_file_by_filename: searching for %s.' %pattern)
# do envvar expandsion and check file
file = path.expanduser(pattern)
file = path.expandvars(file)
if path.isfile(file):
return [file]
# lets see if there's a matching log
global home_dir
file = path.join(home_dir, pattern)
if path.isfile(file):
return [file]
else:
import fnmatch
file = []
file_list = dir_list(home_dir)
n = len(home_dir)
for log in file_list:
basename = log[n:]
if fnmatch.fnmatch(basename, pattern):
file.append(log)
if not all: break
#debug('get_file_by_filename: got %s.' %file)
return file
def get_file_by_buffer(buffer):
"""Given buffer pointer, finds log's path or returns None."""
#debug('get_file_by_buffer: searching for %s' %buffer)
infolist = weechat.infolist_get('logger_buffer', '', '')
if not infolist: return
try:
while weechat.infolist_next(infolist):
pointer = weechat.infolist_pointer(infolist, 'buffer')
if pointer == buffer:
file = weechat.infolist_string(infolist, 'log_filename')
if weechat.infolist_integer(infolist, 'log_enabled'):
#debug('get_file_by_buffer: got %s' %file)
return file
#else:
# debug('get_file_by_buffer: got %s but log not enabled' %file)
finally:
#debug('infolist gets freed')
weechat.infolist_free(infolist)
def get_file_by_name(buffer_name):
"""Given a buffer name, returns its log path or None. buffer_name should be in 'server.#channel'
or '#channel' format."""
#debug('get_file_by_name: searching for %s' %buffer_name)
# common mask options
config_masks = ('logger.mask.irc', 'logger.file.mask')
# since there's no buffer pointer, we try to replace some local vars in mask, like $channel and
# $server, then replace the local vars left with '*', and use it as a mask for get the path with
# get_file_by_pattern
for config in config_masks:
mask = weechat.config_string(weechat.config_get(config))
#debug('get_file_by_name: mask: %s' %mask)
if '$name' in mask:
mask = mask.replace('$name', buffer_name)
elif '$channel' in mask or '$server' in mask:
if '.' in buffer_name and \
'#' not in buffer_name[:buffer_name.find('.')]: # the dot isn't part of the channel name
# ^ I'm asuming channel starts with #, i'm lazy.
server, channel = buffer_name.split('.', 1)
else:
server, channel = '*', buffer_name
if '$channel' in mask:
mask = mask.replace('$channel', channel)
if '$server' in mask:
mask = mask.replace('$server', server)
# change the unreplaced vars by '*'
if '$' in mask:
chars = 'abcdefghijklmnopqrstuvwxyz_'
masks = mask.split('$')
masks = map(lambda s: s.lstrip(chars), masks)
mask = '*'.join(masks)
if mask[0] != '*':
mask = '*' + mask
#debug('get_file_by_name: using mask %s' %mask)
file = get_file_by_pattern(mask)
#debug('get_file_by_name: got file %s' %file)
if file:
return file
return None
def get_buffer_by_name(buffer_name):
"""Given a buffer name returns its buffer pointer or None."""
#debug('get_buffer_by_name: searching for %s' %buffer_name)
pointer = weechat.buffer_search('', buffer_name)
if not pointer:
try:
infolist = weechat.infolist_get('buffer', '', '')
while weechat.infolist_next(infolist):
short_name = weechat.infolist_string(infolist, 'short_name')
name = weechat.infolist_string(infolist, 'name')
if buffer_name in (short_name, name):
#debug('get_buffer_by_name: found %s' %name)
pointer = weechat.buffer_search('', name)
return pointer
finally:
weechat.infolist_free(infolist)
#debug('get_buffer_by_name: got %s' %pointer)
return pointer
def get_all_buffers():
"""Returns list with pointers of all open buffers."""
buffers = []
infolist = weechat.infolist_get('buffer', '', '')
while weechat.infolist_next(infolist):
buffers.append(weechat.infolist_pointer(infolist, 'pointer'))
weechat.infolist_free(infolist)
grep_buffer = weechat.buffer_search('python', SCRIPT_NAME)
if grep_buffer and grep_buffer in buffers:
# remove it from list
del buffers[buffers.index(grep_buffer)]
return buffers
### Grep ###
def make_regexp(pattern, matchcase=False):
"""Returns a compiled regexp."""
if pattern in ('.', '.*', '.?', '.+'):
# because I don't need to use a regexp if we're going to match all lines
return None
try:
if not matchcase:
regexp = re.compile(pattern, re.IGNORECASE)
else:
regexp = re.compile(pattern)
except Exception, e:
raise Exception, 'Bad pattern, %s' %e
return regexp
def check_string(s, regexp, hilight='', exact=False):
"""Checks 's' with a regexp and returns it if is a match."""
if not regexp:
return s
elif exact:
matchlist = regexp.findall(s)
if matchlist:
return matchlist
elif hilight:
matchlist = regexp.findall(s)
if matchlist:
matchlist = list(set(matchlist)) # remove duplicates if any
# apply hilight
color_hilight, color_reset = hilight.split(',', 1)
for m in matchlist:
s = s.replace(m, '%s%s%s' %(color_hilight, m, color_reset))
return s
# no need for findall() here
elif regexp.search(s):
return s
def grep_file(file, head, tail, after_context, before_context, count, regexp, hilight, exact, invert):
"""Return a list of lines that match 'regexp' in 'file', if no regexp returns all lines."""
if count:
tail = head = after_context = before_context = False
hilight = ''
elif exact:
before_context = after_context = False
hilight = ''
elif invert:
hilight = ''
#debug(' '.join(map(str, (file, head, tail, after_context, before_context))))
lines = linesList()
# define these locally as it makes the loop run slightly faster
append = lines.append
count_match = lines.count_match
separator = lines.append_separator
if invert:
def check(s):
if check_string(s, regexp, hilight, exact):
return None
else:
return s
else:
check = lambda s: check_string(s, regexp, hilight, exact)
try:
file_object = open(file, 'r')
except IOError:
# file doesn't exist
return lines
if tail or before_context:
# for these options, I need to seek in the file, but is slower and uses a good deal of
# memory if the log is too big, so we do this *only* for these options.
file_lines = file_object.readlines()
if tail:
# instead of searching in the whole file and later pick the last few lines, we
# reverse the log, search until count reached and reverse it again, that way is a lot
# faster
file_lines.reverse()
# don't invert context switches
before_context, after_context = after_context, before_context
if before_context:
before_context_range = range(1, before_context + 1)
before_context_range.reverse()
limit = tail or head
line_idx = 0
while line_idx < len(file_lines):
line = file_lines[line_idx]
line = check(line)
if line:
if before_context:
separator()
trimmed = False
for id in before_context_range:
try:
context_line = file_lines[line_idx - id]
if check(context_line):
# match in before context, that means we appended these same lines in a
# previous match, so we delete them merging both paragraphs
if not trimmed:
del lines[id - before_context - 1:]
trimmed = True
else:
append(context_line)
except IndexError:
pass
append(line)
count_match(line)
if after_context:
id, offset = 0, 0
while id < after_context + offset:
id += 1
try:
context_line = file_lines[line_idx + id]
_context_line = check(context_line)
if _context_line:
offset = id
context_line = _context_line # so match is hilighted with --hilight
count_match()
append(context_line)
except IndexError:
pass
separator()
line_idx += id
if limit and lines.matches_count >= limit:
break
line_idx += 1
if tail:
lines.reverse()
else:
# do a normal grep
limit = head
for line in file_object:
line = check(line)
if line:
count or append(line)
count_match(line)
if after_context:
id, offset = 0, 0
while id < after_context + offset:
id += 1
try:
context_line = file_object.next()
_context_line = check(context_line)
if _context_line:
offset = id
context_line = _context_line
count_match()
count or append(context_line)
except StopIteration:
pass
separator()
if limit and lines.matches_count >= limit:
break
file_object.close()
return lines
def grep_buffer(buffer, head, tail, after_context, before_context, count, regexp, hilight, exact,
invert):
"""Return a list of lines that match 'regexp' in 'buffer', if no regexp returns all lines."""
lines = linesList()
if count:
tail = head = after_context = before_context = False
hilight = ''
elif exact:
before_context = after_context = False
#debug(' '.join(map(str, (tail, head, after_context, before_context, count, exact, hilight))))
# Using /grep in grep's buffer can lead to some funny effects
# We should take measures if that's the case
def make_get_line_funcion():
"""Returns a function for get lines from the infolist, depending if the buffer is grep's or
not."""
string_remove_color = weechat.string_remove_color
infolist_string = weechat.infolist_string
grep_buffer = weechat.buffer_search('python', SCRIPT_NAME)
if grep_buffer and buffer == grep_buffer:
def function(infolist):
prefix = infolist_string(infolist, 'prefix')
message = infolist_string(infolist, 'message')
if prefix: # only our messages have prefix, ignore it
return None
return message
else:
infolist_time = weechat.infolist_time
def function(infolist):
prefix = string_remove_color(infolist_string(infolist, 'prefix'), '')
message = string_remove_color(infolist_string(infolist, 'message'), '')
date = infolist_time(infolist, 'date')
return '%s\t%s\t%s' %(date, prefix, message)
return function
get_line = make_get_line_funcion()
infolist = weechat.infolist_get('buffer_lines', buffer, '')
if tail:
# like with grep_file() if we need the last few matching lines, we move the cursor to
# the end and search backwards
infolist_next = weechat.infolist_prev
infolist_prev = weechat.infolist_next
else:
infolist_next = weechat.infolist_next
infolist_prev = weechat.infolist_prev
limit = head or tail
# define these locally as it makes the loop run slightly faster
append = lines.append
count_match = lines.count_match
separator = lines.append_separator
if invert:
def check(s):
if check_string(s, regexp, hilight, exact):
return None
else:
return s
else:
check = lambda s: check_string(s, regexp, hilight, exact)
if before_context:
before_context_range = range(1, before_context + 1)
before_context_range.reverse()
while infolist_next(infolist):
line = get_line(infolist)
if line is None: continue
line = check(line)
if line:
if before_context:
separator()
trimmed = False
for id in before_context_range:
if not infolist_prev(infolist):
trimmed = True
for id in before_context_range:
context_line = get_line(infolist)
if check(context_line):
if not trimmed:
del lines[id - before_context - 1:]
trimmed = True
else:
append(context_line)
infolist_next(infolist)
count or append(line)
count_match(line)
if after_context:
id, offset = 0, 0
while id < after_context + offset:
id += 1
if infolist_next(infolist):
context_line = get_line(infolist)
_context_line = check(context_line)
if _context_line:
context_line = _context_line
offset = id
count_match()
append(context_line)
else:
# in the main loop infolist_next will start again an cause an infinite loop
# this will avoid it
infolist_next = lambda x: 0
separator()
if limit and lines.matches_count >= limit:
break
weechat.infolist_free(infolist)
if tail:
lines.reverse()
return lines
### this is our main grep function
hook_file_grep = None
def show_matching_lines():
"""
Greps buffers in search_in_buffers or files in search_in_files and updates grep buffer with the
result.
"""
global pattern, matchcase, number, count, exact, hilight, invert
global tail, head, after_context, before_context
global search_in_files, search_in_buffers, matched_lines, home_dir
global time_start
matched_lines = linesDict()
#debug('buffers:%s \nlogs:%s' %(search_in_buffers, search_in_files))
time_start = now()
# buffers
if search_in_buffers:
regexp = make_regexp(pattern, matchcase)
for buffer in search_in_buffers:
buffer_name = weechat.buffer_get_string(buffer, 'name')
matched_lines[buffer_name] = grep_buffer(buffer, head, tail, after_context,
before_context, count, regexp, hilight, exact, invert)
# logs
if search_in_files:
size_limit = get_config_int('size_limit', allow_empty_string=True)
background = False
if size_limit or size_limit == 0:
size = sum(map(get_size, search_in_files))
if size > size_limit * 1024:
background = True
elif size_limit == '':
background = False
if not background:
# run grep normally
regexp = make_regexp(pattern, matchcase)
for log in search_in_files:
log_name = strip_home(log)
matched_lines[log_name] = grep_file(log, head, tail, after_context, before_context,
count, regexp, hilight, exact, invert)
buffer_update()
else:
# we hook a process so grepping runs in background.
#debug('on background')
global hook_file_grep, script_path, bytecode
timeout = 1000*60*10 # 10 min
quotify = lambda s: '"%s"' %s
files_string = ', '.join(map(quotify, search_in_files))
cmd = grep_process_cmd %dict(logs=files_string, head=head, pattern=pattern, tail=tail,
hilight=hilight, after_context=after_context, before_context=before_context,
exact=exact, matchcase=matchcase, home_dir=home_dir, script_path=script_path,
count=count, invert=invert, bytecode=bytecode)
#debug(cmd)
hook_file_grep = weechat.hook_process(cmd, timeout, 'grep_file_callback', '')
global pattern_tmpl
if hook_file_grep:
buffer_create("Searching for '%s' in %s worth of data..." %(pattern_tmpl,
human_readable_size(size)))
else:
buffer_update()
# defined here for commodity
grep_process_cmd = """python -%(bytecode)sc '
import sys, cPickle, tempfile, os
sys.path.append("%(script_path)s") # add WeeChat script dir so we can import grep
from grep import make_regexp, grep_file, strip_home
logs = (%(logs)s, )
try:
regexp = make_regexp("%(pattern)s", %(matchcase)s)
d = {}
for log in logs:
log_name = strip_home(log, "%(home_dir)s")
lines = grep_file(log, %(head)s, %(tail)s, %(after_context)s, %(before_context)s,
%(count)s, regexp, "%(hilight)s", %(exact)s, %(invert)s)
d[log_name] = lines
#fdname = "/tmp/grep_search.tmp"
fd, fdname = tempfile.mkstemp(prefix="grep", dir="%(home_dir)s")
fd = os.fdopen(fd, "wb")
print fdname
cPickle.dump(d, fd, -1)
fd.close()
except Exception, e:
print >> sys.stderr, e'
"""
grep_stdout = grep_stderr = ''
def grep_file_callback(data, command, rc, stdout, stderr):
global hook_file_grep, grep_stderr, grep_stdout
global matched_lines
#debug("rc: %s\nstderr: %s\nstdout: %s" %(rc, repr(stderr), repr(stdout)))
if stdout:
grep_stdout += stdout
if stderr:
grep_stderr += stderr
if int(rc) >= 0:
def set_buffer_error():
grep_buffer = buffer_create()
title = weechat.buffer_get_string(grep_buffer, 'title')
title = title + ' %serror' %color_title
weechat.buffer_set(grep_buffer, 'title', title)
try:
if grep_stderr:
error(grep_stderr)
set_buffer_error()
elif grep_stdout:
#debug(grep_stdout)
file = grep_stdout.strip()
if file:
try:
import cPickle, os
#debug(file)
fd = open(file, 'rb')
d = cPickle.load(fd)
matched_lines.update(d)
fd.close()
except Exception, e:
error(e)
set_buffer_error()
else:
os.remove(file)
buffer_update()
finally:
grep_stdout = grep_stderr = ''
hook_file_grep = None
return WEECHAT_RC_OK