Debian Codegraph @

tools/scripts/checksum/checksum.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 #----------------------------------------------------------------------------------------------------------
5 # checksum.py
6 # A SHA1 hash checksum list generator for fonts and fontTools
7 # XML dumps of font OpenType table data + checksum testing
8 # script
9 #
10 # Copyright 2018 Christopher Simpkins
11 # MIT License
12 #
13 # Dependencies:
14 # - Python fontTools library
15 # - Python 3 interpreter
16 #
17 # Usage: checksum.py (options) [file path 1]...[file path n]
18 #
19 # `file path` should be defined as a path to a font file for all use cases except with use of -c/--check.
20 # With the -c/--check option, use one or more file paths to checksum files
21 #
22 # Options:
23 # -h, --help Help
24 # -t, --ttx Calculate SHA1 hash values from ttx dump of XML (default = font binary)
25 # -s, --stdout Stream to standard output stream (default = write to working dir as 'checksum.txt')
26 # -c, --check Test SHA1 checksum values against a valid checksum file
27 #
28 # Options, --ttx only:
29 # -e, --exclude Excluded OpenType table (may be used more than once, mutually exclusive with -i)
30 # -i, --include Included OpenType table (may be used more than once, mutually exclusive with -e)
31 # -n, --noclean Do not discard .ttx files that are used to calculate SHA1 hashes
32 #-----------------------------------------------------------------------------------------------------------
33
34 import argparse
35 import hashlib
36 import os
37 import sys
38
39 from os.path import basename
40
41 from fontTools.ttLib import TTFont
42
43
44 def write_checksum(filepaths, stdout_write=False, use_ttx=False, include_tables=None, exclude_tables=None, do_not_cleanup=False):
45 checksum_dict = {}
46 for path in filepaths:
47 if not os.path.exists(path):
48 sys.stderr.write("[checksum.py] ERROR: " + path + " is not a valid file path" + os.linesep)
49 sys.exit(1)
50
51 if use_ttx:
52 # append a .ttx extension to existing extension to maintain data about the binary that
53 # was used to generate the .ttx XML dump. This creates unique checksum path values for
54 # paths that would otherwise not be unique with a file extension replacement with .ttx
55 # An example is woff and woff2 web font files that share the same base file name:
56 #
57 # coolfont-regular.woff ==> coolfont-regular.ttx
58 # coolfont-regular.woff2 ==> coolfont-regular.ttx (KAPOW! checksum data lost as this would overwrite dict value)
59 temp_ttx_path = path + ".ttx"
60
61 tt = TTFont(path)
62 # important to keep the newlinestr value defined here as hash values will change across platforms
63 # if platform specific newline values are assumed
64 tt.saveXML(temp_ttx_path, newlinestr="\n", skipTables=exclude_tables, tables=include_tables)
65 checksum_path = temp_ttx_path
66 else:
67 if include_tables is not None:
68 sys.stderr.write("[checksum.py] -i and --include are not supported for font binary filepaths. \
69 Use these flags for checksums with the --ttx flag.")
70 sys.exit(1)
71 if exclude_tables is not None:
72 sys.stderr.write("[checksum.py] -e and --exclude are not supported for font binary filepaths. \
73 Use these flags for checksums with the --ttx flag.")
74 sys.exit(1)
75 checksum_path = path
76
77 file_contents = _read_binary(checksum_path)
78
79 # store SHA1 hash data and associated file path basename in the checksum_dict dictionary
80 checksum_dict[basename(checksum_path)] = hashlib.sha1(file_contents).hexdigest()
81
82 # remove temp ttx files when present
83 if use_ttx and do_not_cleanup is False:
84 os.remove(temp_ttx_path)
85
86 # generate the checksum list string for writes
87 checksum_out_data = ""
88 for key in checksum_dict.keys():
89 checksum_out_data += checksum_dict[key] + " " + key + "\n"
90
91 # write to stdout stream or file based upon user request (default = file write)
92 if stdout_write:
93 sys.stdout.write(checksum_out_data)
94 else:
95 checksum_report_filepath = "checksum.txt"
96 with open(checksum_report_filepath, "w") as file:
97 file.write(checksum_out_data)
98
99
100 def check_checksum(filepaths):
101 check_failed = False
102 for path in filepaths:
103 if not os.path.exists(path):
104 sys.stderr.write("[checksum.py] ERROR: " + path + " is not a valid filepath" + os.linesep)
105 sys.exit(1)
106
107 with open(path, mode='r') as file:
108 for line in file.readlines():
109 cleaned_line = line.rstrip()
110 line_list = cleaned_line.split(" ")
111 # eliminate empty strings parsed from > 1 space characters
112 line_list = list(filter(None, line_list))
113 if len(line_list) == 2:
114 expected_sha1 = line_list[0]
115 test_path = line_list[1]
116 else:
117 sys.stderr.write("[checksum.py] ERROR: failed to parse checksum file values" + os.linesep)
118 sys.exit(1)
119
120 if not os.path.exists(test_path):
121 print(test_path + ": Filepath is not valid, ignored")
122 else:
123 file_contents = _read_binary(test_path)
124 observed_sha1 = hashlib.sha1(file_contents).hexdigest()
125 if observed_sha1 == expected_sha1:
126 print(test_path + ": OK")
127 else:
128 print("-" * 80)
129 print(test_path + ": === FAIL ===")
130 print("Expected vs. Observed:")
131 print(expected_sha1)
132 print(observed_sha1)
133 print("-" * 80)
134 check_failed = True
135
136 # exit with status code 1 if any fails detected across all tests in the check
137 if check_failed is True:
138 sys.exit(1)
139
140
141 def _read_binary(filepath):
142 with open(filepath, mode='rb') as file:
143 return file.read()
144
145
146 if __name__ == '__main__':
147 parser = argparse.ArgumentParser(prog="checksum.py")
148 parser.add_argument("-t", "--ttx", help="Calculate from ttx file", action="store_true")
149 parser.add_argument("-s", "--stdout", help="Write output to stdout stream", action="store_true")
150 parser.add_argument("-n", "--noclean", help="Do not discard *.ttx files used to calculate SHA1 hashes", action="store_true")
151 parser.add_argument("-c", "--check", help="Verify checksum values vs. files", action="store_true")
152 parser.add_argument("filepaths", nargs="+", help="One or more file paths to font binary files")
153
154 parser.add_argument("-i", "--include", action="append", help="Included OpenType tables for ttx data dump")
155 parser.add_argument("-e", "--exclude", action="append", help="Excluded OpenType tables for ttx data dump")
156
157 args = parser.parse_args(sys.argv[1:])
158
159 if args.check is True:
160 check_checksum(args.filepaths)
161 else:
162 write_checksum(args.filepaths, stdout_write=args.stdout, use_ttx=args.ttx, do_not_cleanup=args.noclean, include_tables=args.include, exclude_tables=args.exclude)