opex-manifest-generator 1.1.11__py3-none-any.whl → 1.1.13__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,16 @@
1
- """
2
- opex_manifest_generator package definitions
3
-
4
- Author: Christopher Prince
5
- license: Apache License 2.0"
6
- """
7
-
8
- from .opex_manifest import OpexManifestGenerator,OpexDir,OpexFile
9
- from .hash import HashGenerator
10
- from .common import *
11
- from .cli import parse_args,run_cli
12
- import importlib.metadata
13
-
14
- __author__ = "Christopher Prince (c.pj.prince@gmail.com)"
15
- __license__ = "Apache License Version 2.0"
1
+ """
2
+ opex_manifest_generator package definitions
3
+
4
+ Author: Christopher Prince
5
+ license: Apache License 2.0"
6
+ """
7
+
8
+ from .opex_manifest import OpexManifestGenerator,OpexDir,OpexFile
9
+ from .hash import HashGenerator
10
+ from .common import *
11
+ from .cli import parse_args,run_cli
12
+ import importlib.metadata
13
+
14
+ __author__ = "Christopher Prince (c.pj.prince@gmail.com)"
15
+ __license__ = "Apache License Version 2.0"
16
16
  __version__ = importlib.metadata.version("opex_manifest_generator")
@@ -1,160 +1,161 @@
1
- """
2
- Cli interaction.
3
-
4
- author: Christopher Prince
5
- license: Apache License 2.0"
6
- """
7
-
8
- import argparse
9
- import os
10
- import time
11
- from opex_manifest_generator.opex_manifest import OpexManifestGenerator
12
- import importlib.metadata
13
-
14
- def parse_args():
15
- parser = argparse.ArgumentParser(description = "OPEX Manifest Generator for Preservica Uploads")
16
- parser.add_argument('root', default = os.getcwd(), help = "The root path to generate Opexes for")
17
- parser.add_argument("-c", "--autoclass", required = False,
18
- choices = ['catalog', 'c', 'accession', 'a', 'both', 'b', 'generic', 'g', 'catalog-generic', 'cg', "accession-generic", "ag", "both-generic", "bg"],
19
- type = str.lower,
20
- help="""Toggles whether to utilise the auto_classification_generator
21
- to generate an on the fly Reference listing.
22
-
23
- There are several options, {catalog} will generate
24
- a Archival Reference following an ISAD(G) sturcutre.
25
- {accession} will create a running number of files.
26
- {both} will do both at the same time!
27
- {generic} will populate the title and description fields with the folder/file's name,
28
- if used in conjunction with one of the above options:
29
- {generic-catalog,generic-accession, generic-both} it will do both simultaneously.
30
- """)
31
- parser.add_argument("-p", "--prefix", required = False, nargs = '+',
32
- help= """Assign a prefix when utilising the --autoclass option. Prefix will append any text before all generated text.
33
- When utilising the {both} option fill in like: [catalog-prefix, accession-prefix] without square brackets.
34
- """)
35
- parser.add_argument("-fx", "--fixity", required = False, const = "SHA-1", default = None,
36
- nargs = '?', choices = ['NONE', 'SHA-1', 'MD5', 'SHA-256', 'SHA-512'], type = str.upper,
37
- help="Generates a hash for each file and adds it to the opex, can select the algorithm to utilise.")
38
- parser.add_argument("-rme", "--remove-empty", required = False, action = 'store_true', default = False,
39
- help = "Remove and log empty directories from root. Log will be exported to 'meta' / output folder.")
40
- parser.add_argument("-o", "--output", required = False, nargs = 1,
41
- help = "Sets the output to send any generated files to. Will not affect creation of a meta dir.")
42
- parser.add_argument("-dmd", "--disable-meta-dir", required = False, action = 'store_false',
43
- help = """Set whether to disable the creation of a 'meta' directory for generated files,
44
- default behaviour is to always generate this directory""")
45
- parser.add_argument("-clr", "--clear-opex", required = False, action = 'store_true', default = False,
46
- help = """Clears existing opex files from a directory. If set with no further options will only clear opexes;
47
- if multiple options are set will clear opexes and then run the program""")
48
- parser.add_argument("-opt","--options-file", required = False, default=os.path.join(os.path.dirname(__file__),'options.properties'),
49
- help="Specify a custom Options file, changing the set presets for column headers (Title,Description,etc)")
50
- parser.add_argument("-s", "--start-ref", required = False, nargs = '?', default = 1,
51
- help="Set a custom Starting reference for the Auto Classification generator. The generated reference will")
52
- parser.add_argument("-mdir","--metadata-dir", required=False, nargs= '?',
53
- default = os.path.join(os.path.dirname(os.path.realpath(__file__)), "metadata"),
54
- help="Specify the metadata directory to pull XML files from")
55
- parser.add_argument("-m", "--metadata", required = False, const = 'e', default = 'none',
56
- nargs = '?', choices = ['none', 'n', 'exact', 'e', 'flat', 'f'], type = str.lower,
57
- help="Set whether to include xml metadata fields in the generation of the Opex")
58
- parser.add_argument("-ex", "--export", required = False, action = 'store_true', default = False,
59
- help="Set whether to export the generated auto classification references to an AutoClass spreadsheet")
60
- parser.add_argument("-i", "--input", required = False, nargs='?',
61
- help="Set to utilise a CSV / XLSX spreadsheet to import data from")
62
- parser.add_argument("-rm", "--remove", required = False, action = "store_true", default = False,
63
- help="Set whether to enable removals of files and folders from a directory. ***Currently in testing")
64
- parser.add_argument("-z", "--zip", required = False, action = 'store_true',
65
- help="Set to zip files")
66
- parser.add_argument("-fmt", "--output-format", required = False, default = "xlsx", choices = ['xlsx', 'csv'],
67
- help="Set whether to output to an xlsx or csv format")
68
- parser.add_argument("-v", "--version", action = 'version', version = '%(prog)s {version}'.format(version = importlib.metadata.version("opex_manifest_generator")))
69
- parser.add_argument("--accession-mode", required=False, choices=["file",'directory','both'],
70
- help="""Set the mode when utilising the Accession option in autoclass.
71
- file - only adds on files, folder - only adds on folders, both - adds on files and folders""")
72
- parser.add_argument("--hidden", required = False, action = 'store_true', default = False,
73
- help="Set whether to include hidden files and folders")
74
- parser.add_argument("--print-xmls", required = False, action = "store_true", default = False,
75
- help="Prints the elements from your xmls to the consoles")
76
- args = parser.parse_args()
77
- return args
78
-
79
- def run_cli():
80
- args = parse_args()
81
- print(f"Running Opex Generation on: {args.root}")
82
- if not args.output:
83
- args.output = os.path.abspath(args.root)
84
- print(f'Output path defaulting to root directory: {args.output}')
85
- else:
86
- args.output = os.path.abspath(args.output[0])
87
- print(f'Output path set to: {args.output}')
88
- if args.input and args.autoclass:
89
- print(f'Both Input and Auto-Class options have been selected, please use only one...')
90
- time.sleep(5); raise SystemExit()
91
- if not args.metadata in {'none', 'n'} and not args.input:
92
- print(f'Warning: Metadata Flag has been given without Input. Metadata won\'t be generated.')
93
- time.sleep(5)
94
- if args.print_xmls:
95
- OpexManifestGenerator.print_descriptive_xmls()
96
- acc_prefix = None
97
- if args.prefix:
98
- if args.autoclass in {"both", "b", "both-generic", "bg"}:
99
- if len(args.prefix) < 2 or len(args.prefix) > 2:
100
- print('"Both" option is selected, please pass only two prefixes: [-p CATALOG_PREFIX ACCESSION_PREFIX]');
101
- time.sleep(3); raise SystemExit
102
- for n, a in enumerate(args.prefix):
103
- if n == 0:
104
- args.prefix = str(a)
105
- elif n == 1:
106
- acc_prefix = str(a)
107
- print(f"Prefixes are set as: \t Catalog: {args.prefix} \t Acc: {acc_prefix}")
108
- elif args.autoclass in {"accession", "a", "accession-generic", "ag"}:
109
- for a in args.prefix:
110
- acc_prefix = str(a)
111
- print('Prefix is set as: ' + acc_prefix)
112
- elif args.autoclass in {"catalog", "c", "catalog-generic", "cg"}:
113
- acc_prefix = None
114
- for a in args.prefix:
115
- args.prefix = str(a)
116
- print('Prefix is set as: ' + args.prefix)
117
- elif args.autoclass in {"generic", "g"}:
118
- pass
119
- else:
120
- print('''An invalid option has been selected, please select a valid option:
121
- {c, catalog
122
- a, accession
123
- b, both
124
- g, generic
125
- cg, catalog-generic
126
- ag, accesion-generic
127
- bg, both-generic}''')
128
- time.sleep(3)
129
- raise SystemExit
130
- if args.fixity:
131
- print(f'Fixity is activated, using {args.fixity} algorithm')
132
- if args.remove:
133
- i = "y"
134
- # i = input(inspect.cleandoc("""You have enabled the remove functionality.
135
- # This action will remove files listed for removal, it is irreversible.
136
- # Please type Y to confirm, otherwise program will close: """))
137
- if not i.lower() == "y":
138
- print("Closing program..."); time.sleep(3); raise SystemExit()
139
- time.sleep(3)
140
- OpexManifestGenerator(root = args.root,
141
- output_path = args.output,
142
- autoclass_flag = args.autoclass,
143
- prefix = args.prefix,
144
- acc_prefix = acc_prefix,
145
- empty_flag = args.remove_empty,
146
- remove_flag = args.remove,
147
- clear_opex_flag = args.clear_opex,
148
- algorithm = args.fixity,
149
- startref = args.start_ref,
150
- export_flag = args.export,
151
- meta_dir_flag = args.disable_meta_dir,
152
- metadata_flag = args.metadata,
153
- metadata_dir = args.metadata_dir,
154
- hidden_flag= args.hidden,
155
- zip_flag = args.zip,
156
- input = args.input,
157
- output_format = args.output_format).main()
158
-
159
- if __name__ == "__main__":
1
+ """
2
+ Cli interaction.
3
+
4
+ author: Christopher Prince
5
+ license: Apache License 2.0"
6
+ """
7
+
8
+ import argparse
9
+ import os
10
+ import time
11
+ from opex_manifest_generator.opex_manifest import OpexManifestGenerator
12
+ import importlib.metadata
13
+
14
+ def parse_args():
15
+ parser = argparse.ArgumentParser(description = "OPEX Manifest Generator for Preservica Uploads")
16
+ parser.add_argument('root', default = os.getcwd(), help = "The root path to generate Opexes for")
17
+ parser.add_argument("-c", "--autoclass", required = False,
18
+ choices = ['catalog', 'c', 'accession', 'a', 'both', 'b', 'generic', 'g', 'catalog-generic', 'cg', "accession-generic", "ag", "both-generic", "bg"],
19
+ type = str.lower,
20
+ help="""Toggles whether to utilise the auto_classification_generator
21
+ to generate an on the fly Reference listing.
22
+
23
+ There are several options, {catalog} will generate
24
+ a Archival Reference following an ISAD(G) sturcutre.
25
+ {accession} will create a running number of files.
26
+ {both} will do both at the same time!
27
+ {generic} will populate the title and description fields with the folder/file's name,
28
+ if used in conjunction with one of the above options:
29
+ {generic-catalog,generic-accession, generic-both} it will do both simultaneously.
30
+ """)
31
+ parser.add_argument("-p", "--prefix", required = False, nargs = '+',
32
+ help= """Assign a prefix when utilising the --autoclass option. Prefix will append any text before all generated text.
33
+ When utilising the {both} option fill in like: [catalog-prefix, accession-prefix] without square brackets.
34
+ """)
35
+ parser.add_argument("-fx", "--fixity", required = False, const = "SHA-1", default = None,
36
+ nargs = '?', choices = ['NONE', 'SHA-1', 'MD5', 'SHA-256', 'SHA-512'], type = str.upper,
37
+ help="Generates a hash for each file and adds it to the opex, can select the algorithm to utilise.")
38
+ parser.add_argument("-rme", "--remove-empty", required = False, action = 'store_true', default = False,
39
+ help = "Remove and log empty directories from root. Log will be exported to 'meta' / output folder.")
40
+ parser.add_argument("-o", "--output", required = False, nargs = 1,
41
+ help = "Sets the output to send any generated files to. Will not affect creation of a meta dir.")
42
+ parser.add_argument("-dmd", "--disable-meta-dir", required = False, action = 'store_false',
43
+ help = """Set whether to disable the creation of a 'meta' directory for generated files,
44
+ default behaviour is to always generate this directory""")
45
+ parser.add_argument("-clr", "--clear-opex", required = False, action = 'store_true', default = False,
46
+ help = """Clears existing opex files from a directory. If set with no further options will only clear opexes;
47
+ if multiple options are set will clear opexes and then run the program""")
48
+ parser.add_argument("-opt","--options-file", required = False, default=os.path.join(os.path.dirname(__file__),'options.properties'),
49
+ help="Specify a custom Options file, changing the set presets for column headers (Title,Description,etc)")
50
+ parser.add_argument("-s", "--start-ref", required = False, nargs = '?', default = 1,
51
+ help="Set a custom Starting reference for the Auto Classification generator. The generated reference will")
52
+ parser.add_argument("-mdir","--metadata-dir", required=False, nargs= '?',
53
+ default = os.path.join(os.path.dirname(os.path.realpath(__file__)), "metadata"),
54
+ help="Specify the metadata directory to pull XML files from")
55
+ parser.add_argument("-m", "--metadata", required = False, const = 'e', default = 'none',
56
+ nargs = '?', choices = ['none', 'n', 'exact', 'e', 'flat', 'f'], type = str.lower,
57
+ help="Set whether to include xml metadata fields in the generation of the Opex")
58
+ parser.add_argument("-ex", "--export", required = False, action = 'store_true', default = False,
59
+ help="Set whether to export the generated auto classification references to an AutoClass spreadsheet")
60
+ parser.add_argument("-i", "--input", required = False, nargs='?',
61
+ help="Set to utilise a CSV / XLSX spreadsheet to import data from")
62
+ parser.add_argument("-rm", "--remove", required = False, action = "store_true", default = False,
63
+ help="Set whether to enable removals of files and folders from a directory. ***Currently in testing")
64
+ parser.add_argument("-z", "--zip", required = False, action = 'store_true',
65
+ help="Set to zip files")
66
+ parser.add_argument("-fmt", "--output-format", required = False, default = "xlsx", choices = ['xlsx', 'csv'],
67
+ help="Set whether to output to an xlsx or csv format")
68
+ parser.add_argument("-v", "--version", action = 'version', version = '%(prog)s {version}'.format(version = importlib.metadata.version("opex_manifest_generator")))
69
+ parser.add_argument("--accession-mode", required=False, choices=["file",'directory','both'],
70
+ help="""Set the mode when utilising the Accession option in autoclass.
71
+ file - only adds on files, folder - only adds on folders, both - adds on files and folders""")
72
+ parser.add_argument("--hidden", required = False, action = 'store_true', default = False,
73
+ help="Set whether to include hidden files and folders")
74
+ parser.add_argument("--print-xmls", required = False, action = "store_true", default = False,
75
+ help="Prints the elements from your xmls to the consoles")
76
+ args = parser.parse_args()
77
+ return args
78
+
79
+ def run_cli():
80
+ args = parse_args()
81
+ print(f"Running Opex Generation on: {args.root}")
82
+ if not args.output:
83
+ args.output = os.path.abspath(args.root)
84
+ print(f'Output path defaulting to root directory: {args.output}')
85
+ else:
86
+ args.output = os.path.abspath(args.output[0])
87
+ print(f'Output path set to: {args.output}')
88
+ if args.input and args.autoclass:
89
+ print(f'Both Input and Auto-Class options have been selected, please use only one...')
90
+ time.sleep(5); raise SystemExit()
91
+ if not args.metadata in {'none', 'n'} and not args.input:
92
+ print(f'Warning: Metadata Flag has been given without Input. Metadata won\'t be generated.')
93
+ time.sleep(5)
94
+ if args.print_xmls:
95
+ OpexManifestGenerator.print_descriptive_xmls()
96
+ acc_prefix = None
97
+ if args.prefix:
98
+ if args.autoclass in {"both", "b", "both-generic", "bg"}:
99
+ if len(args.prefix) < 2 or len(args.prefix) > 2:
100
+ print('"Both" option is selected, please pass only two prefixes: [-p CATALOG_PREFIX ACCESSION_PREFIX]');
101
+ time.sleep(3); raise SystemExit
102
+ for n, a in enumerate(args.prefix):
103
+ if n == 0:
104
+ args.prefix = str(a)
105
+ elif n == 1:
106
+ acc_prefix = str(a)
107
+ print(f"Prefixes are set as: \t Catalog: {args.prefix} \t Acc: {acc_prefix}")
108
+ elif args.autoclass in {"accession", "a", "accession-generic", "ag"}:
109
+ for a in args.prefix:
110
+ acc_prefix = str(a)
111
+ print('Prefix is set as: ' + acc_prefix)
112
+ elif args.autoclass in {"catalog", "c", "catalog-generic", "cg"}:
113
+ acc_prefix = None
114
+ for a in args.prefix:
115
+ args.prefix = str(a)
116
+ print('Prefix is set as: ' + args.prefix)
117
+ elif args.autoclass in {"generic", "g"}:
118
+ pass
119
+ else:
120
+ print('''An invalid option has been selected, please select a valid option:
121
+ {c, catalog
122
+ a, accession
123
+ b, both
124
+ g, generic
125
+ cg, catalog-generic
126
+ ag, accesion-generic
127
+ bg, both-generic}''')
128
+ time.sleep(3)
129
+ raise SystemExit
130
+ if args.fixity:
131
+ print(f'Fixity is activated, using {args.fixity} algorithm')
132
+ if args.remove:
133
+ i = "y"
134
+ # i = input(inspect.cleandoc("""You have enabled the remove functionality.
135
+ # This action will remove files listed for removal, it is irreversible.
136
+ # Please type Y to confirm, otherwise program will close: """))
137
+ if not i.lower() == "y":
138
+ print("Closing program..."); time.sleep(3); raise SystemExit()
139
+ time.sleep(3)
140
+ OpexManifestGenerator(root = args.root,
141
+ output_path = args.output,
142
+ autoclass_flag = args.autoclass,
143
+ prefix = args.prefix,
144
+ acc_prefix = acc_prefix,
145
+ empty_flag = args.remove_empty,
146
+ remove_flag = args.remove,
147
+ clear_opex_flag = args.clear_opex,
148
+ algorithm = args.fixity,
149
+ startref = args.start_ref,
150
+ export_flag = args.export,
151
+ meta_dir_flag = args.disable_meta_dir,
152
+ metadata_flag = args.metadata,
153
+ metadata_dir = args.metadata_dir,
154
+ hidden_flag= args.hidden,
155
+ zip_flag = args.zip,
156
+ input = args.input,
157
+ output_format = args.output_format,
158
+ options_file=args.options_file).main()
159
+
160
+ if __name__ == "__main__":
160
161
  run_cli()
@@ -1,58 +1,58 @@
1
- """
2
- Common tools for use throghout program.
3
-
4
- author: Christopher Prince
5
- license: Apache License 2.0"
6
- """
7
-
8
- import zipfile, os, sys, time, stat
9
- import datetime
10
- from lxml import etree
11
-
12
- def zip_opex(file_path,opex_path):
13
- zip_file = f"{file_path}.zip"
14
- if not os.path.exists(zip_file):
15
- with zipfile.ZipFile(zip_file,'w') as z:
16
- z.write(file_path,os.path.basename(file_path))
17
- z.write(opex_path,os.path.basename(opex_path))
18
- else: print(f'A zip file already exists for: {zip_file}')
19
-
20
- def win_256_check(path: str):
21
- if len(path) > 255 and sys.platform == "win32":
22
- if path.startswith(u'\\\\?\\'): path = path
23
- else: path = u"\\\\?\\" + path
24
- return path
25
-
26
- def filter_win_hidden(path: str):
27
- if sys.platform =="win32":
28
- if bool(os.stat(path).st_file_attribute & stat.FILE_ATTRIBUTE_HIDDEN) is True:
29
- return True
30
- else:
31
- return False
32
- else:
33
- return False
34
-
35
- def check_nan(value):
36
- if str(value).lower() in {"nan","nat"}:
37
- value = None
38
- return value
39
-
40
- def check_opex(opex_path:str):
41
- opex_path = opex_path + ".opex"
42
- if os.path.exists(win_256_check(opex_path)):
43
- return False
44
- else:
45
- return True
46
-
47
- def write_opex(path: str, opexxml: etree.Element):
48
- opex_path = win_256_check(str(path) + ".opex")
49
- opex = etree.indent(opexxml, " ")
50
- opex = etree.tostring(opexxml, pretty_print=True, xml_declaration=True, encoding="UTF-8", standalone=True)
51
- with open(f'{opex_path}', 'w', encoding="UTF-8") as writer:
52
- writer.write(opex.decode('UTF-8'))
53
- print('Saved Opex File to: ' + opex_path)
54
- return opex_path
55
-
56
- def print_running_time(start_time):
57
- print(f'Running time: {datetime.datetime.now() - start_time}')
58
- time.sleep(5)
1
+ """
2
+ Common tools for use throghout program.
3
+
4
+ author: Christopher Prince
5
+ license: Apache License 2.0"
6
+ """
7
+
8
+ import zipfile, os, sys, time, stat
9
+ import datetime
10
+ from lxml import etree
11
+
12
+ def zip_opex(file_path,opex_path):
13
+ zip_file = f"{file_path}.zip"
14
+ if not os.path.exists(zip_file):
15
+ with zipfile.ZipFile(zip_file,'w') as z:
16
+ z.write(file_path,os.path.basename(file_path))
17
+ z.write(opex_path,os.path.basename(opex_path))
18
+ else: print(f'A zip file already exists for: {zip_file}')
19
+
20
+ def win_256_check(path: str):
21
+ if len(path) > 255 and sys.platform == "win32":
22
+ if path.startswith(u'\\\\?\\'): path = path
23
+ else: path = u"\\\\?\\" + path
24
+ return path
25
+
26
+ def filter_win_hidden(path: str):
27
+ if sys.platform =="win32":
28
+ if bool(os.stat(path).st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN) is True:
29
+ return True
30
+ else:
31
+ return False
32
+ else:
33
+ return False
34
+
35
+ def check_nan(value):
36
+ if str(value).lower() in {"nan","nat"}:
37
+ value = None
38
+ return value
39
+
40
+ def check_opex(opex_path:str):
41
+ opex_path = opex_path + ".opex"
42
+ if os.path.exists(win_256_check(opex_path)):
43
+ return False
44
+ else:
45
+ return True
46
+
47
+ def write_opex(path: str, opexxml: etree.Element):
48
+ opex_path = win_256_check(str(path) + ".opex")
49
+ opex = etree.indent(opexxml, " ")
50
+ opex = etree.tostring(opexxml, pretty_print=True, xml_declaration=True, encoding="UTF-8", standalone=True)
51
+ with open(f'{opex_path}', 'w', encoding="UTF-8") as writer:
52
+ writer.write(opex.decode('UTF-8'))
53
+ print('Saved Opex File to: ' + opex_path)
54
+ return opex_path
55
+
56
+ def print_running_time(start_time):
57
+ print(f'Running time: {datetime.datetime.now() - start_time}')
58
+ time.sleep(5)
@@ -1,34 +1,34 @@
1
- """
2
- Hash Generator class for generating Fixities for files.
3
-
4
- author: Christopher Prince
5
- license: Apache License 2.0"
6
- """
7
-
8
- import hashlib
9
-
10
- class HashGenerator():
11
- def __init__(self,algorithm="SHA-1"):
12
- self.algorithm = algorithm
13
- self.buffer = 4096
14
-
15
- def hash_generator(self,file_path: str):
16
- if self.algorithm == "SHA-1":
17
- hash = hashlib.sha1()
18
- elif self.algorithm == "MD5":
19
- hash = hashlib.md5()
20
- elif self.algorithm == "SHA-256":
21
- hash = hashlib.sha256()
22
- elif self.algorithm == "SHA-512":
23
- hash = hashlib.sha512()
24
- else:
25
- hash = hashlib.sha1()
26
- print(f'Generating Fixity using {self.algorithm} for: {file_path}')
27
- with open(file_path, "rb") as f:
28
- while True:
29
- buff = f.read(self.buffer)
30
- if not buff:
31
- break
32
- hash.update(buff)
33
- f.close()
1
+ """
2
+ Hash Generator class for generating Fixities for files.
3
+
4
+ author: Christopher Prince
5
+ license: Apache License 2.0"
6
+ """
7
+
8
+ import hashlib
9
+
10
+ class HashGenerator():
11
+ def __init__(self,algorithm="SHA-1"):
12
+ self.algorithm = algorithm
13
+ self.buffer = 4096
14
+
15
+ def hash_generator(self,file_path: str):
16
+ if self.algorithm == "SHA-1":
17
+ hash = hashlib.sha1()
18
+ elif self.algorithm == "MD5":
19
+ hash = hashlib.md5()
20
+ elif self.algorithm == "SHA-256":
21
+ hash = hashlib.sha256()
22
+ elif self.algorithm == "SHA-512":
23
+ hash = hashlib.sha512()
24
+ else:
25
+ hash = hashlib.sha1()
26
+ print(f'Generating Fixity using {self.algorithm} for: {file_path}')
27
+ with open(file_path, "rb") as f:
28
+ while True:
29
+ buff = f.read(self.buffer)
30
+ if not buff:
31
+ break
32
+ hash.update(buff)
33
+ f.close()
34
34
  return hash.hexdigest().upper()