-
Notifications
You must be signed in to change notification settings - Fork 72
/
fslint-gui
executable file
·2030 lines (1836 loc) · 78.5 KB
/
fslint-gui
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 python2
# vim:fileencoding=utf-8
# Note both python and vim understand the above encoding declaration
# Note using env above will cause the system to register
# the name (in ps etc.) as "python" rather than fslint-gui
# (because "python" is passed to exec by env).
"""
FSlint - A utility to find File System lint.
Copyright © 2000-2014 by Pádraig Brady <[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 2 of the License, or
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,
which is available at www.gnu.org
"""
import types, os, sys, pipes, time, stat, tempfile, errno
import gettext
import locale
try:
import gtk
except RuntimeError:
etype, emsg, etb = sys.exc_info()
sys.stderr.write(str(emsg)+'\n')
sys.exit(1)
import gtk.glade
time_commands=False #print sub commands timing on status line
def puts(string=""): #print is problematic in python 3
sys.stdout.write(str(string)+'\n')
liblocation=os.path.dirname(os.path.abspath(sys.argv[0]))
locale_base=liblocation+'/po/locale'
try:
import fslint
if sys.argv[0][0] != '/':
#If relative probably debugging so don't use system files if possible
if not os.path.exists(liblocation+'/fslint'):
liblocation = fslint.liblocation
locale_base = None #sys default
else:
liblocation = fslint.liblocation
locale_base = None #sys default
except:
pass
class i18n:
def __init__(self):
self._init_translations()
self._init_locale() #after translations in case they reset codeset
self._init_preferred_encoding()
def _init_translations(self):
#gtk2 only understands utf-8 so convert to unicode
#which will be automatically converted to utf-8 by pygtk
gettext.install("fslint", locale_base, unicode=1)
global N_ #translate string but not at point of definition
def N_(string): return string
gettext.bindtextdomain("fslint",locale_base)
gettext.textdomain("fslint")
#Note gettext does not set libc's domain as
#libc and Python may have different message catalog
#formats (e.g. on Solaris). So make explicit calls.
locale.bindtextdomain("fslint",locale_base)
locale.textdomain("fslint")
def _init_locale(self):
try:
locale.setlocale(locale.LC_ALL,'')
except:
#gtk will print warning for a duff locale
pass
def _init_preferred_encoding(self):
#Note that this encoding name is canonlicalised already
self.preferred_encoding=locale.getpreferredencoding(do_setlocale=False)
#filename encoding can be different from default encoding
filename_encoding = os.environ.get("G_FILENAME_ENCODING")
if filename_encoding:
try:
#Try out the encoding to avoid exceptions later.
#For example on Suse 11.4 this is actually a list
# @locale,UTF-8,$west_europe_legacy_encoding,CP1252
#which we don't support for the moment.
"".encode(filename_encoding)
except:
filename_encoding = None
if filename_encoding:
filename_encoding=filename_encoding.lower()
if filename_encoding == "utf8": filename_encoding="utf-8"
self.filename_encoding=filename_encoding
else:
self.filename_encoding=self.preferred_encoding
class unicode_displayable(unicode):
"""translate non displayable chars to an appropriate representation"""
translate_table=range(0x2400,0x2420) #control chars
#Since python 2.2 this will be a new style class as
#we are subclassing the builtin (immutable) unicode type.
#Therefore we can make a factory function with the following.
def __new__(cls,string,exclude):
if exclude:
curr_table=cls.translate_table[:] #copy
for char in exclude:
try:
curr_table[ord(char)]=ord(char)
except:
pass #won't be converted anyway
else:
curr_table=cls.translate_table
translated_string=unicode(string).translate(curr_table)
return unicode.__new__(cls, translated_string)
def displayable_utf8(self,orig,exclude="",path=False):
"""Convert to utf8, and also convert chars that are not
easily displayable (control chars currently).
If orig is not a valid utf8 string,
then try to convert to utf8 using preferred encoding while
also replacing undisplayable or invalid characters.
Exclude contains control chars you don't want to translate."""
if type(orig) == types.UnicodeType:
uc=orig
else:
try:
uc=unicode(orig,"utf-8")
except:
try:
# Note I don't use "replace" here as that
# replaces multiple bytes with a FFFD in utf8 locales
# This is silly as then you know it's not utf8 so
# one should try each character.
if path:
uc=unicode(orig,self.filename_encoding)
else:
uc=unicode(orig,self.preferred_encoding)
except:
uc=unicode(orig,"ascii","replace")
# Note I don't like the "replacement char" representation
# on fedora core 3 at least (bitstream-vera doesn't have it,
# and the nimbus fallback looks like a comma).
# It's even worse on redhat 9 where there is no
# representation at all. Note FreeSans does have a nice
# question mark representation, and dejavu also since 1.12.
# Alternatively I could: uc=unicode(orig,"latin-1") as that
# has a representation for each byte, but it's not general.
uc=self.unicode_displayable(uc, exclude)
return uc.encode("utf-8")
def g_filename_from_utf8(self, string):
if self.filename_encoding != "utf-8":
uc=unicode(string,"utf-8")
string=uc.encode(self.filename_encoding) #can raise exception
return string
I18N=i18n() #call first so everything is internationalized
import getopt
def Usage():
puts(_("Usage: %s [OPTION] [PATHS]") % os.path.split(sys.argv[0])[1])
puts( " --version " + _("display version"))
puts( " --help " + _("display help"))
try:
lOpts, lArgs = getopt.getopt(sys.argv[1:], "", ["help","version"])
if len(lArgs) == 0:
lArgs = [os.getcwd()]
if ("--help","") in lOpts:
Usage()
sys.exit(None)
if ("--version","") in lOpts:
puts("FSlint 2.47")
sys.exit(None)
except getopt.error as msg:
puts(msg)
puts()
Usage()
sys.exit(2)
def human_num(num, divisor=1, power=""):
num=float(num)
if divisor == 1:
return locale.format("%.f",num,1)
elif divisor == 1000:
powers=[" ","K","M","G","T","P"]
elif divisor == 1024:
powers=[" ","Ki","Mi","Gi","Ti","Pi"]
else:
raise ValueError("Invalid divisor")
if not power: power=powers[0]
while num >= 1000: #4 digits
num /= divisor
power=powers[powers.index(power)+1]
if power.strip():
num = locale.format("%6.1f",num,1)
else:
num = locale.format("%4.f",num,1)+' '
return "%s%s" % (num,power)
class pathInfo:
"""Gets path info appropriate for display, i.e.
(ls_colour, du, size, uid, gid, ls_date, mtime)"""
def __init__(self, path):
stat_val = os.lstat(path)
date = time.ctime(stat_val.st_mtime)
month_time = date[4:16]
year = date[-5:]
timediff = time.time()-stat_val.st_mtime
if timediff > 15552000: #6months
date = month_time[0:6] + year
else:
date = month_time
mode = stat_val.st_mode
if stat.S_ISREG(mode):
colour = '' #default
if mode & (stat.S_IXGRP|stat.S_IXUSR|stat.S_IXOTH):
colour = "#00C000"
elif stat.S_ISDIR(mode):
colour = "blue"
elif stat.S_ISLNK(mode):
colour = "cyan"
if not os.path.exists(path):
colour = "#C00000"
else:
colour = "tan"
self.ls_colour = colour
self.du = stat_val.st_blocks*512
self.size = stat_val.st_size
self.uid = stat_val.st_uid
self.gid = stat_val.st_gid
self.ls_date = date
self.mtime = stat_val.st_mtime
self.inode = stat_val.st_ino
class GladeWrapper:
"""
Superclass for glade based applications. Just derive from this
and your subclass should create methods whose names correspond to
the signal handlers defined in the glade file. Any other attributes
in your class will be safely ignored.
This class will give you the ability to do:
subclass_instance.GtkWindow.method(...)
subclass_instance.widget_name...
"""
def __init__(self, Filename, WindowName):
#load glade file.
self.widgets = gtk.glade.XML(Filename, WindowName, gettext.textdomain())
self.GtkWindow = getattr(self, WindowName)
instance_attributes = {}
for attribute in dir(self.__class__):
instance_attributes[attribute] = getattr(self, attribute)
self.widgets.signal_autoconnect(instance_attributes)
def __getattr__(self, attribute): #Called when no attribute in __dict__
widget = self.widgets.get_widget(attribute)
if widget is None:
raise AttributeError("Widget [" + attribute + "] not found")
self.__dict__[attribute] = widget #add reference to cache
return widget
# SubProcess Example:
#
# process = subProcess("your shell command")
# process.read() #timeout is optional
# handle(process.outdata, process.errdata)
# del(process)
import select, signal
class subProcess:
"""Class representing a child process. It's like popen2.Popen3
but there are three main differences.
1. This makes the new child process group leader (using setpgrp())
so that all children can be killed.
2. The output function (read) is optionally non blocking returning in
specified timeout if nothing is read, or as close to specified
timeout as possible if data is read.
3. The output from both stdout & stderr is read (into outdata and
errdata). Reading from multiple outputs while not deadlocking
is not trivial and is often done in a non robust manner."""
def __init__(self, cmd, bufsize=8192):
"""The parameter 'cmd' is the shell command to execute in a
sub-process. If the 'bufsize' parameter is specified, it
specifies the size of the I/O buffers from the child process."""
self.cleaned=False
self.BUFSIZ=bufsize
self.outr, self.outw = os.pipe()
self.errr, self.errw = os.pipe()
self.pid = os.fork()
if self.pid == 0:
self._child(cmd)
os.close(self.outw) #parent doesn't write so close
os.close(self.errw)
# Note we could use self.stdout=fdopen(self.outr) here
# to get a higher level file object like popen2.Popen3 uses.
# This would have the advantages of auto handling the BUFSIZ
# and closing the files when deleted. However it would mean
# that it would block waiting for a full BUFSIZ unless we explicitly
# set the files non blocking, and there would be extra uneeded
# overhead like EOL conversion. So I think it's handier to use os.read()
self.outdata = self.errdata = ''
self._outeof = self._erreof = 0
def _child(self, cmd):
# Note exec doesn't reset SIG_IGN -> SIG_DFL
# and python sets SIGPIPE etc. to SIG_IGN, so reset:
# http://bugs.python.org/issue1652
signals = ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ')
for sig in signals:
if hasattr(signal, sig):
signal.signal(getattr(signal, sig), signal.SIG_DFL)
# Note sh below doesn't setup a seperate group (job control)
# for non interactive shells (hmm maybe -m option does?)
os.setpgrp() #seperate group so we can kill it
os.dup2(self.outw,1) #stdout to write side of pipe
os.dup2(self.errw,2) #stderr to write side of pipe
#stdout & stderr connected to pipe, so close all other files
map(os.close,(self.outr,self.outw,self.errr,self.errw))
try:
cmd = ['/bin/sh', '-c', cmd]
os.execvp(cmd[0], cmd)
finally: #exit child on error
os._exit(1)
def read(self, timeout=None):
"""return 0 when finished
else return 1 every timeout seconds
data will be in outdata and errdata"""
currtime=time.time()
while 1:
tocheck=[self.outr]*(not self._outeof)+ \
[self.errr]*(not self._erreof)
ready = select.select(tocheck,[],[],timeout)
if len(ready[0]) == 0: #no data timeout
return 1
else:
if self.outr in ready[0]:
outchunk = os.read(self.outr,self.BUFSIZ)
if outchunk == '':
self._outeof = 1
self.outdata += outchunk
if self.errr in ready[0]:
errchunk = os.read(self.errr,self.BUFSIZ)
if errchunk == '':
self._erreof = 1
self.errdata += errchunk
if self._outeof and self._erreof:
return 0
elif timeout:
if (time.time()-currtime) > timeout:
return 1 #may be more data but time to go
def kill(self):
os.kill(-self.pid, signal.SIGTERM) #kill whole group
def pause(self):
os.kill(-self.pid, signal.SIGSTOP) #pause whole group
def resume(self):
os.kill(-self.pid, signal.SIGCONT) #resume whole group
def cleanup(self):
"""Wait for and return the exit status of the child process."""
self.cleaned=True
os.close(self.outr)
os.close(self.errr)
pid, sts = os.waitpid(self.pid, 0)
if pid == self.pid:
self.sts = sts
else:
self.sts = None
return self.sts
def __del__(self):
if not self.cleaned:
self.cleanup()
# Determine what type of distro we're on.
class distroType:
def __init__(self):
types = ("rpm", "dpkg", "pacman")
for dist in types:
setattr(self, dist, False)
if os.path.exists("/etc/redhat-release"):
self.rpm = True
elif os.path.exists("/etc/debian_version"):
self.dpkg = True
elif os.path.exists("/etc/arch-release"):
self.pacman = True
else:
for dist in types:
cmd = dist + " --version >/dev/null 2>&1"
if os.WEXITSTATUS(os.system(cmd)) == 0:
setattr(self, dist, True)
break
dist_type=distroType()
def human_space_left(where):
(device, total, used_b, avail, used_p, mount)=\
os.popen("df -Ph %s | tail -n1" % where).read().split()
translation_map={"percent":used_p, "disk":mount, "size":avail}
return _("%(percent)s of %(disk)s is used leaving %(size)sB available") %\
translation_map
# Avoid using clist.get_selectable() which is O(n)
def get_selectable(row, row_data):
return row_data[row][0] != '#'
class dlgUserInteraction(GladeWrapper):
"""
Note input buttons tuple text should not be translated
so that the stock buttons are used if possible. But the
translations should be available, so use N_ for input
buttons tuple text. Note the returned response is not
translated either. Note also, that if you know a stock
button is already available, then there's no point in
translating the passed in string.
"""
def init(self, app, message, buttons, entry_default,
again=False, again_val=True):
for text in buttons:
try:
stock_text=getattr(gtk,"STOCK_"+text.upper())
button = gtk.Button(stock=stock_text)
except:
button = gtk.Button(label=_(text))
button.set_data("text", text)
button.connect("clicked", self.button_clicked)
self.GtkWindow.action_area.pack_start(button)
button.show()
button.set_flags(gtk.CAN_DEFAULT)
button.grab_default() #last button is default
self.app = app
self.lblmsg.set_text(message)
self.lblmsg.show()
self.response=None
if message.endswith(":"):
if entry_default:
self.entry.set_text(entry_default)
self.entry.show()
self.input=None
else:
self.entry.hide()
if again:
self.again=again_val
if type(again) == types.StringType:
self.chkAgain.set_label(again)
self.chkAgain.set_active(again_val)
#Dialog seems to give focus to first available widget,
#So undo the focus on the check box
self.GtkWindow.action_area.get_children()[-1].grab_focus()
self.chkAgain.show()
def show(self):
self.GtkWindow.set_transient_for(self.app.GtkWindow)#center on main win
self.GtkWindow.show() #Note dialog is initially hidden in glade file
if self.GtkWindow.modal:
gtk.main() #synchronous call from parent
#else: not supported
#################
# Signal handlers
#################
def quit(self, *args):
if self.GtkWindow.modal:
gtk.main_quit()
def button_clicked(self, button):
self.response = button.get_data("text")
if self.entry.flags() & gtk.VISIBLE:
self.input = self.entry.get_text()
if self.chkAgain.flags() & gtk.VISIBLE:
self.again = self.chkAgain.get_active()
self.GtkWindow.destroy()
class dlgPath(GladeWrapper):
def init(self, app):
self.app = app
self.pwd = self.app.pwd
def show(self, fileOps=False, filename=""):
self.canceled = True
self.fileOps = fileOps
if self.fileOps:
# Change to last folder as more likely to want
# to save results there
self.GtkWindow.set_action(gtk.FILE_CHOOSER_ACTION_SAVE)
self.GtkWindow.set_current_folder(self.pwd)
self.GtkWindow.set_current_name(filename)
else:
self.GtkWindow.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
# set_filename doesn't highlight dir after first call
# so using select_filename for consistency. Also I think
# select_filename is better than set_current_folder as
# it allows one to more easily select items at the same level
self.GtkWindow.select_filename(self.pwd)
self.GtkWindow.set_transient_for(self.app.GtkWindow)#center on main win
self.GtkWindow.show()
if self.GtkWindow.modal:
gtk.main() #synchronous call from parent
#else: not supported
#################
# Signal handlers
#################
def quit(self, *args):
self.GtkWindow.hide()
if not self.canceled:
if self.fileOps:
self.pwd = self.GtkWindow.get_current_folder()
else:
user_path = self.GtkWindow.get_filename()
if os.path.exists(user_path):
self.pwd = user_path
if self.GtkWindow.modal:
gtk.main_quit()
return True #Don't let window be destroyed
def on_ok_clicked(self, *args):
file = self.GtkWindow.get_filename()
if not file:
# This can happen for the fileOps case, or otherwise
# if one clicks on the "recently used" group and
# then clicks Ok without selecting anything.
return True #Don't let window be destroyed
if self.fileOps: #creating new item
if os.path.isdir(file):
self.GtkWindow.set_current_folder(file)
return True #Don't let window be destroyed
if os.path.exists(file):
if os.path.isfile(file):
(response,) = self.app.msgbox(
_("Do you want to overwrite?\n") + file,
('Yes', 'No')
)
if response != "Yes":
return
else:
self.app.msgbox(_("You can't overwrite ") + file)
return
self.canceled = False
self.quit()
class fslint(GladeWrapper):
class UserAbort(Exception):
pass
def __init__(self, Filename, WindowName):
os.close(0) #don't hang if any sub cmd tries to read from stdin
os.open("/dev/null", os.O_RDONLY)
self.pwd=os.path.realpath(os.curdir)
GladeWrapper.__init__(self, Filename, WindowName)
self.dlgPath = dlgPath(liblocation+"/fslint.glade", "PathChoose")
self.dlgPath.init(self)
self.confirm_delete = True
self.confirm_delete_group = True
self.confirm_clean = True
#Just need to keep this tuple in sync with tabs
(self.mode_up, self.mode_pkgs, self.mode_nl, self.mode_sn,
self.mode_tf, self.mode_bl, self.mode_id, self.mode_ed,
self.mode_ns, self.mode_rs) = range(10)
self.clists = {
self.mode_up:self.clist_dups,
self.mode_pkgs:self.clist_pkgs,
self.mode_nl:self.clist_nl,
self.mode_sn:self.clist_sn,
self.mode_tf:self.clist_tf,
self.mode_bl:self.clist_bl,
self.mode_id:self.clist_id,
self.mode_ed:self.clist_ed,
self.mode_ns:self.clist_ns,
self.mode_rs:self.clist_rs
}
self.mode_descs = {
self.mode_up:_("Files with the same content"),
self.mode_pkgs:_("Installed packages ordered by disk usage"),
self.mode_nl:_("Problematic filenames"),
self.mode_sn:_("Possibly conflicting commands or filenames"),
self.mode_tf:_("Possibly old temporary files"),
self.mode_bl:_("Problematic symbolic links"),
self.mode_id:_("Files with missing user IDs"),
self.mode_ed:_("Directory branches with no files"),
self.mode_ns:_("Executables still containing debugging info"),
self.mode_rs:_("Erroneous whitespace in a text file")
}
for path in lArgs:
if os.path.exists(path):
self.addDirs(self.ok_dirs, os.path.abspath(path))
else:
self.ShowErrors(_("Invalid path [") + path + "]")
for bad_dir in ['/lost+found','/dev','/proc','/sys','/tmp',
'*/.svn','*/CVS', '*/.git', '*/.hg', '*/.bzr',
'*/node_modules']:
self.addDirs(self.bad_dirs, bad_dir)
self._alloc_mouse_cursors()
self.mode=0
self.status.set_text(self.mode_descs[self.mode])
self.bg_colour=self.vpanes.get_style().bg[gtk.STATE_NORMAL]
#make readonly GtkEntry and GtkTextView widgets obviously so,
#by making them the same colour as the surrounding panes
self.errors.modify_base(gtk.STATE_NORMAL,self.bg_colour)
self.status.modify_base(gtk.STATE_NORMAL,self.bg_colour)
self.pkg_info.modify_base(gtk.STATE_NORMAL,self.bg_colour)
#Other GUI stuff that ideally [lib]glade should support
self.clist_pkgs.set_column_visibility(2,0)
self.clist_pkgs.set_column_visibility(3,0)
self.clist_ns.set_column_justification(2,gtk.JUSTIFY_RIGHT)
def _alloc_mouse_cursors(self):
#The following is the cursor used by mozilla and themed by X/distros
left_ptr_watch = \
"\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x0c\x00\x00\x00"\
"\x1c\x00\x00\x00\x3c\x00\x00\x00\x7c\x00\x00\x00\xfc\x00\x00\x00"\
"\xfc\x01\x00\x00\xfc\x3b\x00\x00\x7c\x38\x00\x00\x6c\x54\x00\x00"\
"\xc4\xdc\x00\x00\xc0\x44\x00\x00\x80\x39\x00\x00\x80\x39"+"\x00"*66
try:
pix = gtk.gdk.bitmap_create_from_data(None, left_ptr_watch, 32, 32)
color = gtk.gdk.Color()
self.LEFT_PTR_WATCH=gtk.gdk.Cursor(pix, pix, color, color, 2, 2)
#Note mask is ignored when doing the hash
except TypeError:
#http://bugzilla.gnome.org/show_bug.cgi?id=103616 #older pygtks
#http://bugzilla.gnome.org/show_bug.cgi?id=318874 #pygtk-2.8.[12]
#Note pygtk-2.8.1 was released with ubuntu breezy :(
self.LEFT_PTR_WATCH=None #default cursor
self.SB_V_DOUBLE_ARROW=gtk.gdk.Cursor(gtk.gdk.SB_V_DOUBLE_ARROW)
self.XTERM=gtk.gdk.Cursor(gtk.gdk.XTERM) #I beam
self.WATCH=gtk.gdk.Cursor(gtk.gdk.WATCH) #hourglass
def get_fslint(self, command, delim='\n'):
self.fslintproc = subProcess(command)
self.status.set_text(_("searching")+"...")
while self.fslintproc.read(timeout=0.1):
while gtk.events_pending(): gtk.main_iteration(False)
if self.stopflag:
if self.paused:
self.fslintproc.resume()
self.fslintproc.kill()
break
elif self.pauseflag:
self.pause_search()
else:
self.fslintproc.outdata=self.fslintproc.outdata.split(delim)[:-1]
ret = (self.fslintproc.outdata, self.fslintproc.errdata)
#we can't control internal processing at present so hide buttons
self.pause.hide()
self.resume.hide()
self.stop.hide()
self.status.set_text(_("processing..."))
while gtk.events_pending(): gtk.main_iteration(False)
del(self.fslintproc)
if self.stopflag:
raise self.UserAbort
else:
return ret
def ShowErrors(self, lines):
if len(lines) == 0:
return
end=self.errors.get_buffer().get_end_iter()
self.errors.get_buffer().insert(end,I18N.displayable_utf8(lines,"\n"))
def ClearErrors(self):
self.errors.get_buffer().set_text("")
def buildFindParameters(self):
if self.mode == self.mode_sn:
if self.chk_sn_path.get_active():
return ""
elif self.mode == self.mode_ns:
if self.chk_ns_path.get_active():
return ""
elif self.mode == self.mode_pkgs:
return ""
if self.ok_dirs.rows == 0:
return _("No search paths specified")
search_dirs = ""
for row in range(self.ok_dirs.rows):
search_dirs += " " + pipes.quote(self.ok_dirs.get_row_data(row))
exclude_dirs=""
# One can't remove directories listed as empty if
# they have .git/ dirs etc. so ignore the exluded paths here
if self.mode != self.mode_ed:
for row in range(self.bad_dirs.rows):
if exclude_dirs == "":
exclude_dirs = '\(' + ' -path '
else:
exclude_dirs += ' -o -path '
exclude_dirs += pipes.quote(self.bad_dirs.get_row_data(row))
if exclude_dirs != "":
exclude_dirs += ' \) -prune -o '
if not self.recurseDirs.get_active():
recurseParam=" -r "
else:
recurseParam=" "
self.findParams = search_dirs + " -f " + recurseParam + exclude_dirs
if self.mode == self.mode_up:
min_size = self.min_size.get_text()
if min_size == '0' or min_size == '':
min_size=''
elif min_size[-1].isdigit():
min_size=str(int(min_size)-1)
min_size += 'c'
if min_size:
self.findParams += '-size +' + min_size + ' '
self.findParams += self.extra_find_params.get_text()
return ""
def addDirs(self, dirlist, dirs):
"""Adds items to passed clist."""
dirlist.append([I18N.displayable_utf8(dirs,path=True)])
dirlist.set_row_data(dirlist.rows-1, dirs)
def removeDirs(self, dirlist):
"""Removes selected items from passed clist.
If no items selected then list is cleared."""
paths_to_remove = dirlist.selection
if len(paths_to_remove) == 0:
dirlist.clear()
else:
paths_to_remove.sort() #selection order irrelevant/problematic
paths_to_remove.reverse() #so deleting works correctly
for row in paths_to_remove:
dirlist.remove(row)
dirlist.select_row(dirlist.focus_row,0)
def clist_alloc_colour(self, clist, colour):
"""cache colour allocation for clist
as colour will probably be used multiple times"""
cmap = clist.get_colormap()
cmap_cache=clist.get_data("cmap_cache")
if cmap_cache == None:
cmap_cache={'':None}
if colour not in cmap_cache:
cmap_cache[colour]=cmap.alloc_color(colour)
clist.set_data("cmap_cache",cmap_cache)
return cmap_cache[colour]
def clist_append_path(self, clist, path, colour, *rest):
"""append path to clist, handling utf8 and colour issues"""
colour = self.clist_alloc_colour(clist, colour)
utf8_path=I18N.displayable_utf8(path,path=True)
(dir,file)=os.path.split(utf8_path)
clist.append((file,dir)+rest)
row_data = clist.get_data("row_data")
row_data.append(path+'\n') #add '\n' so can write with writelines
if colour:
clist.set_foreground(clist.rows-1,colour)
def clist_append_group_row(self, clist, cols):
"""append header to clist"""
clist.append(cols)
row_data = clist.get_data("row_data")
row_data.append('#'+"\t".join(cols).rstrip()+'\n')
clist.set_background(clist.rows-1,self.bg_colour)
clist.set_selectable(clist.rows-1,0)
def clist_remove_handled_groups(self, clist):
row_data = clist.get_data("row_data")
rowver=clist.rows
rows_left = range(rowver)
rows_left.reverse()
for row in rows_left:
if not get_selectable(row, row_data):
if row == clist.rows-1 or not get_selectable(row+1, row_data):
clist.remove(row)
row_data.pop(row)
else: #remove single item groups
if row == clist.rows-1 and not get_selectable(row-1, row_data):
clist.remove(row)
row_data.pop(row)
elif not ((row!=0 and get_selectable(row-1, row_data)) or
(row!=clist.rows-1 and get_selectable(row+1, row_data))):
clist.remove(row)
row_data.pop(row)
def whatRequires(self, packages, level=0):
if not packages: return
if level==0: self.checked_pkgs={}
for package in packages:
#puts("\t"*level+package)
self.checked_pkgs[package]=''
if dist_type.rpm:
cmd = r"rpm -e --test " + ' '.join(packages) + r" 2>&1 | "
cmd += r"sed -n 's/-[0-9]\{1,\}:/-/; " #strip epoch
cmd += r" s/.*is needed by (installed) \(.*\)/\1/p' | "
cmd += r"LANG=C sort | uniq"
elif dist_type.dpkg:
cmd = r"dpkg --purge --dry-run " + ' '.join(packages) + r" 2>&1 | "
cmd += r"sed -n 's/ \(.*\) depends on.*/\1/p' | "
cmd += r"LANG=C sort | uniq"
elif dist_type.pacman:
cmd = r"LC_ALL=C pacman -Qi " + ' '.join(packages)
cmd += r" 2>/dev/null | tr '\n' ' ' | "
cmd += r"sed -e 's/Name .* Required By \{1,\}: \{1,\}//' -e "
cmd += r"'s/Conflicts With .*//' -e 's/ \{18\}//g' -e "
cmd += r"'s/ \{1,\}$/\n/'"
else:
raise RuntimeError("unknown distro")
process = os.popen(cmd)
requires = process.read()
del(process)
new_packages = [p for p in requires.split()
if p not in self.checked_pkgs]
self.whatRequires(new_packages, level+1)
if level==0: return self.checked_pkgs.keys()
def findpkgs(self, clist_pkgs):
self.clist_pkgs_order=[False,False] #unordered, descending
self.clist_pkgs_user_input=False
self.pkg_info.get_buffer().set_text("")
if dist_type.dpkg:
#Package names unique on debian
cmd = r"dpkg-query -W --showformat='${Package}\t${Installed-Size}"
cmd += r"\t${Status}\n' | LANG=C grep -F 'installed' | cut -f1,2 | "
cmd += r"sed 's/[^0-9]$/\t0/'" #packages with missing size = 0
elif dist_type.rpm:
#Must include version names to uniquefy on redhat
cmd = r"rpm -qa --queryformat '%{N}-%{V}-%{R}.%{ARCH}\t%{SIZE}\n'"
elif dist_type.pacman:
cmd = r"pacman -Q | sed -n 's/^\([^ ]\{1,\}\) .*/\1/p' | "
cmd += r"LC_ALL=C xargs pacman -Qi | sed -n -e "
cmd += r"'s/Installed Size : \([^ ]*\) \([^ ]*\)B/\1\2/p' | "
cmd += r"numfmt --from=auto"
else:
return ("", _("Sorry, FSlint does not support this functionality \
on your system at present."))
po, pe = self.get_fslint(cmd + " | LANG=C sort -k2,2rn")
pkg_tot = 0
row = 0
for pkg_info in po:
pkg_name, pkg_size= pkg_info.split()
pkg_size = int(float(pkg_size))
if dist_type.dpkg:
pkg_size *= 1024
pkg_tot += pkg_size
clist_pkgs.append([pkg_name,human_num(pkg_size,1000).strip(),
"%010ld"%pkg_size,"0"])
clist_pkgs.set_row_data(row, pkg_name)
row += 1
return (str(row) + _(" packages, ") +
_("consuming %sB. ") % human_num(pkg_tot,1000).strip() +
_("Note %s.") % human_space_left('/'), pe)
#Note pkgs generally installed on root partition so report space left.
def findrs(self, clist_rs):
options=""
if self.chkWhitespace.get_active():
options += "-w "
if self.chkTabs.get_active():
options += "-t%d " % int(self.spinTabs.get_value())
if not options:
return ("","")
po, pe = self.get_fslint("./findrs " + options + self.findParams)
row = 0
for line in po:
pi = pathInfo(line)
self.clist_append_path(clist_rs, line,
pi.ls_colour, str(pi.size), pi.ls_date)
row += 1
return (str(row) + _(" files"), pe)
def findns(self, clist_ns):
cmd = "./findns "
if not self.chk_ns_path.get_active():
cmd += self.findParams
po, pe = self.get_fslint(cmd)
unstripped=[]
for line in po:
pi = pathInfo(line)
unstripped.append((pi.size, line, pi.ls_date))
unstripped.sort()
unstripped.reverse()
row = 0
for size, path, ls_date in unstripped:
self.clist_append_path(clist_ns, path, '', human_num(size), ls_date)
row += 1
return (str(row) + _(" unstripped binaries"), pe)
def finded(self, clist_ed):
po, pe = self.get_fslint("./finded " + self.findParams, '\0')
row = 0
for line in po:
self.clist_append_path(clist_ed, line, '', pathInfo(line).ls_date)
row += 1
return (str(row) + _(" empty directories"), pe)
def findid(self, clist_id):
po, pe = self.get_fslint("./findid " + self.findParams, '\0')
row = 0
for record in po:
pi = pathInfo(record)
self.clist_append_path(clist_id, record, pi.ls_colour, str(pi.uid),
str(pi.gid), str(pi.size), pi.ls_date)
row += 1
return (str(row) + _(" files"), pe)
def findbl(self, clist_bl):
cmd = "./findbl " + self.findParams
if self.opt_bl_dangling.get_active():
cmd += " -d"
elif self.opt_bl_suspect.get_active():
cmd += " -s"
elif self.opt_bl_relative.get_active():
cmd += " -l"
elif self.opt_bl_absolute.get_active():
cmd += " -A"
elif self.opt_bl_redundant.get_active():
cmd += " -n"
po, pe = self.get_fslint(cmd)
row = 0
for line in po:
link, target = line.split(" -> ", 2)
self.clist_append_path(clist_bl, link, '', target)
row += 1
return (str(row) + _(" links"), pe)
def findtf(self, clist_tf):
cmd = "./findtf " + self.findParams
cmd += " --age=" + str(int(self.spin_tf_core.get_value()))
if self.chk_tf_core.get_active():
cmd += " -c"
po, pe = self.get_fslint(cmd)
row = 0
byteWaste = 0
for line in po:
pi = pathInfo(line)
self.clist_append_path(clist_tf, line, '', str(pi.size), pi.ls_date)
byteWaste += pi.du
row += 1
return (human_num(byteWaste,1000).strip() + 'B' + _(" wasted in ") +
str(row) + _(" files"), pe)
def findsn(self, clist_sn):
cmd = "./findsn "
if self.chk_sn_path.get_active():
option = self.opt_sn_path.get_children()[0].get()
if option == _("Aliases"):
cmd += " -A"
elif option == _("Conflicting files"):
pass #default mode
else:
raise RuntimeError("glade GtkOptionMenu item not found")
else:
cmd += self.findParams
option = self.opt_sn_paths.get_children()[0].get()
if option == _("Aliases"):
cmd += " -A"
elif option == _("Same names"):
pass #default mode
elif option == _("Same names(ignore case)"):
cmd += " -C"
elif option == _("Case conflicts"):
cmd += " -c"
else: