-
Notifications
You must be signed in to change notification settings - Fork 1
/
register.py
909 lines (771 loc) · 33.1 KB
/
register.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
import datetime
import fnmatch
import functools
import glob
import os
import os.path
import re
import threading
import time
from MySum import MySum
from PathTemplates import PathTemplates
from RegfileConfiguration import RegfileConfiguration
from db.DBConnection import DBConnection
from db.DBFile import DBFile
from db.DBFileQueryArguments import DBFileQueryArguments
from db.DBFileRegister import DBFileRegister
from progressbar import progressbar
class Register(object):
DEFAULTFILES = ["_.regfiledefaults", ".regfiledefaults"]
LOGCOMMENT="# "
LOGADD="+ "
LOGUPDATE="! "
LOGUPDATED="!! "
RULER=" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "
LOG_DBFILE_RE = re.compile(
r"^DBF(?P<fileId>\d*)\|" +
r"n:(?P<fileName>.*)\|" +
r"g:(?P<group>.*)\|" +
r"c:(?P<comment>.*)\|" +
r"s:(?P<fileSize>\d*)\|" +
r"md1:(?P<md1>.*)\|" +
r"md5:(?P<md5>.*)\|" +
r"ed2k:(?P<ed2k>.*)\|$"
)
def __init__(self, args):
"""
initialize the register, read parsed arguments, set the desired operation (op)
"""
# setup configuration {{{
self.configuration = RegfileConfiguration()
self.dbFilePath = self.configuration[RegfileConfiguration.DB]
self.logfile = self.configuration[RegfileConfiguration.LOG]
# }}}
# arguments
self.fileId = args.fileId
self.group = args.group
self.comment = args.comment
self.files = args.filenames
self.queryasmysum = args.queryasmysum
self.queryverbose = args.queryverbose
self.queryed2k = args.queryed2k
self.auto= args.auto
self.defaults = args.defaults
self.determineconfirm(args)
# defaults
self.dbConnection = None # database connection
self.op = None # operation function
self.logf = None # log file
self.pathTemplates = None # path templates
self.totalsize = 0 # the size of all the files to register/check in bytes
self.defaultcache = dict() # cache with default values
self.cols = 80 # terminal columns (accurate where supported - Linux/Unix)
if (not self.configuration.fromConfigFile):
import textwrap as tw
print(tw.fill(tw.dedent("""
The configuration file '{0}' didn't exist, so a default has been created!
That also means that a default location for the database '{1}' is being
used. Review and change the configuration if necessary! The requested
operation has been canceled. (This warning is displayed only once!)
""".format(self.configuration.path, self.dbFilePath))
, initial_indent="!!! ", subsequent_indent="!!! "))
return
# key: the op code, value: op function, thorough for processfiles
dd = { \
"r" : (self.register, True),\
"c" : (self.check, True),\
"i": (self.batchimport, True),\
"s" : (self.setdata, False),\
"q" : (self.query, False),\
"l" : (self.resetfromlog, False),\
"d" : (self.makedefaults, False),\
}
if not args.op in dd:
raise ValueError(
"Operation '{}' is not supported!"
.format(args.op))
self.op = dd[args.op][0]
if self.op != self.resetfromlog:
self.dbConnection = DBConnection(self.dbFilePath)
self.processfiles(thorough=dd[args.op][1])
try:
self.cols = int(os.popen('stty size', 'r').read().split()[1])
except:
pass
def go(self):
"""
just run the designed doperation
"""
try:
if self.op:
self.op()
finally:
if self.logf:
self.logf.close()
if self.dbConnection:
self.dbConnection.close()
def determineconfirm(self, args):
"""arguments take precedence over configuration"""
self.confirm = self.confirmproblem = False
if args.commit: # specified on command line
cc = args.commit
else: # get value from config instead
cc = self.configuration[RegfileConfiguration.COMMIT]
self.confirm = (cc == "confirm")
self.confirmproblem = (cc == "problem")
def docommit(self, problems):
if self.confirm or (self.confirmproblem and problems):
while True:
response = input("Do you wish to commit these changes? [YES/no] ").lower().strip()
if (response not in ["", "yes", "y", "no", "n"]):
print("Only yes or no (or just Enter) is a valid choice.")
continue
return (response in ["", "yes", "y"])
return True
def register(self):
return self.registercheck(True)
def check(self):
return self.registercheck(False)
def registercheck(self, register):
"""
register (or check) the given files
"""
pgr, pcom, pdir, psize = "", "", "", 0 # previous group, comment, directory and size
tstart = time.time()
ii = 0
failfiles = []
dbFilesToStore = []
with self.dbConnection.getSessionContext() as session:
for ff in self.files:
ii = ii + 1
fileMightBeRegistered = False
cdir = os.path.dirname(ff) # directory
sff = os.path.basename(ff) # short filename
try:
if cdir != pdir:
print("Directory [{}]".format(cdir))
pdir = cdir
dbf = DBFile(fileName = sff)
if register: # group and comment
gr, com = self.getgroupcomment(ff)
if gr != pgr or com != pcom:
print("Using group:'{}' comment:'{}'".format(gr, com))
pgr, pcom = gr, com
dbf.group, dbf.comment = gr, com
self.printstatus(ii, sff, "Quick")
# stage 1 - silent
ms = MySum(ff)
ms.upgrade(1)
dbf.fileSize = ms.fileSize
dbf.md1 = ms.md1
fileMightBeRegistered = self._determineFileMightBeRegistered(
session = session,
fileSize = dbf.fileSize,
md1 = dbf.md1,
)
if ((not register) and (not fileMightBeRegistered)):
self.printstatus(ii, sff, "FAILED")
failfiles.append(ff)
print()
continue
tt = threading.Thread(target=ms.upgrade,args=[2])
tt.start()
while tt.is_alive():
try:
self.printstatus(ii, sff, self.msgpgs(ms,psize,tstart,fileMightBeRegistered))
time.sleep(0.25)
except KeyboardInterrupt:
ms.requestStop()
tt.join()
raise
tt.join()
psize = psize + ms.fileSize
dbf.md5 = ms.md5
dbf.ed2k = ms.ed2k
matchingDBFile = self._determineMatchingDBFile(
session = session,
fileSize = dbf.fileSize,
md1 = dbf.md1,
md5 = dbf.md5,
ed2k = dbf.ed2k,
)
fullMatch = (
(matchingDBFile is not None) and
(dbf.fileName == matchingDBFile.fileName) and
(dbf.group == matchingDBFile.group) and
(dbf.comment == matchingDBFile.comment)
)
if register:
if (matchingDBFile is None):
DBFileRegister.insert(session, dbf, commit=False)
self.printstatus(ii, sff, "New entry " + str(dbf.fileId))
dbFilesToStore.append(dbf)
else:
if (fullMatch):
self.printstatus(ii, sff, "Already registered (full match) as " + str(matchingDBFile.fileId))
else:
self.printstatus(ii, sff, "Already registered (data match) as " + str(matchingDBFile.fileId))
failfiles.append(ff)
else:
if (matchingDBFile is None):
self.printstatus(ii, sff, "FAILED")
failfiles.append(ff)
else:
stat = "OK"
if (dbf.fileName != matchingDBFile.fileName):
stat = "(as " + matchingDBFile.fileName + ") OK"
stat = "id:" + str(matchingDBFile.fileId) + " " + stat
self.printstatus(ii, sff, stat)
print()
except KeyboardInterrupt:
self.printstatus(ii, sff, "Interrupted")
failfiles.append(ff + " (Interrupted)")
print()
break
print(self.RULER)
if register:
print("About to register {} files out of {}".format(ii-len(failfiles),ii))
else:
print("Passed {} files out of {}.{}".format(ii-len(failfiles), ii, "ALL OK" if not len(failfiles) else "" ))
if len(failfiles) > 0:
print("A list of files that failed:")
for ff in failfiles:
print(" " + ff)
if register:
if len(failfiles) == ii:
print("No files were registered!")
elif self.docommit(failfiles):
session.commit()
for storedDBFile in dbFilesToStore:
self.log(Register.LOGADD + self._formatDBFileForLog(storedDBFile))
print("Done.")
else:
print("Aborted!")
@staticmethod
def _determineFileMightBeRegistered(session, fileSize, md1):
# DOC {{{
"""Returns True if there is a registered file of the size and the MD5
sum of the first megabyte specified in the provided DBFile(), False
otherwise.
Parameters
session -- an instance of the SQLAlchemy's Session()
fileSize -- the size of the file to look for in bytes
md1 -- the MD5 sum of the first megabyte of the file
"""
# }}}
# CODE {{{
dbfs = DBFileRegister.query(
session = session,
fileSize = fileSize,
md1 = md1,
)
return (dbfs is not None)
# }}}
@staticmethod
def _determineMatchingDBFile(session, fileSize, md1, md5, ed2k):
# DOC {{{
"""Returns the DBFile() that matches the size, the MD5 sum of the first
megabyte, the MD5 sum of the entire file and the ED2K sum of the
specified DBFile() and is already registered in the register.
Parameters
session -- an instance of the SQLAlchemy's Session()
fileSize -- the size of the file to look for in bytes
md1 -- the MD5 sum of the first megabyte of the file
md1 -- the MD5 sum of the entire file
ed2k -- the ED2K sum of the entire file
"""
# }}}
# CODE {{{
dbfs = DBFileRegister.query(
session = session,
fileSize = fileSize,
md1 = md1,
md5 = md5,
ed2k = ed2k,
)
if ((dbfs is None) or (len(dbfs) == 0)):
return None
else:
return dbfs[0]
# }}}
def batchimport(self):
"""
store all data stored in the provided files (usually named like sumlog.txt)
Only [MYSUM...] entries are valid.
"""
pgr, pcom, pdir = "", "", "" # previous group, comment and directory
ii = 0 # file no
jj = 0 # successfully imported entries
warn = 0 # number of warnings (duplicities)
failfiles = [] # a list of files that failed to import
allDBFilesToStore = []
with self.dbConnection.getSessionContext() as session:
for ff in self.files:
ii = ii + 1
cdir = os.path.dirname(ff) # directory
if cdir != pdir:
print("Directory [{}]".format(cdir))
pdir = cdir
gr, com = self.getgroupcomment(ff, imp=True)
if gr != pgr or com != pcom:
print("Using group:{} comment:{}".format(gr, com))
pgr, pcom = gr, com
self.printstatus(ii, ff, "")
with open(ff, "r") as fsum:
ll = 0
fail = False
dbFilesToStoreFromImportFile = []
for line in fsum:
ll = ll + 1
self.printstatus(ii, ff, "L" + str(ll))
try:
ms = MySum.fromString(line)
except ValueError:
self.printstatus(ii, ff, "not a MYSUM!")
print()
fail = True
break
self.printstatus(ii, ff, ms.fileName + " L" + str(ll))
dbf = DBFile(
fileName = ms.fileName,
group = gr,
comment = com,
fileSize = ms.fileSize,
md1 = ms.md1,
md5 = ms.md5,
ed2k = ms.ed2k,
)
matchingDBFile = self._determineMatchingDBFile(
session = session,
fileSize = dbf.fileSize,
md1 = dbf.md1,
md5 = dbf.md5,
ed2k = dbf.ed2k,
)
fullMatch = ((matchingDBFile is not None) and
(dbf.fileName == matchingDBFile.fileName) and
(dbf.group == matchingDBFile.group) and
(dbf.comment == matchingDBFile.comment))
if (matchingDBFile):
warn = warn + 1
if (fullMatch):
self.printstatus(ii, ff, "Already registered (full match) as {} L{}".format(matchingDBFile.fileId, ll))
else:
self.printstatus(ii, ff, "Already registered (data match) as {} L{}".format(matchingDBFile.fileId, ll))
print()
continue
jj = jj + 1
dbFilesToStoreFromImportFile.append(dbf)
if fail:
if ll == 1:
self.printstatus(ii, ff, "FAILED")
failfiles.append(ff)
print()
else:
sll = "after " + str(ll) + " lines"
self.printstatus(ii, ff, "FAILED " + sll)
failfiles.append(ff + " (" + sll + ")")
print()
else:
for dbf in dbFilesToStoreFromImportFile:
DBFileRegister.insert(session, dbf, commit=False)
allDBFilesToStore.extend(dbFilesToStoreFromImportFile)
print()
print(self.RULER)
print("About to import {} entries ({} warnings) from {} files out of {}".format(jj, warn, len(self.files) - len(failfiles), len(self.files)))
if len(failfiles) > 0:
print("A list of files that failed:")
for ff in failfiles:
print(" " + ff)
if self.docommit(failfiles):
session.commit()
for storedDBFile in allDBFilesToStore:
self.log(Register.LOGADD + self._formatDBFileForLog(storedDBFile))
print("Done.")
else:
print("Aborted!")
def setdata(self):
"""
Change some details of the entries given by IDs. IDs are required.
Only filename, comment and group can be changed.
"""
ff = None
if (isinstance(self.files, list)):
if len(self.files) > 1:
print("Please provide just one name or none at all!")
return
elif len(self.files) == 1:
ff = self.files[0]
if (self.fileId is None):
print("Please provide file ID (-i option).")
return
self.fileId = int(self.fileId)
dbf = DBFile(fileId=self.fileId, fileName=ff, group=self.group, comment=self.comment)
self.log(Register.LOGUPDATE + self._formatDBFileForLog(dbf))
with self.dbConnection.getSessionContext() as session:
dbf = DBFileRegister.update(session, dbf)
if not dbf:
print("Error updating the entry!")
else:
self.log(Register.LOGUPDATED + self._formatDBFileForLog(dbf))
def query(self):
"""
Query the register for any entry matching the parameters.
Only parts of the entry have to match the given parameters (ilike)
"""
ff = None
if (isinstance(self.files, list)):
if len(self.files) > 1:
print("Please provide just one name or none at all!")
return
elif len(self.files) == 1:
ff = self.files[0]
# create a new query arguments
dbFileQueryArguments = DBFileQueryArguments()
# add a query argument matching the file's ID if it is specified {{{
if (self.fileId is not None):
dbFileQueryArguments.fileId = self.fileId
# }}}
# add a query argument matching the file's name if it is specified {{{
if (ff is not None):
dbFileQueryArguments.fileName = ff
# }}}
# add a query argument matching the file's group if it is specified {{{
if (self.group is not None):
dbFileQueryArguments.group = self.group
# }}}
# add a query argument matching the file's comment if it is specified {{{
if (self.comment is not None):
dbFileQueryArguments.comment = self.comment
# }}}
with self.dbConnection.getSessionContext() as session:
ll = DBFileRegister.query(session, dbFileQueryArguments)
if (ll is None):
print("No record matches the query!")
else:
formatDBFileMethod = self._formatDBFile
if self.queryasmysum:
formatDBFileMethod = self._formatDBFileAsMysum
elif self.queryed2k:
formatDBFileMethod = self._formatDBFileAsED2K
elif self.queryverbose:
formatDBFileMethod = functools.partial(self._formatDBFile, verbose = True)
for dbf in ll:
print(formatDBFileMethod(dbf))
def resetfromlog(self):
"""
drop the db and reinsert (and update) all the entries from log to the empty db
"""
if not os.path.exists(self.logfile):
print("The logfile " + self.logfile + " doesn't exist!")
return
# backup the old one
if os.path.exists(self.dbFilePath):
bak = self.dbFilePath + "~"
if os.path.exists(bak):
if input("A backup already exists. Remove it (only Yes is accepted)? ") != "Yes":
return
os.remove(bak)
os.rename(self.dbFilePath, bak)
# read new one
print("This might take a while depending on the log size. Please wait ...")
self.dbConnection = DBConnection(self.dbFilePath)
with self.dbConnection.getSessionContext() as session:
with open(self.logfile, "r") as self.logf:
for ll in self.logf:
if ll.startswith(Register.LOGADD):
dbf = self._dbFileFromLog(ll[len(Register.LOGADD):])
DBFileRegister.insert(session, dbf, commit=False)
elif ll.startswith(Register.LOGUPDATED):
dbf = self._dbFileFromLog(ll[len(Register.LOGUPDATED):])
session.commit()
DBFileRegister.update(session,dbf, setall=True)
# TODO display progress (line, items, date)
session.commit()
print("Done")
def log(self, line):
"""
log the line to log file
if this is late commit op, store line for later (in self.latelog buffer)
to write stored lines set op to eg. None and call it again
"""
if not self.logf:
self.logfile = os.path.expanduser(self.logfile)
if not os.path.exists(self.logfile):
self.logf = open(self.logfile, "w")
else:
self.logf = open(self.logfile, "a")
self.logf.write(self.LOGCOMMENT+datetime.datetime.now().ctime()+"\n")
if line:
self.logf.write(line+"\n")
def printstatus(self, no, ff, msg, totalItems = None):
"""
print the provided information so it fits on one line of the terminal
self.cols holds the maximum line size
everything will fit to fill the linelike this
|[no/total] filenamefilename~filenamefilename message |
|[no/total] filenamefi~mefilename veryverylongmessage |
"""
if (totalItems is None):
totalItems = len(self.files)
stat = str(len(self.files))
stat = "[{}/{}] ".format(str(no).rjust(len(stat)), totalItems)
# filename has all the space that's left by message and current stat
lff = self.cols - len(msg) - len(stat) - 5 # 1 (before) + 3 (after) + 1 (end)
if lff < len(ff): # not enough space - construct file~name
hff = int((lff-1)/2)
ff = ff[:hff]+"~"+ff[-hff:]
ff = ff.ljust(lff)
print("\r{} {} {}".format(stat, ff, msg), end="")
def msgpgs(self, ms, psize, tstart, fileMightBeRegistered=False):
"""
create a progress message from the given info
"""
pgs = ms.processedSize
size = ms.fileSize
tnow = time.time()
if (pgs is None):
pgs = 0
if size == 0:
percent = 100
else:
percent = int(pgs * 100 / size)
tdif = tnow - tstart
if tdif == 0:
speed = 0
else:
speed = (psize + pgs) / (1024*1024*tdif)
if speed == 0:
speed = 0
eta = " --:--"
else:
eta = int((self.totalsize - psize - pgs) / (1024*1024*speed))
speed = int(speed)
if eta != 0:
eta = " {:02d}:{:02d}".format(int(eta/60), eta % 60)
else:
eta = " 00:00"
return "{}{} {:3d}MB/s{}".format("* " if fileMightBeRegistered else "", progressbar(percent,size=21), speed, eta)
def processfiles(self, thorough=True):
"""
parse the files from arguments to a useable list
if thorough is True the list of directories, files and wildcards is turned into a list of real filenames (and total size is computed)
"""
if (isinstance(self.files, str)):
self.files = [ self.files ]
elif self.files is None:
return
elif (not isinstance(self.files, list)):
raise ValueError("The files is not a list nor a string")
if not thorough:
return
rf = [] # real files
ts = 0 # total size
if (os.name == 'posix'):
cwd = os.popen('pwd').read().strip('\n')
else:
cwd = os.getcwd()
for ff in self.files:
# the file could be: a file, a directory (then add everything recursively), or a wildcard
ff = os.path.expanduser(ff)
if (not os.path.isabs(ff)):
ff = os.path.normpath(os.path.join(cwd, ff))
if (os.path.exists(ff) and os.path.isdir(ff)):
for root, dirnames, filenames in os.walk(ff):
for filename in fnmatch.filter(filenames, '*'):
fn = os.path.join(root, filename)
ts = ts + os.stat(fn)[6]
rf.append(fn)
else:
for fn in glob.iglob(ff):
fn = os.path.join(cwd, fn)
ts = ts + os.stat(fn)[6]
rf.append(fn)
self.totalsize = ts
self.files = rf
def makedefaults(self):
"""
create a defaults file that can be edited to change default group and comment
the file is created in the current directory
"""
if os.path.exists(self.DEFAULTFILES[0]):
print("The file " + self.DEFAULTFILES[1] + " already exists!")
return
elif os.path.exists(self.DEFAULTFILES[1]):
print("Warning the file " + self.DEFAULTFILES[1] + " exists!")
with open(self.DEFAULTFILES[0], "w"):
pass
print("File " + self.DEFAULTFILES[0] + " created. You can rename it to "+ self.DEFAULTFILES[1] + " if you want.")
def getgroupcomment(self, ff, imp=False):
"""
determine group and comment for the given file
the sources for both of these values are (in this order, lowest to highest prio):
- the defaults files (the first of .regfiledefaults or _.regfiledefaults )
- the first line is the default group (if not empty)
- the second line is the default comment (if not empty)
- path templates (group and comment for certain directories)
- command arguments
returns (group, comment) tuple
to be used with register and import only
set imp to True if importing
"""
gr = self.group
com = self.comment
if gr and com:
return gr, com
if self.defaults:
# first look in the cache
dirname = os.path.dirname(ff)
if dirname in self.defaultcache:
grcom = self.defaultcache[dirname]
if (grcom is not None): # None means "use arg values"
gr, com = grcom
else:
# not in cache - read the defaults file
for df in self.DEFAULTFILES:
fdf = os.path.join(dirname, df)
if not os.path.exists(fdf) or not os.path.isfile(fdf):
continue
try:
dd = open(fdf, 'r')
except:
print("Error trying to open the file '{}'".format(fdf))
continue
ll = dd.readlines()
dd.close()
if len(ll) >= 1 and not gr:
gr = ll[0].strip()
if len(ll) >= 2 and not com:
com = ll[1].strip()
break
# store result in cache for further use
if gr == self.group and com == self.comment:
self.defaultcache[dirname] = None
else:
self.defaultcache[dirname] = (gr, com)
if self.auto:
# now the magic
# ff can be relative to os.getcwd or absolute, absolute path is needed
if not os.path.isabs(ff):
ff = os.path.join(os.getcwd(), ff)
if (self.pathTemplates is None):
self.pathTemplates = PathTemplates.fromConfig(self.configuration[RegfileConfiguration.PATH_TEMPLATES])
gr, com = self.pathTemplates.apply(ff, self.group, self.comment, gr, com, imp)
return (gr,com)
@staticmethod
def _formatDBFileAsMysum(dbFile):
# DOC {{{
"""Returns a string with the specified DBFile()'s properties in
the MySum format.
Parameters
dbFile -- a DBFile() to format
"""
# }}}
# CODE {{{
return MySum.format(
fileName = dbFile.fileName,
fileSize = dbFile.fileSize,
md5 = dbFile.md5,
md1 = dbFile.md1,
ed2k = dbFile.ed2k,
)
# }}}
@staticmethod
def _formatDBFileAsED2K(dbFile):
# DOC {{{
"""Returns a string containing the specified DBFile()'s as an
ED2K link.
Parameters
dbFile -- a DBFile() to format
"""
# }}}
# CODE {{{
return "ed2k://|file|{fileName}|{fileSize}|{ed2k}|/".format(
fileName = dbFile.fileName,
fileSize = dbFile.fileSize,
ed2k = dbFile.ed2k,
)
# }}}
@staticmethod
def _formatDBFile(dbFile, verbose = False):
# DOC {{{
"""Formats the specified DBFile()'s properties to a string and
returns it.
Parameters
dbFile -- a DBFile() to format
verbose -- (optional) if True checksums are included
"""
# }}}
# CODE {{{
# a list of lines of formated DBFile()'s properties
formatedLines = []
# print file's ID, name and size {{{
formatedLines.append("[{fileId:5d}] '{fileName}' s:{fileSize}".format(
fileId = dbFile.fileId,
fileName = dbFile.fileName,
fileSize = dbFile.fileSize,
))
# }}}
# print the file's group if it is not empty {{{
if (dbFile.group):
formatedLines.append(" group: {}".format(dbFile.group))
# }}}
# print the file's comment if it is not empty {{{
if (dbFile.comment):
formatedLines.append(" comment: {}".format(dbFile.comment))
# }}}
# print file's checksums if verbosity is set {{{
if (verbose):
formatedLines.append(" md1:{md1} md5:{md5} ed2k:{ed2k}".format(
md1 = dbFile.md1,
md5 = dbFile.md5,
ed2k = dbFile.ed2k
))
# }}}
# join all the lines and return the resulting string for formated DBFile()'s properties
return "\n".join(formatedLines)
# }}}
@staticmethod
def _formatDBFileForLog(dbFile):
# DOC {{{
"""Returns a string representation of the specified dbFile for the log.
Parameters
dbFile -- a DBFile() to format
"""
# }}}
# CODE {{{
return ("DBF{fileId:06d}|n:{fileName}|" +
"g:{group}|c:{comment}|s:{fileSize}|" +
"md1:{md1}|md5:{md5}|ed2k:{ed2k}|").format(
fileId = dbFile.fileId if (dbFile.fileId is not None) else 0,
fileName = dbFile.fileName,
group = dbFile.group if (dbFile.group is not None) else "",
comment = dbFile.comment if (dbFile.comment is not None) else "",
fileSize = dbFile.fileSize,
md1 = dbFile.md1,
md5 = dbFile.md5,
ed2k = dbFile.ed2k,
)
# }}}
@staticmethod
def _dbFileFromLog(ls):
rr = Register.LOG_DBFILE_RE.match(ls)
if not rr:
raise ValueError("The string " + ls + " doesnt match the logline!")
matchGroups = rr.groupdict()
dbf = DBFile(
fileId = int(matchGroups['fileId']),
fileName = matchGroups['fileName'],
fileSize = int(matchGroups['fileSize']),
group = matchGroups['group'],
comment = matchGroups['comment'],
md1 = matchGroups['md1'],
md5 = matchGroups['md5'],
ed2k = matchGroups['ed2k'],
)
assert (Register._formatDBFileForLog(dbf).strip() == ls.strip())
return dbf
def runop(args):
Register(args).go()
if __name__ == "__main__":
print("This is a library, please run regfile. (There's no unittest yet.)")