Skip to content

Instantly share code, notes, and snippets.

@MetroWind
Created October 4, 2012 19:51
Show Gist options
  • Save MetroWind/3835977 to your computer and use it in GitHub Desktop.
Save MetroWind/3835977 to your computer and use it in GitHub Desktop.
SFV sum
#!/usr/bin/env python3
import sys, os
import zlib
ChunkSize = 1024*1024
def crcFile(f):
Chunk = f.read(ChunkSize)
CRC = 0
while Chunk:
CRC = zlib.crc32(Chunk, CRC)
Chunk = f.read(ChunkSize)
return CRC & 0xffffffff
def checkSFV(sfv_name):
"""Returns a generator of (filename, passed) in which `passed' is
a bool.
"""
import re
SFV = open(sfv_name, 'r')
# Result = []
for Line in SFV:
Match = re.match('(.*)[ \t]+([0-9a-f]+)', Line.strip())
Filename = Match.group(1)
Sum = int(Match.group(2), 16)
with open(Filename, 'rb') as File:
# Result.append((Filename, Sum == crcFile(File)))
yield (Filename, Sum == crcFile(File))
SFV.close()
# return Result
def main(argv):
import argparse
Parser = argparse.ArgumentParser(description='SFV checksum-mer.')
Parser.add_argument('Files', metavar='FILE', type=str, nargs='*',
help='SFV File(s) to checksum, or file(s) to check to generate a SFV.')
Parser.add_argument('-p', '--progress', dest='ShowProg', action='store_true',
help='Which each file checked, prints a "." to stderr. Only works with "-g".')
Parser.add_argument('-g', '--generate', dest='GenSFV', action='store_true',
help="If issued, generate a SFV file from FILEs to stdout, "
"instead of treating FILEs as SFVs.")
Args = Parser.parse_args(argv[1:])
if Args.GenSFV == False and len(Args.Files) == 0:
print("{:08x}".format(crcFile(sys.stdin.buffer)))
if Args.GenSFV:
if Args.Files:
for FName in Args.Files:
with open(FName, 'rb') as File:
print(FName, "{:08x}".format(crcFile(File)))
if Args.ShowProg:
sys.stderr.write('.')
sys.stderr.flush()
if Args.ShowProg:
sys.stderr.write('\n')
else:
print("Need filenames... :-(", file=sys.stderr)
return -1
else:
Results = []
Fails = []
for SFVName in Args.Files:
for Result in checkSFV(SFVName):
if Result[1] == True:
print("PASSED ---", Result[0])
else:
print("FAILED ---", Result[0])
Fails.append(Result)
if Fails:
print()
print("Fails:")
for Fail in Fails:
print(Fail[0])
else:
print("All passed.")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment