Created
October 30, 2020 10:17
-
-
Save jshwi/cf2aa168964e353d7859af8b7f2762c7 to your computer and use it in GitHub Desktop.
Sort files the way python's sorted() function sorts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
"""pysort | |
========= | |
Sort files in pythonic order | |
""" | |
# Copyright 2020 Stephen Whitlock | |
# | |
# Permission is hereby granted, free of charge, to any person obtaining a copy | |
# of this software and associated documentation files (the "Software"), to deal | |
# in the Software without restriction, including without limitation the rights | |
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
# copies of the Software, and to permit persons to whom the Software is | |
# furnished to do so, subject to the following conditions: | |
# | |
# The above copyright notice and this permission notice shall be included in | |
# all copies or substantial portions of the Software. | |
# | |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
# SOFTWARE. | |
__author__ = "Stephen Whitlock" | |
__maintainer__ = "Stephen Whitlock" | |
__email__ = "[email protected]" | |
__version__ = "1.0.0" | |
__copyright__ = "2020, Stephen Whitlock" | |
__license__ = "MIT" | |
import hashlib | |
import sys | |
import os | |
import argparse | |
class Parser(argparse.ArgumentParser): | |
"""Parse the chosen path for this module and test that it is | |
valid. | |
""" | |
def __init__(self): | |
super().__init__(prog=f"\u001b[0;36;40mpysort\u001b[0;0m",) | |
self._add_arguments() | |
self._args = self.parse_args() | |
self.path = self._args.path | |
self.dedupe = self._args.dedupe | |
self._exit_invalid() | |
def _add_arguments(self): | |
self.add_argument( | |
"path", | |
metavar="PATH", | |
action="store", | |
help="path to the file you wish to sort", | |
) | |
self.add_argument( | |
"-d", | |
"--dedupe", | |
action="store_true", | |
help="remove duplicates from file" | |
) | |
def _exit_invalid(self): | |
if not os.path.isfile(self.path): | |
print(f"`{self.path}' is not a file", file=sys.stderr) | |
if not os.path.exists(self.path): | |
print(f"`{self.path}' does not exist", file=sys.stderr) | |
sys.exit(1) | |
class MaxSizeList(list): | |
def __init__(self, maxlen): | |
super().__init__() | |
self._maxlen = maxlen | |
def append(self, element): | |
self.__delitem__(slice(0, len(self) == self._maxlen)) | |
super(MaxSizeList, self).append(element) | |
class HashCap: | |
def __init__(self, path): | |
self.path = path | |
self.snapshot = MaxSizeList(maxlen=2) | |
def hash_file(self): | |
"""Open the files and inspect it to get its hash. Return the | |
hash as a string | |
""" | |
with open(self.path, "rb") as lines: | |
md5_hash = hashlib.md5(lines.read()) | |
self.snapshot.append(md5_hash.hexdigest()) | |
def compare(self): | |
"""Compare two hashes in the ``snapshot`` list. | |
:return: Boolean: True for both match, False if they | |
don't. | |
""" | |
return self.snapshot[0] == self.snapshot[1] | |
class TextIO: | |
"""Input / output for the selected path.""" | |
def __init__(self, path): | |
self.path = path | |
self.lines = [] | |
def read_file(self): | |
"""read files into buffer.""" | |
with open(self.path) as file: | |
fin = file.read() | |
self.lines.extend(fin.splitlines()) | |
def sort(self): | |
"""Sort the list of lines from file.""" | |
self.lines = sorted(self.lines) | |
def write(self): | |
"""write buffer back to file.""" | |
with open(self.path, "w") as file: | |
for line in self.lines: | |
file.write(f"{line}\n") | |
def deduplicate(self): | |
newlines = [] | |
for line in self.lines: | |
if line not in newlines: | |
newlines.append(line) | |
self.lines = newlines | |
def announce_sort(path, match): | |
"""Announce whether a file needed to be sorted or not. | |
:param path: Path to the file to sort. | |
:param match: Boolean: True for both match, False if they don't. | |
""" | |
if match: | |
print(f"`{path}' already sorted") | |
else: | |
print(f"sorted `{path}'") | |
def announce_dedupe(path, match): | |
"""Announce whether a file needed to be deduplicated or not. | |
:param path: Path to the file to sort. | |
:param match: Boolean: True for both match, False if they don't. | |
""" | |
if match: | |
print(f"no duplicates found in `{path}'") | |
else: | |
print(f"deduplicated `{path}'") | |
def main(): | |
"""where it's at""" | |
parser = Parser() | |
path = parser.path | |
file = TextIO(path) | |
hashcap = HashCap(path) | |
hashcap.hash_file() | |
file.read_file() | |
file.sort() | |
file.write() | |
hashcap.hash_file() | |
match = hashcap.compare() | |
announce_sort(path, match) | |
if parser.dedupe: | |
file.deduplicate() | |
file.write() | |
hashcap.hash_file() | |
match = hashcap.compare() | |
announce_dedupe(path, match) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment