id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
28,100
notify.py
arsenetar_dupeguru/hscommon/notify.py
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html """Very simple inter-object notification system. This module is a brain-dead simple notification system involving a :class:`Broadcaster` and a :class:`Listener`. A listener can only listen to one broadcaster. A broadcaster can have multiple listeners. If the listener is connected, whenever the broadcaster calls :meth:`~Broadcaster.notify`, the method with the same name as the broadcasted message is called on the listener. """ from collections import defaultdict from typing import Callable, DefaultDict, List class Broadcaster: """Broadcasts messages that are received by all listeners.""" def __init__(self): self.listeners = set() def add_listener(self, listener: "Listener") -> None: self.listeners.add(listener) def notify(self, msg: str) -> None: """Notify all connected listeners of ``msg``. That means that each listeners will have their method with the same name as ``msg`` called. """ for listener in self.listeners.copy(): # listeners can change during iteration if listener in self.listeners: # disconnected during notification listener.dispatch(msg) def remove_listener(self, listener: "Listener") -> None: self.listeners.discard(listener) class Listener: """A listener is initialized with the broadcaster it's going to listen to. Initially, it is not connected.""" def __init__(self, broadcaster: Broadcaster) -> None: self.broadcaster = broadcaster self._bound_notifications: DefaultDict[str, List[Callable]] = defaultdict(list) def bind_messages(self, messages: str, func: Callable) -> None: """Binds multiple message to the same function. Often, we perform the same thing on multiple messages. Instead of having the same function repeated again and agin in our class, we can use this method to bind multiple messages to the same function. """ for message in messages: self._bound_notifications[message].append(func) def connect(self) -> None: """Connects the listener to its broadcaster.""" self.broadcaster.add_listener(self) def disconnect(self) -> None: """Disconnects the listener from its broadcaster.""" self.broadcaster.remove_listener(self) def dispatch(self, msg: str) -> None: if msg in self._bound_notifications: for func in self._bound_notifications[msg]: func() if hasattr(self, msg): method = getattr(self, msg) method() class Repeater(Broadcaster, Listener): REPEATED_NOTIFICATIONS = None def __init__(self, broadcaster: Broadcaster) -> None: Broadcaster.__init__(self) Listener.__init__(self, broadcaster) def _repeat_message(self, msg: str) -> None: if not self.REPEATED_NOTIFICATIONS or msg in self.REPEATED_NOTIFICATIONS: self.notify(msg) def dispatch(self, msg: str) -> None: Listener.dispatch(self, msg) self._repeat_message(msg)
3,343
Python
.py
64
45.046875
113
0.693088
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,101
testutil.py
arsenetar_dupeguru/hscommon/testutil.py
# Created By: Virgil Dupras # Created On: 2010-11-14 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import pytest def eq_(a, b, msg=None): __tracebackhide__ = True assert a == b, msg or "{!r} != {!r}".format(a, b) def callcounter(): def f(*args, **kwargs): f.callcount += 1 f.callcount = 0 return f class CallLogger: """This is a dummy object that logs all calls made to it. It is used to simulate the GUI layer. """ def __init__(self): self.calls = [] def __getattr__(self, func_name): def func(*args, **kw): self.calls.append(func_name) return func def clear_calls(self): del self.calls[:] def check_gui_calls(self, expected, verify_order=False): """Checks that the expected calls have been made to 'self', then clears the log. `expected` is an iterable of strings representing method names. If `verify_order` is True, the order of the calls matters. """ __tracebackhide__ = True if verify_order: eq_(self.calls, expected) else: eq_(set(self.calls), set(expected)) self.clear_calls() def check_gui_calls_partial(self, expected=None, not_expected=None, verify_order=False): """Checks that the expected calls have been made to 'self', then clears the log. `expected` is an iterable of strings representing method names. Order doesn't matter. Moreover, if calls have been made that are not in expected, no failure occur. `not_expected` can be used for a more explicit check (rather than calling `check_gui_calls` with an empty `expected`) to assert that calls have *not* been made. """ __tracebackhide__ = True if expected is not None: not_called = set(expected) - set(self.calls) assert not not_called, f"These calls haven't been made: {not_called}" if verify_order: max_index = 0 for call in expected: index = self.calls.index(call) if index < max_index: raise AssertionError(f"The call {call} hasn't been made in the correct order") max_index = index if not_expected is not None: called = set(not_expected) & set(self.calls) assert not called, f"These calls shouldn't have been made: {called}" self.clear_calls() class TestApp: def __init__(self): self._call_loggers = [] def clear_gui_calls(self): for logger in self._call_loggers: logger.clear_calls() def make_logger(self, logger=None): if logger is None: logger = CallLogger() self._call_loggers.append(logger) return logger def make_gui(self, name, class_, view=None, parent=None, holder=None): if view is None: view = self.make_logger() if parent is None: # The attribute "default_parent" has to be set for this to work correctly parent = self.default_parent if holder is None: holder = self setattr(holder, f"{name}_gui", view) gui = class_(parent) gui.view = view setattr(holder, name, gui) return gui # To use @with_app, you have to import app in your conftest.py file. def with_app(setupfunc): def decorator(func): func.setupfunc = setupfunc return func return decorator @pytest.fixture def app(request): setupfunc = request.function.setupfunc if hasattr(setupfunc, "__code__"): argnames = setupfunc.__code__.co_varnames[: setupfunc.__code__.co_argcount] def getarg(name): if name == "self": return request.function.__self__ else: return request.getfixturevalue(name) args = [getarg(argname) for argname in argnames] else: args = [] app = setupfunc(*args) return app def _unify_args(func, args, kwargs, args_to_ignore=None): """Unify args and kwargs in the same dictionary. The result is kwargs with args added to it. func.func_code.co_varnames is used to determine under what key each elements of arg will be mapped in kwargs. if you want some arguments not to be in the results, supply a list of arg names in args_to_ignore. if f is a function that takes *args, func_code.co_varnames is empty, so args will be put under 'args' in kwargs. def foo(bar, baz) _unifyArgs(foo, (42,), {'baz': 23}) --> {'bar': 42, 'baz': 23} _unifyArgs(foo, (42,), {'baz': 23}, ['bar']) --> {'baz': 23} """ result = kwargs.copy() if hasattr(func, "__code__"): # built-in functions don't have func_code args = list(args) if getattr(func, "__self__", None) is not None: # bound method, we have to add self to args list args = [func.__self__] + args defaults = list(func.__defaults__) if func.__defaults__ is not None else [] arg_count = func.__code__.co_argcount arg_names = list(func.__code__.co_varnames) if len(args) < arg_count: # We have default values required_arg_count = arg_count - len(args) args = args + defaults[-required_arg_count:] for arg_name, arg in zip(arg_names, args): # setdefault is used because if the arg is already in kwargs, we don't want to use default values result.setdefault(arg_name, arg) else: # 'func' has a *args argument result["args"] = args if args_to_ignore: for kw in args_to_ignore: del result[kw] return result def log_calls(func): """Logs all func calls' arguments under func.calls. func.calls is a list of _unify_args() result (dict). Mostly used for unit testing. """ def wrapper(*args, **kwargs): unified_args = _unify_args(func, args, kwargs) wrapper.calls.append(unified_args) return func(*args, **kwargs) wrapper.calls = [] return wrapper
6,339
Python
.py
150
34.053333
109
0.617599
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,102
build.py
arsenetar_dupeguru/hscommon/build.py
# Created By: Virgil Dupras # Created On: 2009-03-03 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html """This module is a collection of function to help in HS apps build process. """ from argparse import ArgumentParser import os import sys import os.path as op import shutil import tempfile import plistlib from subprocess import Popen import re import importlib from datetime import datetime import glob from typing import Any, AnyStr, Callable, Dict, List, Union from hscommon.plat import ISWINDOWS def print_and_do(cmd: str) -> int: """Prints ``cmd`` and executes it in the shell.""" print(cmd) p = Popen(cmd, shell=True) return p.wait() def _perform(src: os.PathLike, dst: os.PathLike, action: Callable, actionname: str) -> None: if not op.lexists(src): print("Copying %s failed: it doesn't exist." % src) return if op.lexists(dst): if op.isdir(dst): shutil.rmtree(dst) else: os.remove(dst) print("{} {} --> {}".format(actionname, src, dst)) action(src, dst) def copy_file_or_folder(src: os.PathLike, dst: os.PathLike) -> None: if op.isdir(src): shutil.copytree(src, dst, symlinks=True) else: shutil.copy(src, dst) def move(src: os.PathLike, dst: os.PathLike) -> None: _perform(src, dst, os.rename, "Moving") def copy(src: os.PathLike, dst: os.PathLike) -> None: _perform(src, dst, copy_file_or_folder, "Copying") def _perform_on_all(pattern: AnyStr, dst: os.PathLike, action: Callable) -> None: # pattern is a glob pattern, example "folder/foo*". The file is moved directly in dst, no folder # structure from src is kept. filenames = glob.glob(pattern) for fn in filenames: destpath = op.join(dst, op.basename(fn)) action(fn, destpath) def move_all(pattern: AnyStr, dst: os.PathLike) -> None: _perform_on_all(pattern, dst, move) def copy_all(pattern: AnyStr, dst: os.PathLike) -> None: _perform_on_all(pattern, dst, copy) def filereplace(filename: os.PathLike, outfilename: Union[os.PathLike, None] = None, **kwargs) -> None: """Reads `filename`, replaces all {variables} in kwargs, and writes the result to `outfilename`.""" if outfilename is None: outfilename = filename fp = open(filename, encoding="utf-8") contents = fp.read() fp.close() # We can't use str.format() because in some files, there might be {} characters that mess with it. for key, item in kwargs.items(): contents = contents.replace(f"{{{key}}}", item) fp = open(outfilename, "wt", encoding="utf-8") fp.write(contents) fp.close() def get_module_version(modulename: str) -> str: mod = importlib.import_module(modulename) return mod.__version__ def setup_package_argparser(parser: ArgumentParser): parser.add_argument( "--sign", dest="sign_identity", help="Sign app under specified identity before packaging (OS X only)", ) parser.add_argument( "--nosign", action="store_true", dest="nosign", help="Don't sign the packaged app (OS X only)", ) parser.add_argument( "--src-pkg", action="store_true", dest="src_pkg", help="Build a tar.gz of the current source.", ) parser.add_argument( "--arch-pkg", action="store_true", dest="arch_pkg", help="Force Arch Linux packaging type, regardless of distro name.", ) # `args` come from an ArgumentParser updated with setup_package_argparser() def package_cocoa_app_in_dmg(app_path: os.PathLike, destfolder: os.PathLike, args) -> None: # Rather than signing our app in XCode during the build phase, we sign it during the package # phase because running the app before packaging can modify it and we want to be sure to have # a valid signature. if args.sign_identity: sign_identity = f"Developer ID Application: {args.sign_identity}" result = print_and_do(f'codesign --force --deep --sign "{sign_identity}" "{app_path}"') if result != 0: print("ERROR: Signing failed. Aborting packaging.") return elif not args.nosign: print("ERROR: Either --nosign or --sign argument required.") return build_dmg(app_path, destfolder) def build_dmg(app_path: os.PathLike, destfolder: os.PathLike) -> None: """Builds a DMG volume with application at ``app_path`` and puts it in ``dest_path``. The name of the resulting DMG volume is determined by the app's name and version. """ print(repr(op.join(app_path, "Contents", "Info.plist"))) with open(op.join(app_path, "Contents", "Info.plist"), "rb") as fp: plist = plistlib.load(fp) workpath = tempfile.mkdtemp() dmgpath = op.join(workpath, plist["CFBundleName"]) os.mkdir(dmgpath) print_and_do('cp -R "{}" "{}"'.format(app_path, dmgpath)) print_and_do('ln -s /Applications "%s"' % op.join(dmgpath, "Applications")) dmgname = "{}_osx_{}.dmg".format( plist["CFBundleName"].lower().replace(" ", "_"), plist["CFBundleVersion"].replace(".", "_"), ) print("Building %s" % dmgname) # UDBZ = bzip compression. UDZO (zip compression) was used before, but it compresses much less. print_and_do( 'hdiutil create "{}" -format UDBZ -nocrossdev -srcdir "{}"'.format(op.join(destfolder, dmgname), dmgpath) ) print("Build Complete") def add_to_pythonpath(path: os.PathLike) -> None: """Adds ``path`` to both ``PYTHONPATH`` env and ``sys.path``.""" abspath = op.abspath(path) pythonpath = os.environ.get("PYTHONPATH", "") pathsep = ";" if ISWINDOWS else ":" pythonpath = pathsep.join([abspath, pythonpath]) if pythonpath else abspath os.environ["PYTHONPATH"] = pythonpath sys.path.insert(1, abspath) # This is a method to hack around those freakingly tricky data inclusion/exlusion rules # in setuptools. We copy the packages *without data* in a build folder and then build the plugin # from there. def copy_packages( packages_names: List[str], dest: os.PathLike, create_links: bool = False, extra_ignores: Union[List[str], None] = None, ) -> None: """Copy python packages ``packages_names`` to ``dest``, spurious data. Copy will happen without tests, testdata, mercurial data or C extension module source with it. ``py2app`` include and exclude rules are **quite** funky, and doing this is the only reliable way to make sure we don't end up with useless stuff in our app. """ if ISWINDOWS: create_links = False if not extra_ignores: extra_ignores = [] ignore = shutil.ignore_patterns(".hg*", "tests", "testdata", "modules", "docs", "locale", *extra_ignores) for package_name in packages_names: if op.exists(package_name): source_path = package_name else: mod = __import__(package_name) source_path = mod.__file__ if mod.__file__.endswith("__init__.py"): source_path = op.dirname(source_path) dest_name = op.basename(source_path) dest_path = op.join(dest, dest_name) if op.exists(dest_path): if op.islink(dest_path): os.unlink(dest_path) else: shutil.rmtree(dest_path) print(f"Copying package at {source_path} to {dest_path}") if create_links: os.symlink(op.abspath(source_path), dest_path) else: if op.isdir(source_path): shutil.copytree(source_path, dest_path, ignore=ignore) else: shutil.copy(source_path, dest_path) def build_debian_changelog( changelogpath: os.PathLike, destfile: os.PathLike, pkgname: str, from_version: Union[str, None] = None, distribution: str = "precise", fix_version: Union[str, None] = None, ) -> None: """Builds a debian changelog out of a YAML changelog. Use fix_version to patch the top changelog to that version (if, for example, there was a packaging error and you need to quickly fix it) """ def desc2list(desc): # We take each item, enumerated with the '*' character, and transform it into a list. desc = desc.replace("\n", " ") desc = desc.replace(" ", " ") result = desc.split("*") return [s.strip() for s in result if s.strip()] ENTRY_MODEL = ( "{pkg} ({version}) {distribution}; urgency=low\n\n{changes}\n " "-- Virgil Dupras <hsoft@hardcoded.net> {date}\n\n" ) CHANGE_MODEL = " * {description}\n" changelogs = read_changelog_file(changelogpath) if from_version: # We only want logs from a particular version for index, log in enumerate(changelogs): if log["version"] == from_version: changelogs = changelogs[: index + 1] break if fix_version: changelogs[0]["version"] = fix_version rendered_logs = [] for log in changelogs: version = log["version"] logdate = log["date"] desc = log["description"] rendered_date = logdate.strftime("%a, %d %b %Y 00:00:00 +0000") rendered_descs = [CHANGE_MODEL.format(description=d) for d in desc2list(desc)] changes = "".join(rendered_descs) rendered_log = ENTRY_MODEL.format( pkg=pkgname, version=version, changes=changes, date=rendered_date, distribution=distribution, ) rendered_logs.append(rendered_log) result = "".join(rendered_logs) fp = open(destfile, "w") fp.write(result) fp.close() re_changelog_header = re.compile(r"=== ([\d.b]*) \(([\d\-]*)\)") def read_changelog_file(filename: os.PathLike) -> List[Dict[str, Any]]: def iter_by_three(it): while True: try: version = next(it) date = next(it) description = next(it) except StopIteration: return yield version, date, description with open(filename, encoding="utf-8") as fp: contents = fp.read() splitted = re_changelog_header.split(contents)[1:] # the first item is empty result = [] for version, date_str, description in iter_by_three(iter(splitted)): date = datetime.strptime(date_str, "%Y-%m-%d").date() d = { "date": date, "date_str": date_str, "version": version, "description": description.strip(), } result.append(d) return result def fix_qt_resource_file(path: os.PathLike) -> None: # pyrcc5 under Windows, if the locale is non-english, can produce a source file with a date # containing accented characters. If it does, the encoding is wrong and it prevents the file # from being correctly frozen by cx_freeze. To work around that, we open the file, strip all # comments, and save. with open(path, "rb") as fp: contents = fp.read() lines = contents.split(b"\n") lines = [line for line in lines if not line.startswith(b"#")] with open(path, "wb") as fp: fp.write(b"\n".join(lines))
11,452
Python
.py
273
35.175824
113
0.639116
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,103
job.py
arsenetar_dupeguru/hscommon/jobprogress/job.py
# Created By: Virgil Dupras # Created On: 2004/12/20 # Copyright 2011 Hardcoded Software (http://www.hardcoded.net) # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from typing import Any, Callable, Generator, List, Union class JobCancelled(Exception): "The user has cancelled the job" class JobInProgressError(Exception): "A job is already being performed, you can't perform more than one at the same time." class JobCountError(Exception): "The number of jobs started have exceeded the number of jobs allowed" class Job: """Manages a job's progression and return it's progression through a callback. Note that this class is not foolproof. For example, you could call start_subjob, and then call add_progress from the parent job, and nothing would stop you from doing it. However, it would mess your progression because it is the sub job that is supposed to drive the progression. Another example would be to start a subjob, then start another, and call add_progress from the old subjob. Once again, it would mess your progression. There are no stops because it would remove the lightweight aspect of the class (A Job would need to have a Parent instead of just a callback, and the parent could be None. A lot of checks for nothing.). Another one is that nothing stops you from calling add_progress right after SkipJob. """ # ---Magic functions def __init__(self, job_proportions: Union[List[int], int], callback: Callable) -> None: """Initialize the Job with 'jobcount' jobs. Start every job with start_job(). Every time the job progress is updated, 'callback' is called 'callback' takes a 'progress' int param, and a optional 'desc' parameter. Callback must return false if the job must be cancelled. """ if not hasattr(callback, "__call__"): raise TypeError("'callback' MUST be set when creating a Job") if isinstance(job_proportions, int): job_proportions = [1] * job_proportions self._job_proportions = list(job_proportions) self._jobcount = sum(job_proportions) self._callback = callback self._current_job = 0 self._passed_jobs = 0 self._progress = 0 self._currmax = 1 # ---Private def _subjob_callback(self, progress: int, desc: str = "") -> bool: """This is the callback passed to children jobs.""" self.set_progress(progress, desc) return True # if JobCancelled has to be raised, it will be at the highest level def _do_update(self, desc: str) -> None: """Calls the callback function with a % progress as a parameter. The parameter is a int in the 0-100 range. """ if self._current_job: passed_progress = self._passed_jobs * self._currmax current_progress = self._current_job * self._progress total_progress = self._jobcount * self._currmax progress = ((passed_progress + current_progress) * 100) // total_progress else: progress = -1 # indeterminate # It's possible that callback doesn't support a desc arg result = self._callback(progress, desc) if desc else self._callback(progress) if not result: raise JobCancelled() # ---Public def add_progress(self, progress: int = 1, desc: str = "") -> None: self.set_progress(self._progress + progress, desc) def check_if_cancelled(self) -> None: self._do_update("") # TODO type hint iterable def iter_with_progress( self, iterable, desc_format: Union[str, None] = None, every: int = 1, count: Union[int, None] = None ) -> Generator[Any, None, None]: """Iterate through ``iterable`` while automatically adding progress. WARNING: We need our iterable's length. If ``iterable`` is not a sequence (that is, something we can call ``len()`` on), you *have* to specify a count through the ``count`` argument. If ``count`` is ``None``, ``len(iterable)`` is used. """ if count is None: count = len(iterable) desc = "" if desc_format: desc = desc_format % (0, count) self.start_job(count, desc) for i, element in enumerate(iterable, start=1): yield element if i % every == 0: if desc_format: desc = desc_format % (i, count) self.add_progress(progress=every, desc=desc) if desc_format: desc = desc_format % (count, count) self.set_progress(100, desc) def start_job(self, max_progress: int = 100, desc: str = "") -> None: """Begin work on the next job. You must not call start_job more than 'jobcount' (in __init__) times. 'max' is the job units you are to perform. 'desc' is the description of the job. """ self._passed_jobs += self._current_job try: self._current_job = self._job_proportions.pop(0) except IndexError: raise JobCountError() self._progress = 0 self._currmax = max(1, max_progress) self._do_update(desc) def start_subjob(self, job_proportions: Union[List[int], int], desc: str = "") -> "Job": """Starts a sub job. Use this when you want to split a job into multiple smaller jobs. Pretty handy when starting a process where you know how many subjobs you will have, but don't know the work unit count for every of them. returns the Job object """ self.start_job(100, desc) return Job(job_proportions, self._subjob_callback) def set_progress(self, progress: int, desc: str = "") -> None: """Sets the progress of the current job to 'progress', and call the callback """ self._progress = progress if self._progress > self._currmax: self._progress = self._currmax self._do_update(desc) class NullJob(Job): def __init__(self, *args, **kwargs) -> None: # Null job does nothing pass def add_progress(self, *args, **kwargs) -> None: # Null job does nothing pass def check_if_cancelled(self) -> None: # Null job does nothing pass def start_job(self, *args, **kwargs) -> None: # Null job does nothing pass def start_subjob(self, *args, **kwargs) -> "NullJob": return NullJob() def set_progress(self, *args, **kwargs) -> None: # Null job does nothing pass nulljob = NullJob()
6,812
Python
.py
144
39.166667
108
0.636829
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,104
performer.py
arsenetar_dupeguru/hscommon/jobprogress/performer.py
# Created By: Virgil Dupras # Created On: 2010-11-19 # Copyright 2011 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from threading import Thread import sys from typing import Callable, Tuple, Union from hscommon.jobprogress.job import Job, JobInProgressError, JobCancelled class ThreadedJobPerformer: """Run threaded jobs and track progress. To run a threaded job, first create a job with _create_job(), then call _run_threaded(), with your work function as a parameter. Example: j = self._create_job() self._run_threaded(self.some_work_func, (arg1, arg2, j)) """ _job_running = False last_error = None # --- Protected def create_job(self) -> Job: if self._job_running: raise JobInProgressError() self.last_progress: Union[int, None] = -1 self.last_desc = "" self.job_cancelled = False return Job(1, self._update_progress) def _async_run(self, *args) -> None: target = args[0] args = tuple(args[1:]) self._job_running = True self.last_error = None try: target(*args) except JobCancelled: pass except Exception as e: self.last_error = e self.last_traceback = sys.exc_info()[2] finally: self._job_running = False self.last_progress = None def reraise_if_error(self) -> None: """Reraises the error that happened in the thread if any. Call this after the caller of run_threaded detected that self._job_running returned to False """ if self.last_error is not None: raise self.last_error.with_traceback(self.last_traceback) def _update_progress(self, newprogress: int, newdesc: str = "") -> bool: self.last_progress = newprogress if newdesc: self.last_desc = newdesc return not self.job_cancelled def run_threaded(self, target: Callable, args: Tuple = ()) -> None: if self._job_running: raise JobInProgressError() args = (target,) + args Thread(target=self._async_run, args=args).start()
2,373
Python
.py
60
32.25
100
0.645498
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,105
progress_window.py
arsenetar_dupeguru/hscommon/gui/progress_window.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from typing import Callable, Tuple, Union from hscommon.jobprogress.performer import ThreadedJobPerformer from hscommon.gui.base import GUIObject from hscommon.gui.text_field import TextField class ProgressWindowView: """Expected interface for :class:`ProgressWindow`'s view. *Not actually used in the code. For documentation purposes only.* Our view, some kind window with a progress bar, two labels and a cancel button, is expected to properly respond to its callbacks. It's also expected to call :meth:`ProgressWindow.cancel` when the cancel button is clicked. """ def show(self) -> None: """Show the dialog.""" def close(self) -> None: """Close the dialog.""" def set_progress(self, progress: int) -> None: """Set the progress of the progress bar to ``progress``. Not all jobs are equally responsive on their job progress report and it is recommended that you put your progressbar in "indeterminate" mode as long as you haven't received the first ``set_progress()`` call to avoid letting the user think that the app is frozen. :param int progress: a value between ``0`` and ``100``. """ class ProgressWindow(GUIObject, ThreadedJobPerformer): """Cross-toolkit GUI-enabled progress window. This class allows you to run a long running, job enabled function in a separate thread and allow the user to follow its progress with a progress dialog. To use it, you start your long-running job with :meth:`run` and then have your UI layer regularly call :meth:`pulse` to refresh the job status in the UI. It is advised that you call :meth:`pulse` in the main thread because GUI toolkit usually only support calling UI-related functions from the main thread. We subclass :class:`.GUIObject` and :class:`.ThreadedJobPerformer`. Expected view: :class:`ProgressWindowView`. :param finish_func: A function ``f(jobid)`` that is called when a job is completed. ``jobid`` is an arbitrary id passed to :meth:`run`. :param error_func: A function ``f(jobid, err)`` that is called when an exception is raised and unhandled during the job. If not specified, the error will be raised in the main thread. If it's specified, it's your responsibility to raise the error if you want to. If the function returns ``True``, ``finish_func()`` will be called as if the job terminated normally. """ def __init__( self, finish_func: Callable[[Union[str, None]], None], error_func: Callable[[Union[str, None], Exception], bool] = None, ) -> None: # finish_func(jobid) is the function that is called when a job is completed. GUIObject.__init__(self) ThreadedJobPerformer.__init__(self) self._finish_func = finish_func self._error_func = error_func #: :class:`.TextField`. It contains that title you gave the job on :meth:`run`. self.jobdesc_textfield = TextField() #: :class:`.TextField`. It contains the job textual update that the function might yield #: during its course. self.progressdesc_textfield = TextField() self.jobid: Union[str, None] = None def cancel(self) -> None: """Call for a user-initiated job cancellation.""" # The UI is sometimes a bit buggy and calls cancel() on self.view.close(). We just want to # make sure that this doesn't lead us to think that the user acually cancelled the task, so # we verify that the job is still running. if self._job_running: self.job_cancelled = True def pulse(self) -> None: """Update progress reports in the GUI. Call this regularly from the GUI main run loop. The values might change before :meth:`ProgressWindowView.set_progress` happens. If the job is finished, ``pulse()`` will take care of closing the window and re-raising any exception that might have been raised during the job (in the main thread this time). If there was no exception, ``finish_func(jobid)`` is called to let you take appropriate action. """ last_progress = self.last_progress last_desc = self.last_desc if not self._job_running or last_progress is None: self.view.close() should_continue = True if self.last_error is not None: err = self.last_error.with_traceback(self.last_traceback) if self._error_func is not None: should_continue = self._error_func(self.jobid, err) else: raise err if not self.job_cancelled and should_continue: self._finish_func(self.jobid) return if self.job_cancelled: return if last_desc: self.progressdesc_textfield.text = last_desc self.view.set_progress(last_progress) def run(self, jobid: str, title: str, target: Callable, args: Tuple = ()): """Starts a threaded job. The ``target`` function will be sent, as its first argument, a :class:`.Job` instance which it can use to report on its progress. :param jobid: Arbitrary identifier which will be passed to ``finish_func()`` at the end. :param title: A title for the task you're starting. :param target: The function that does your famous long running job. :param args: additional arguments that you want to send to ``target``. """ # target is a function with its first argument being a Job. It can then be followed by other # arguments which are passed as `args`. self.jobid = jobid self.progressdesc_textfield.text = "" j = self.create_job() args = tuple([j] + list(args)) self.run_threaded(target, args) self.jobdesc_textfield.text = title self.view.show()
6,316
Python
.py
113
46.920354
100
0.661055
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,106
tree.py
arsenetar_dupeguru/hscommon/gui/tree.py
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from collections.abc import MutableSequence from hscommon.gui.base import GUIObject class Node(MutableSequence): """Pretty bland node implementation to be used in a :class:`Tree`. It has a :attr:`parent`, behaves like a list, its content being its children. Link integrity is somewhat enforced (adding a child to a node will set the child's :attr:`parent`, but that's pretty much as far as we go, integrity-wise. Nodes don't tend to move around much in a GUI tree). We don't even check for infinite node loops. Don't play around these grounds too much. Nodes are designed to be subclassed and given meaningful attributes (those you'll want to display in your tree view), but they all have a :attr:`name`, which is given on initialization. """ def __init__(self, name): self._name = name self._parent = None self._path = None self._children = [] def __repr__(self): return "<Node %r>" % self.name # --- MutableSequence overrides def __delitem__(self, key): self._children.__delitem__(key) def __getitem__(self, key): return self._children.__getitem__(key) def __len__(self): return len(self._children) def __setitem__(self, key, value): self._children.__setitem__(key, value) def append(self, node): self._children.append(node) node._parent = self node._path = None def insert(self, index, node): self._children.insert(index, node) node._parent = self node._path = None # --- Public def clear(self): """Clears the node of all its children.""" del self[:] def find(self, predicate, include_self=True): """Return the first child to match ``predicate``. See :meth:`findall`. """ try: return next(self.findall(predicate, include_self=include_self)) except StopIteration: return None def findall(self, predicate, include_self=True): """Yield all children matching ``predicate``. :param predicate: ``f(node) --> bool`` :param include_self: Whether we can return ``self`` or we return only children. """ if include_self and predicate(self): yield self for child in self: yield from child.findall(predicate, include_self=True) def get_node(self, index_path): """Returns the node at ``index_path``. :param index_path: a list of int indexes leading to our node. See :attr:`path`. """ result = self if index_path: for index in index_path: result = result[index] return result def get_path(self, target_node): """Returns the :attr:`path` of ``target_node``. If ``target_node`` is ``None``, returns ``None``. """ if target_node is None: return None return target_node.path @property def children_count(self): """Same as ``len(self)``.""" return len(self) @property def name(self): """Name for the node, supplied on init.""" return self._name @property def parent(self): """Parent of the node. If ``None``, we have a root node. """ return self._parent @property def path(self): """A list of node indexes leading from the root node to ``self``. The path of a node is always related to its :attr:`root`. It's the sequences of index that we have to take to get to our node, starting from the root. For example, if ``node.path == [1, 2, 3, 4]``, it means that ``node.root[1][2][3][4] is node``. """ if self._path is None: if self._parent is None: self._path = [] else: self._path = self._parent.path + [self._parent.index(self)] return self._path @property def root(self): """Root node of current node. To get it, we recursively follow our :attr:`parent` chain until we have ``None``. """ if self._parent is None: return self else: return self._parent.root class Tree(Node, GUIObject): """Cross-toolkit GUI-enabled tree view. This class is a bit too thin to be used as a tree view controller out of the box and HS apps that subclasses it each add quite a bit of logic to it to make it workable. Making this more usable out of the box is a work in progress. This class is here (in addition to being a :class:`Node`) mostly to handle selection. Subclasses :class:`Node` (it is the root node of all its children) and :class:`.GUIObject`. """ def __init__(self): Node.__init__(self, "") GUIObject.__init__(self) #: Where we store selected nodes (as a list of :class:`Node`) self._selected_nodes = [] # --- Virtual def _select_nodes(self, nodes): """(Virtual) Customize node selection behavior. By default, simply set :attr:`_selected_nodes`. """ self._selected_nodes = nodes # --- Override def _view_updated(self): self.view.refresh() def clear(self): self._selected_nodes = [] Node.clear(self) # --- Public @property def selected_node(self): """Currently selected node. *:class:`Node`*. *get/set*. First of :attr:`selected_nodes`. ``None`` if empty. """ return self._selected_nodes[0] if self._selected_nodes else None @selected_node.setter def selected_node(self, node): if node is not None: self._select_nodes([node]) else: self._select_nodes([]) @property def selected_nodes(self): """List of selected nodes in the tree. *List of :class:`Node`*. *get/set*. We use nodes instead of indexes to store selection because it's simpler when it's time to manage selection of multiple node levels. """ return self._selected_nodes @selected_nodes.setter def selected_nodes(self, nodes): self._select_nodes(nodes) @property def selected_path(self): """Currently selected path. *:attr:`Node.path`*. *get/set*. First of :attr:`selected_paths`. ``None`` if empty. """ return self.get_path(self.selected_node) @selected_path.setter def selected_path(self, index_path): if index_path is not None: self.selected_paths = [index_path] else: self._select_nodes([]) @property def selected_paths(self): """List of selected paths in the tree. *List of :attr:`Node.path`*. *get/set* Computed from :attr:`selected_nodes`. """ return list(map(self.get_path, self._selected_nodes)) @selected_paths.setter def selected_paths(self, index_paths): nodes = [] for path in index_paths: try: nodes.append(self.get_node(path)) except IndexError: pass self._select_nodes(nodes)
7,472
Python
.py
192
30.765625
99
0.60695
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,107
column.py
arsenetar_dupeguru/hscommon/gui/column.py
# Created By: Virgil Dupras # Created On: 2010-07-25 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import copy from typing import Any, List, Tuple, Union from hscommon.gui.base import GUIObject from hscommon.gui.table import GUITable class Column: """Holds column attributes such as its name, width, visibility, etc. These attributes are then used to correctly configure the column on the "view" side. """ def __init__(self, name: str, display: str = "", visible: bool = True, optional: bool = False) -> None: #: "programmatical" (not for display) name. Used as a reference in a couple of place, such #: as :meth:`Columns.column_by_name`. self.name = name #: Immutable index of the column. Doesn't change even when columns are re-ordered. Used in #: :meth:`Columns.column_by_index`. self.logical_index = 0 #: Index of the column in the ordered set of columns. self.ordered_index = 0 #: Width of the column. self.width = 0 #: Default width of the column. This value usually depends on the platform and is set on #: columns initialisation. It will be used if column restoration doesn't contain any #: "remembered" widths. self.default_width = 0 #: Display name (title) of the column. self.display = display #: Whether the column is visible. self.visible = visible #: Whether the column is visible by default. It will be used if column restoration doesn't #: contain any "remembered" widths. self.default_visible = visible #: Whether the column can have :attr:`visible` set to false. self.optional = optional class ColumnsView: """Expected interface for :class:`Columns`'s view. *Not actually used in the code. For documentation purposes only.* Our view, the columns controller of a table or outline, is expected to properly respond to callbacks. """ def restore_columns(self) -> None: """Update all columns according to the model. When this is called, our view has to update the columns title, order and visibility of all columns. """ def set_column_visible(self, colname: str, visible: bool) -> None: """Update visibility of column ``colname``. Called when the user toggles the visibility of a column, we must update the column ``colname``'s visibility status to ``visible``. """ class PrefAccessInterface: """Expected interface for :class:`Columns`'s prefaccess. *Not actually used in the code. For documentation purposes only.* """ def get_default(self, key: str, fallback_value: Union[Any, None]) -> Any: """Retrieve the value for ``key`` in the currently running app's preference store. If the key doesn't exist, return ``fallback_value``. """ def set_default(self, key: str, value: Any) -> None: """Set the value ``value`` for ``key`` in the currently running app's preference store.""" class Columns(GUIObject): """Cross-toolkit GUI-enabled column set for tables or outlines. Manages a column set's order, visibility and width. We also manage the persistence of these attributes so that we can restore them on the next run. Subclasses :class:`.GUIObject`. Expected view: :class:`ColumnsView`. :param table: The table the columns belong to. It's from there that we retrieve our column configuration and it must have a ``COLUMNS`` attribute which is a list of :class:`Column`. We also call :meth:`~.GUITable.save_edits` on it from time to time. Technically, this argument can also be a tree, but there's probably some sorting in the code to do to support this option cleanly. :param prefaccess: An object giving access to user preferences for the currently running app. We use this to make column attributes persistent. Must follow :class:`PrefAccessInterface`. :param str savename: The name under which column preferences will be saved. This name is in fact a prefix. Preferences are saved under more than one name, but they will all have that same prefix. """ def __init__(self, table: GUITable, prefaccess=None, savename: Union[str, None] = None): GUIObject.__init__(self) self.table = table self.prefaccess = prefaccess self.savename = savename # We use copy here for test isolation. If we don't, changing a column affects all tests. self.column_list: List[Column] = list(map(copy.copy, table.COLUMNS)) for i, column in enumerate(self.column_list): column.logical_index = i column.ordered_index = i self.coldata = {col.name: col for col in self.column_list} # --- Private def _get_colname_attr(self, colname: str, attrname: str, default: Any) -> Any: try: return getattr(self.coldata[colname], attrname) except KeyError: return default def _set_colname_attr(self, colname: str, attrname: str, value: Any) -> None: try: col = self.coldata[colname] setattr(col, attrname, value) except KeyError: pass def _optional_columns(self) -> List[Column]: return [c for c in self.column_list if c.optional] # --- Override def _view_updated(self) -> None: self.restore_columns() # --- Public def column_by_index(self, index: int): """Return the :class:`Column` having the :attr:`~Column.logical_index` ``index``.""" return self.column_list[index] def column_by_name(self, name: str): """Return the :class:`Column` having the :attr:`~Column.name` ``name``.""" return self.coldata[name] def columns_count(self) -> int: """Returns the number of columns in our set.""" return len(self.column_list) def column_display(self, colname: str) -> str: """Returns display name for column named ``colname``, or ``''`` if there's none.""" return self._get_colname_attr(colname, "display", "") def column_is_visible(self, colname: str) -> bool: """Returns visibility for column named ``colname``, or ``True`` if there's none.""" return self._get_colname_attr(colname, "visible", True) def column_width(self, colname: str) -> int: """Returns width for column named ``colname``, or ``0`` if there's none.""" return self._get_colname_attr(colname, "width", 0) def columns_to_right(self, colname: str) -> List[str]: """Returns the list of all columns to the right of ``colname``. "right" meaning "having a higher :attr:`Column.ordered_index`" in our left-to-right civilization. """ column = self.coldata[colname] index = column.ordered_index return [col.name for col in self.column_list if (col.visible and col.ordered_index > index)] def menu_items(self) -> List[Tuple[str, bool]]: """Returns a list of items convenient for quick visibility menu generation. Returns a list of ``(display_name, is_marked)`` items for each optional column in the current view (``is_marked`` means that it's visible). You can use this to generate a menu to let the user toggle the visibility of an optional column. That is why we only show optional column, because the visibility of mandatory columns can't be toggled. """ return [(c.display, c.visible) for c in self._optional_columns()] def move_column(self, colname: str, index: int) -> None: """Moves column ``colname`` to ``index``. The column will be placed just in front of the column currently having that index, or to the end of the list if there's none. """ colnames = self.colnames colnames.remove(colname) colnames.insert(index, colname) self.set_column_order(colnames) def reset_to_defaults(self) -> None: """Reset all columns' width and visibility to their default values.""" self.set_column_order([col.name for col in self.column_list]) for col in self._optional_columns(): col.visible = col.default_visible col.width = col.default_width self.view.restore_columns() def resize_column(self, colname: str, newwidth: int) -> None: """Set column ``colname``'s width to ``newwidth``.""" self._set_colname_attr(colname, "width", newwidth) def restore_columns(self) -> None: """Restore's column persistent attributes from the last :meth:`save_columns`.""" if not (self.prefaccess and self.savename and self.coldata): if (not self.savename) and (self.coldata): # This is a table that will not have its coldata saved/restored. we should # "restore" its default column attributes. self.view.restore_columns() return for col in self.column_list: pref_name = f"{self.savename}.Columns.{col.name}" coldata = self.prefaccess.get_default(pref_name, fallback_value={}) if "index" in coldata: col.ordered_index = coldata["index"] if "width" in coldata: col.width = coldata["width"] if col.optional and "visible" in coldata: col.visible = coldata["visible"] self.view.restore_columns() def save_columns(self) -> None: """Save column attributes in persistent storage for restoration in :meth:`restore_columns`.""" if not (self.prefaccess and self.savename and self.coldata): return for col in self.column_list: pref_name = f"{self.savename}.Columns.{col.name}" coldata = {"index": col.ordered_index, "width": col.width} if col.optional: coldata["visible"] = col.visible self.prefaccess.set_default(pref_name, coldata) # TODO annotate colnames def set_column_order(self, colnames) -> None: """Change the columns order so it matches the order in ``colnames``. :param colnames: A list of column names in the desired order. """ colnames = (name for name in colnames if name in self.coldata) for i, colname in enumerate(colnames): col = self.coldata[colname] col.ordered_index = i def set_column_visible(self, colname: str, visible: bool) -> None: """Set the visibility of column ``colname``.""" self.table.save_edits() # the table on the GUI side will stop editing when the columns change self._set_colname_attr(colname, "visible", visible) self.view.set_column_visible(colname, visible) def set_default_width(self, colname: str, width: int) -> None: """Set the default width or column ``colname``.""" self._set_colname_attr(colname, "default_width", width) def toggle_menu_item(self, index: int) -> bool: """Toggles the visibility of an optional column. You know, that optional column menu you've generated in :meth:`menu_items`? Well, ``index`` is the index of them menu item in *that* menu that the user has clicked on to toggle it. Returns whether the column in question ends up being visible or not. """ col = self._optional_columns()[index] self.set_column_visible(col.name, not col.visible) return col.visible # --- Properties @property def ordered_columns(self) -> List[Column]: """List of :class:`Column` in visible order.""" return [col for col in sorted(self.column_list, key=lambda col: col.ordered_index)] @property def colnames(self) -> List[str]: """List of column names in visible order.""" return [col.name for col in self.ordered_columns]
12,278
Python
.py
228
44.991228
107
0.646407
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,108
selectable_list.py
arsenetar_dupeguru/hscommon/gui/selectable_list.py
# Created By: Virgil Dupras # Created On: 2011-09-06 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from collections.abc import Sequence, MutableSequence from hscommon.gui.base import GUIObject class Selectable(Sequence): """Mix-in for a ``Sequence`` that manages its selection status. When mixed in with a ``Sequence``, we enable it to manage its selection status. The selection is held as a list of ``int`` indexes. Multiple selection is supported. """ def __init__(self): self._selected_indexes = [] # --- Private def _check_selection_range(self): if not self: self._selected_indexes = [] if not self._selected_indexes: return self._selected_indexes = [index for index in self._selected_indexes if index < len(self)] if not self._selected_indexes: self._selected_indexes = [len(self) - 1] # --- Virtual def _update_selection(self): """(Virtual) Updates the model's selection appropriately. Called after selection has been updated. Takes the table's selection and does appropriates updates on the view and/or model. Common sense would dictate that when the selection doesn't change, we don't update anything (and thus don't call ``_update_selection()`` at all), but there are cases where it's false. For example, if our list updates its items but doesn't change its selection, we probably want to update the model's selection. By default, does nothing. Important note: This is only called on :meth:`select`, not on changes to :attr:`selected_indexes`. """ # A redesign of how this whole thing works is probably in order, but not now, there's too # much breakage at once involved. # --- Public def select(self, indexes): """Update selection to ``indexes``. :meth:`_update_selection` is called afterwards. :param list indexes: List of ``int`` that is to become the new selection. """ if isinstance(indexes, int): indexes = [indexes] self.selected_indexes = indexes self._update_selection() # --- Properties @property def selected_index(self): """Points to the first selected index. *int*. *get/set*. Thin wrapper around :attr:`selected_indexes`. ``None`` if selection is empty. Using this property only makes sense if your selectable sequence supports single selection only. """ return self._selected_indexes[0] if self._selected_indexes else None @selected_index.setter def selected_index(self, value): self.selected_indexes = [value] @property def selected_indexes(self): """List of selected indexes. *list of int*. *get/set*. When setting the value, automatically removes out-of-bounds indexes. The list is kept sorted. """ return self._selected_indexes @selected_indexes.setter def selected_indexes(self, value): self._selected_indexes = value self._selected_indexes.sort() self._check_selection_range() class SelectableList(MutableSequence, Selectable): """A list that can manage selection of its items. Subclasses :class:`Selectable`. Behaves like a ``list``. """ def __init__(self, items=None): Selectable.__init__(self) if items: self._items = list(items) else: self._items = [] def __delitem__(self, key): self._items.__delitem__(key) self._check_selection_range() self._on_change() def __getitem__(self, key): return self._items.__getitem__(key) def __len__(self): return len(self._items) def __setitem__(self, key, value): self._items.__setitem__(key, value) self._on_change() # --- Override def append(self, item): self._items.append(item) self._on_change() def insert(self, index, item): self._items.insert(index, item) self._on_change() def remove(self, row): self._items.remove(row) self._check_selection_range() self._on_change() # --- Virtual def _on_change(self): """(Virtual) Called whenever the contents of the list changes. By default, does nothing. """ # --- Public def search_by_prefix(self, prefix): # XXX Why the heck is this method here? prefix = prefix.lower() for index, s in enumerate(self): if s.lower().startswith(prefix): return index return -1 class GUISelectableListView: """Expected interface for :class:`GUISelectableList`'s view. *Not actually used in the code. For documentation purposes only.* Our view, some kind of list view or combobox, is expected to sync with the list's contents by appropriately behave to all callbacks in this interface. """ def refresh(self): """Refreshes the contents of the list widget. Ensures that the contents of the list widget is synced with the model. """ def update_selection(self): """Update selection status. Ensures that the list widget's selection is in sync with the model. """ class GUISelectableList(SelectableList, GUIObject): """Cross-toolkit GUI-enabled list view. Represents a UI element presenting the user with a selectable list of items. Subclasses :class:`SelectableList` and :class:`.GUIObject`. Expected view: :class:`GUISelectableListView`. :param iterable items: If specified, items to fill the list with initially. """ def __init__(self, items=None): SelectableList.__init__(self, items) GUIObject.__init__(self) def _view_updated(self): """Refreshes the view contents with :meth:`GUISelectableListView.refresh`. Overrides :meth:`~hscommon.gui.base.GUIObject._view_updated`. """ self.view.refresh() def _update_selection(self): """Refreshes the view selection with :meth:`GUISelectableListView.update_selection`. Overrides :meth:`Selectable._update_selection`. """ self.view.update_selection() def _on_change(self): """Refreshes the view contents with :meth:`GUISelectableListView.refresh`. Overrides :meth:`SelectableList._on_change`. """ self.view.refresh()
6,722
Python
.py
158
34.962025
100
0.651506
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,109
table.py
arsenetar_dupeguru/hscommon/gui/table.py
# Created By: Eric Mc Sween # Created On: 2008-05-29 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from collections.abc import MutableSequence from collections import namedtuple from typing import Any, List, Tuple, Union from hscommon.gui.base import GUIObject from hscommon.gui.selectable_list import Selectable # We used to directly subclass list, but it caused problems at some point with deepcopy class Table(MutableSequence, Selectable): """Sortable and selectable sequence of :class:`Row`. In fact, the Table is very similar to :class:`.SelectableList` in practice and differs mostly in principle. Their difference lies in the nature of their items they manage. With the Table, rows usually have many properties, presented in columns, and they have to subclass :class:`Row`. Usually used with :class:`~hscommon.gui.column.Column`. Subclasses :class:`.Selectable`. """ # Should be List[Column], but have circular import... COLUMNS: List = [] def __init__(self) -> None: Selectable.__init__(self) self._rows: List["Row"] = [] self._header: Union["Row", None] = None self._footer: Union["Row", None] = None # TODO type hint for key def __delitem__(self, key): self._rows.__delitem__(key) if self._header is not None and ((not self) or (self[0] is not self._header)): self._header = None if self._footer is not None and ((not self) or (self[-1] is not self._footer)): self._footer = None self._check_selection_range() # TODO type hint for key def __getitem__(self, key) -> Any: return self._rows.__getitem__(key) def __len__(self) -> int: return len(self._rows) # TODO type hint for key def __setitem__(self, key, value: Any) -> None: self._rows.__setitem__(key, value) def append(self, item: "Row") -> None: """Appends ``item`` at the end of the table. If there's a footer, the item is inserted before it. """ if self._footer is not None: self._rows.insert(-1, item) else: self._rows.append(item) def insert(self, index: int, item: "Row") -> None: """Inserts ``item`` at ``index`` in the table. If there's a header, will make sure we don't insert before it, and if there's a footer, will make sure that we don't insert after it. """ if (self._header is not None) and (index == 0): index = 1 if (self._footer is not None) and (index >= len(self)): index = len(self) - 1 self._rows.insert(index, item) def remove(self, row: "Row") -> None: """Removes ``row`` from table. If ``row`` is a header or footer, that header or footer will be set to ``None``. """ if row is self._header: self._header = None if row is self._footer: self._footer = None self._rows.remove(row) self._check_selection_range() def sort_by(self, column_name: str, desc: bool = False) -> None: """Sort table by ``column_name``. Sort key for each row is computed from :meth:`Row.sort_key_for_column`. If ``desc`` is ``True``, sort order is reversed. If present, header and footer will always be first and last, respectively. """ if self._header is not None: self._rows.pop(0) if self._footer is not None: self._rows.pop() self._rows.sort(key=lambda row: row.sort_key_for_column(column_name), reverse=desc) if self._header is not None: self._rows.insert(0, self._header) if self._footer is not None: self._rows.append(self._footer) # --- Properties @property def footer(self) -> Union["Row", None]: """If set, a row that always stay at the bottom of the table. :class:`Row`. *get/set*. When set to something else than ``None``, ``header`` and ``footer`` represent rows that will always be kept in first and/or last position, regardless of sorting. ``len()`` and indexing will include them, which means that if there's a header, ``table[0]`` returns it and if there's a footer, ``table[-1]`` returns it. To make things short, all list-like functions work with header and footer "on". But things get fuzzy for ``append()`` and ``insert()`` because these will ensure that no "normal" row gets inserted before the header or after the footer. Adding and removing footer here and there might seem (and is) hackish, but it's much simpler than the alternative (when, of course, you need such a feature), which is to override magic methods and adjust the results. When we do that, there the slice stuff that we have to implement and it gets quite complex. Moreover, the most frequent operation on a table is ``__getitem__``, and making checks to know whether the key is a header or footer at each call would make that operation, which is the most used, slower. """ return self._footer @footer.setter def footer(self, value: Union["Row", None]) -> None: if self._footer is not None: self._rows.pop() if value is not None: self._rows.append(value) self._footer = value @property def header(self) -> Union["Row", None]: """If set, a row that always stay at the bottom of the table. See :attr:`footer` for details. """ return self._header @header.setter def header(self, value: Union["Row", None]) -> None: if self._header is not None: self._rows.pop(0) if value is not None: self._rows.insert(0, value) self._header = value @property def row_count(self) -> int: """Number or rows in the table (without counting header and footer). *int*. *read-only*. """ result = len(self) if self._footer is not None: result -= 1 if self._header is not None: result -= 1 return result @property def rows(self) -> List["Row"]: """List of rows in the table, excluding header and footer. List of :class:`Row`. *read-only*. """ start = None end = None if self._footer is not None: end = -1 if self._header is not None: start = 1 return self[start:end] @property def selected_row(self) -> "Row": """Selected row according to :attr:`Selectable.selected_index`. :class:`Row`. *get/set*. When setting this attribute, we look up the index of the row and set the selected index from there. If the row isn't in the list, selection isn't changed. """ return self[self.selected_index] if self.selected_index is not None else None @selected_row.setter def selected_row(self, value: int) -> None: try: self.selected_index = self.index(value) except ValueError: pass @property def selected_rows(self) -> List["Row"]: """List of selected rows based on :attr:`.selected_indexes`. List of :class:`Row`. *read-only*. """ return [self[index] for index in self.selected_indexes] class GUITableView: """Expected interface for :class:`GUITable`'s view. *Not actually used in the code. For documentation purposes only.* Our view, some kind of table view, is expected to sync with the table's contents by appropriately behave to all callbacks in this interface. When in edit mode, the content types by the user is expected to be sent as soon as possible to the :class:`Row`. Whenever the user changes the selection, we expect the view to call :meth:`Table.select`. """ def refresh(self) -> None: """Refreshes the contents of the table widget. Ensures that the contents of the table widget is synced with the model. This includes selection. """ def start_editing(self) -> None: """Start editing the currently selected row. Begin whatever inline editing support that the view supports. """ def stop_editing(self) -> None: """Stop editing if there's an inline editing in effect. There's no "aborting" implied in this call, so it's appropriate to send whatever the user has typed and might not have been sent down to the :class:`Row` yet. After you've done that, stop the editing mechanism. """ SortDescriptor = namedtuple("SortDescriptor", "column desc") class GUITable(Table, GUIObject): """Cross-toolkit GUI-enabled table view. Represents a UI element presenting the user with a sortable, selectable, possibly editable, table view. Behaves like the :class:`Table` which it subclasses, but is more focused on being the presenter of some model data to its :attr:`.GUIObject.view`. There's a :meth:`refresh` mechanism which ensures fresh data while preserving sorting order and selection. There's also an editing mechanism which tracks whether (and which) row is being edited (or added) and save/cancel edits when appropriate. Subclasses :class:`Table` and :class:`.GUIObject`. Expected view: :class:`GUITableView`. """ def __init__(self) -> None: GUIObject.__init__(self) Table.__init__(self) #: The row being currently edited by the user. ``None`` if no edit is taking place. self.edited: Union["Row", None] = None self._sort_descriptor: Union[SortDescriptor, None] = None # --- Virtual def _do_add(self) -> Tuple["Row", int]: """(Virtual) Creates a new row, adds it in the table. Returns ``(row, insert_index)``. """ raise NotImplementedError() def _do_delete(self) -> None: """(Virtual) Delete the selected rows.""" pass def _fill(self) -> None: """(Virtual/Required) Fills the table with all the rows that this table is supposed to have. Called by :meth:`refresh`. Does nothing by default. """ pass def _is_edited_new(self) -> bool: """(Virtual) Returns whether the currently edited row should be considered "new". This is used in :meth:`cancel_edits` to know whether the cancellation of the edit means a revert of the row's value or the removal of the row. By default, always false. """ return False def _restore_selection(self, previous_selection): """(Virtual) Restores row selection after a contents-changing operation. Before each contents changing operation, we store our previously selected indexes because in many cases, such as in :meth:`refresh`, our selection will be lost. After the operation is over, we call this method with our previously selected indexes (in ``previous_selection``). The default behavior is (if we indeed have an empty :attr:`.selected_indexes`) to re-select ``previous_selection``. If it was empty, we select the last row of the table. This behavior can, of course, be overriden. """ if not self.selected_indexes: if previous_selection: self.select(previous_selection) else: self.select([len(self) - 1]) # --- Public def add(self) -> None: """Add a new row in edit mode. Requires :meth:`do_add` to be implemented. The newly added row will be selected and in edit mode. """ self.view.stop_editing() if self.edited is not None: self.save_edits() row, insert_index = self._do_add() self.insert(insert_index, row) self.select([insert_index]) self.view.refresh() # We have to set "edited" after calling refresh() because some UI are trigger-happy # about calling save_edits() and they do so during calls to refresh(). We don't want # a call to save_edits() during refresh prematurely mess with our newly added item. self.edited = row self.view.start_editing() def can_edit_cell(self, column_name: str, row_index: int) -> bool: """Returns whether the cell at ``row_index`` and ``column_name`` can be edited. A row is, by default, editable as soon as it has an attr with the same name as `column`. If :meth:`Row.can_edit` returns False, the row is not editable at all. You can set editability of rows at the attribute level with can_edit_* properties. Mostly just a shortcut to :meth:`Row.can_edit_cell`. """ row = self[row_index] return row.can_edit_cell(column_name) def cancel_edits(self) -> None: """Cancels the current edit operation. If there's an :attr:`edited` row, it will be re-initialized (with :meth:`Row.load`). """ if self.edited is None: return self.view.stop_editing() if self._is_edited_new(): previous_selection = self.selected_indexes self.remove(self.edited) self._restore_selection(previous_selection) self._update_selection() else: self.edited.load() self.edited = None self.view.refresh() def delete(self) -> None: """Delete the currently selected rows. Requires :meth:`_do_delete` for this to have any effect on the model. Cancels editing if relevant. """ self.view.stop_editing() if self.edited is not None: self.cancel_edits() return if self: self._do_delete() def refresh(self, refresh_view: bool = True) -> None: """Empty the table and re-create its rows. :meth:`_fill` is called after we emptied the table to create our rows. Previous sort order will be preserved, regardless of the order in which the rows were filled. If there was any edit operation taking place, it's cancelled. :param bool refresh_view: Whether we tell our view to refresh after our refill operation. Most of the time, it's what we want, but there's some cases where we don't. """ self.cancel_edits() previous_selection = self.selected_indexes del self[:] self._fill() sd = self._sort_descriptor if sd is not None: Table.sort_by(self, column_name=sd.column, desc=sd.desc) self._restore_selection(previous_selection) if refresh_view: self.view.refresh() def save_edits(self) -> None: """Commit user edits to the model. This is done by calling :meth:`Row.save`. """ if self.edited is None: return row = self.edited self.edited = None row.save() def sort_by(self, column_name: str, desc: bool = False) -> None: """Sort table by ``column_name``. Overrides :meth:`Table.sort_by`. After having performed sorting, calls :meth:`~.Selectable._update_selection` to give you the chance, if appropriate, to update your selected indexes according to, maybe, the selection that you have in your model. Then, we refresh our view. """ Table.sort_by(self, column_name=column_name, desc=desc) self._sort_descriptor = SortDescriptor(column_name, desc) self._update_selection() self.view.refresh() class Row: """Represents a row in a :class:`Table`. It holds multiple values to be represented through columns. It's its role to prepare data fetched from model instances into ready-to-present-in-a-table fashion. You will do this in :meth:`load`. When you do this, you'll put the result into arbitrary attributes, which will later be fetched by your table for presentation to the user. You can organize your attributes in whatever way you want, but there's a convention you can follow if you want to minimize subclassing and use default behavior: 1. Attribute name = column name. If your attribute is ``foobar``, whenever we refer to ``column_name``, you refer to that attribute with the column name ``foobar``. 2. Public attributes are for *formatted* value, that is, user readable strings. 3. Underscore prefix is the unformatted (computable) value. For example, you could have ``_foobar`` at ``42`` and ``foobar`` at ``"42 seconds"`` (what you present to the user). 4. Unformatted values are used for sorting. 5. If your column name is a python keyword, add an underscore suffix (``from_``). Of course, this is only default behavior. This can be overriden. """ def __init__(self, table: GUITable) -> None: super().__init__() self.table = table def _edit(self) -> None: if self.table.edited is self: return assert self.table.edited is None self.table.edited = self # --- Virtual def can_edit(self) -> bool: """(Virtual) Whether the whole row can be edited. By default, always returns ``True``. This is for the *whole* row. For individual cells, it's :meth:`can_edit_cell`. """ return True def load(self) -> None: """(Virtual/Required) Loads up values from the model to be presented in the table. Usually, our model instances contain values that are not quite ready for display. If you have number formatting, display calculations and other whatnots to perform, you do it here and then you put the result in an arbitrary attribute of the row. """ raise NotImplementedError() def save(self) -> None: """(Virtual/Required) Saves user edits into your model. If your table is editable, this is called when the user commits his changes. Usually, these are typed up stuff, or selected indexes. You have to do proper parsing and reference linking, and save that stuff into your model. """ raise NotImplementedError() def sort_key_for_column(self, column_name: str) -> Any: """(Virtual) Return the value that is to be used to sort by column ``column_name``. By default, looks for an attribute with the same name as ``column_name``, but with an underscore prefix ("unformatted value"). If there's none, tries without the underscore. If there's none, raises ``AttributeError``. """ try: return getattr(self, "_" + column_name) except AttributeError: return getattr(self, column_name) # --- Public def can_edit_cell(self, column_name: str) -> bool: """Returns whether cell for column ``column_name`` can be edited. By the default, the check is done in many steps: 1. We check whether the whole row can be edited with :meth:`can_edit`. If it can't, the cell can't either. 2. If the column doesn't exist as an attribute, we can't edit. 3. If we have an attribute ``can_edit_<column_name>``, return that. 4. Check if our attribute is a property. If it's not, it's not editable. 5. If our attribute is in fact a property, check whether the property is "settable" (has a ``fset`` method). The cell is editable only if the property is "settable". """ if not self.can_edit(): return False # '_' is in case column is a python keyword if not hasattr(self, column_name): if hasattr(self, column_name + "_"): column_name = column_name + "_" else: return False if hasattr(self, "can_edit_" + column_name): return getattr(self, "can_edit_" + column_name) # If the row has a settable property, we can edit the cell rowclass = self.__class__ prop = getattr(rowclass, column_name, None) if prop is None: return False return bool(getattr(prop, "fset", None)) def get_cell_value(self, attrname: str) -> Any: """Get cell value for ``attrname``. By default, does a simple ``getattr()``, but it is used to allow subclasses to have alternative value storage mechanisms. """ if attrname == "from": attrname = "from_" return getattr(self, attrname) def set_cell_value(self, attrname: str, value: Any) -> None: """Set cell value to ``value`` for ``attrname``. By default, does a simple ``setattr()``, but it is used to allow subclasses to have alternative value storage mechanisms. """ if attrname == "from": attrname = "from_" setattr(self, attrname, value)
21,256
Python
.py
444
39.256757
100
0.631752
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,110
base.py
arsenetar_dupeguru/hscommon/gui/base.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html def noop(*args, **kwargs): pass class NoopGUI: def __getattr__(self, func_name): return noop class GUIObject: """Cross-toolkit "model" representation of a GUI layer object. A ``GUIObject`` is a cross-toolkit "model" representation of a GUI layer object, for example, a table. It acts as a cross-toolkit interface to what we call here a :attr:`view`. That view is a toolkit-specific controller to the actual view (an ``NSTableView``, a ``QTableView``, etc.). In our GUIObject, we need a reference to that toolkit-specific controller because some actions have effects on it (for example, prompting it to refresh its data). The ``GUIObject`` is typically instantiated before its :attr:`view`, that is why we set it to ``None`` on init. However, the GUI layer is supposed to set the view as soon as its toolkit-specific controller is instantiated. When you subclass ``GUIObject``, you will likely want to update its view on instantiation. That is why we call ``self.view.refresh()`` in :meth:`_view_updated`. If you need another type of action on view instantiation, just override the method. Most of the time, you will only one to bind a view once in the lifetime of your GUI object. That is why there are safeguards, when setting ``view`` to ensure that we don't double-assign. However, sometimes you want to be able to re-bind another view. In this case, set the ``multibind`` flag to ``True`` and the safeguard will be disabled. """ def __init__(self, multibind: bool = False) -> None: self._view = None self._multibind = multibind def _view_updated(self) -> None: """(Virtual) Called after :attr:`view` has been set. Doing nothing by default, this method is called after :attr:`view` has been set (it isn't called when it's unset, however). Use this for initialization code that requires a view (which is often the whole of the initialization code). """ def has_view(self) -> bool: return (self._view is not None) and (not isinstance(self._view, NoopGUI)) @property def view(self): """A reference to our toolkit-specific view controller. *view answering to GUIObject sublass's view protocol*. *get/set* This view starts as ``None`` and has to be set "manually". There's two times at which we set the view property: On initialization, where we set the view that we'll use for our lifetime, and just before the view is deallocated. We need to unset our view at that time to avoid calls to a deallocated instance (which means a crash). To unset our view, we simple assign it to ``None``. """ return self._view @view.setter def view(self, value) -> None: if self._view is None and value is None: # Initial view assignment return if self._view is None or self._multibind: if value is None: value = NoopGUI() self._view = value self._view_updated() else: assert value is None # Instead of None, we put a NoopGUI() there to avoid rogue view callback raising an # exception. self._view = NoopGUI()
3,581
Python
.py
65
47.723077
100
0.675815
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,111
text_field.py
arsenetar_dupeguru/hscommon/gui/text_field.py
# Created On: 2012/01/23 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.gui.base import GUIObject from hscommon.util import nonone class TextFieldView: """Expected interface for :class:`TextField`'s view. *Not actually used in the code. For documentation purposes only.* Our view is expected to sync with :attr:`TextField.text` "both ways", that is, update the model's text when the user types something, but also update the text field when :meth:`refresh` is called. """ def refresh(self): """Refreshes the contents of the input widget. Ensures that the contents of the input widget is actually :attr:`TextField.text`. """ class TextField(GUIObject): """Cross-toolkit text field. Represents a UI element allowing the user to input a text value. Its main attribute is :attr:`text` which acts as the store of the said value. When our model value isn't a string, we have a built-in parsing/formatting mechanism allowing us to directly retrieve/set our non-string value through :attr:`value`. Subclasses :class:`.GUIObject`. Expected view: :class:`TextFieldView`. """ def __init__(self): GUIObject.__init__(self) self._text = "" self._value = None # --- Virtual def _parse(self, text): """(Virtual) Parses ``text`` to put into :attr:`value`. Returns the parsed version of ``text``. Called whenever :attr:`text` changes. """ return text def _format(self, value): """(Virtual) Formats ``value`` to put into :attr:`text`. Returns the formatted version of ``value``. Called whenever :attr:`value` changes. """ return value def _update(self, newvalue): """(Virtual) Called whenever we have a new value. Whenever our text/value store changes to a new value (different from the old one), this method is called. By default, it does nothing but you can override it if you want. """ # --- Override def _view_updated(self): self.view.refresh() # --- Public def refresh(self): """Triggers a view :meth:`~TextFieldView.refresh`.""" self.view.refresh() @property def text(self): """The text that is currently displayed in the widget. *str*. *get/set*. This property can be set. When it is, :meth:`refresh` is called and the view is synced with our value. Always in sync with :attr:`value`. """ return self._text @text.setter def text(self, newtext): self.value = self._parse(nonone(newtext, "")) @property def value(self): """The "parsed" representation of :attr:`text`. *arbitrary type*. *get/set*. By default, it's a mirror of :attr:`text`, but a subclass can override :meth:`_parse` and :meth:`_format` to have anything else. Always in sync with :attr:`text`. """ return self._value @value.setter def value(self, newvalue): if newvalue == self._value: return self._value = newvalue self._text = self._format(newvalue) self._update(self._value) self.refresh()
3,465
Python
.py
81
35.888889
99
0.651863
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,112
table_test.py
arsenetar_dupeguru/hscommon/tests/table_test.py
# Created By: Virgil Dupras # Created On: 2008-08-12 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.testutil import CallLogger, eq_ from hscommon.gui.table import Table, GUITable, Row class TestRow(Row): __test__ = False def __init__(self, table, index, is_new=False): Row.__init__(self, table) self.is_new = is_new self._index = index def load(self): # Does nothing for test pass def save(self): self.is_new = False @property def index(self): return self._index class TestGUITable(GUITable): __test__ = False def __init__(self, rowcount, viewclass=CallLogger): GUITable.__init__(self) self.view = viewclass() self.view.model = self self.rowcount = rowcount self.updated_rows = None def _do_add(self): return TestRow(self, len(self), is_new=True), len(self) def _is_edited_new(self): return self.edited is not None and self.edited.is_new def _fill(self): for i in range(self.rowcount): self.append(TestRow(self, i)) def _update_selection(self): self.updated_rows = self.selected_rows[:] def table_with_footer(): table = Table() table.append(TestRow(table, 0)) footer = TestRow(table, 1) table.footer = footer return table, footer def table_with_header(): table = Table() table.append(TestRow(table, 1)) header = TestRow(table, 0) table.header = header return table, header # --- Tests def test_allow_edit_when_attr_is_property_with_fset(): # When a row has a property that has a fset, by default, make that cell editable. class TestRow(Row): @property def foo(self): # property only for existence checks pass @property def bar(self): # property only for existence checks pass @bar.setter def bar(self, value): # setter only for existence checks pass row = TestRow(Table()) assert row.can_edit_cell("bar") assert not row.can_edit_cell("foo") assert not row.can_edit_cell("baz") # doesn't exist, can't edit def test_can_edit_prop_has_priority_over_fset_checks(): # When a row has a cen_edit_* property, it's the result of that property that is used, not the # result of a fset check. class TestRow(Row): @property def bar(self): # property only for existence checks pass @bar.setter def bar(self, value): # setter only for existence checks pass can_edit_bar = False row = TestRow(Table()) assert not row.can_edit_cell("bar") def test_in(): # When a table is in a list, doing "in list" with another instance returns false, even if # they're the same as lists. table = Table() some_list = [table] assert Table() not in some_list def test_footer_del_all(): # Removing all rows doesn't crash when doing the footer check. table, footer = table_with_footer() del table[:] assert table.footer is None def test_footer_del_row(): # Removing the footer row sets it to None table, footer = table_with_footer() del table[-1] assert table.footer is None eq_(len(table), 1) def test_footer_is_appened_to_table(): # A footer is appended at the table's bottom table, footer = table_with_footer() eq_(len(table), 2) assert table[1] is footer def test_footer_remove(): # remove() on footer sets it to None table, footer = table_with_footer() table.remove(footer) assert table.footer is None def test_footer_replaces_old_footer(): table, footer = table_with_footer() other = Row(table) table.footer = other assert table.footer is other eq_(len(table), 2) assert table[1] is other def test_footer_rows_and_row_count(): # rows() and row_count() ignore footer. table, footer = table_with_footer() eq_(table.row_count, 1) eq_(table.rows, table[:-1]) def test_footer_setting_to_none_removes_old_one(): table, footer = table_with_footer() table.footer = None assert table.footer is None eq_(len(table), 1) def test_footer_stays_there_on_append(): # Appending another row puts it above the footer table, footer = table_with_footer() table.append(Row(table)) eq_(len(table), 3) assert table[2] is footer def test_footer_stays_there_on_insert(): # Inserting another row puts it above the footer table, footer = table_with_footer() table.insert(3, Row(table)) eq_(len(table), 3) assert table[2] is footer def test_header_del_all(): # Removing all rows doesn't crash when doing the header check. table, header = table_with_header() del table[:] assert table.header is None def test_header_del_row(): # Removing the header row sets it to None table, header = table_with_header() del table[0] assert table.header is None eq_(len(table), 1) def test_header_is_inserted_in_table(): # A header is inserted at the table's top table, header = table_with_header() eq_(len(table), 2) assert table[0] is header def test_header_remove(): # remove() on header sets it to None table, header = table_with_header() table.remove(header) assert table.header is None def test_header_replaces_old_header(): table, header = table_with_header() other = Row(table) table.header = other assert table.header is other eq_(len(table), 2) assert table[0] is other def test_header_rows_and_row_count(): # rows() and row_count() ignore header. table, header = table_with_header() eq_(table.row_count, 1) eq_(table.rows, table[1:]) def test_header_setting_to_none_removes_old_one(): table, header = table_with_header() table.header = None assert table.header is None eq_(len(table), 1) def test_header_stays_there_on_insert(): # Inserting another row at the top puts it below the header table, header = table_with_header() table.insert(0, Row(table)) eq_(len(table), 3) assert table[0] is header def test_refresh_view_on_refresh(): # If refresh_view is not False, we refresh the table's view on refresh() table = TestGUITable(1) table.refresh() table.view.check_gui_calls(["refresh"]) table.view.clear_calls() table.refresh(refresh_view=False) table.view.check_gui_calls([]) def test_restore_selection(): # By default, after a refresh, selection goes on the last row table = TestGUITable(10) table.refresh() eq_(table.selected_indexes, [9]) def test_restore_selection_after_cancel_edits(): # _restore_selection() is called after cancel_edits(). Previously, only _update_selection would # be called. class MyTable(TestGUITable): def _restore_selection(self, previous_selection): self.selected_indexes = [6] table = MyTable(10) table.refresh() table.add() table.cancel_edits() eq_(table.selected_indexes, [6]) def test_restore_selection_with_previous_selection(): # By default, we try to restore the selection that was there before a refresh table = TestGUITable(10) table.refresh() table.selected_indexes = [2, 4] table.refresh() eq_(table.selected_indexes, [2, 4]) def test_restore_selection_custom(): # After a _fill() called, the virtual _restore_selection() is called so that it's possible for a # GUITable subclass to customize its post-refresh selection behavior. class MyTable(TestGUITable): def _restore_selection(self, previous_selection): self.selected_indexes = [6] table = MyTable(10) table.refresh() eq_(table.selected_indexes, [6]) def test_row_cell_value(): # *_cell_value() correctly mangles attrnames that are Python reserved words. row = Row(Table()) row.from_ = "foo" eq_(row.get_cell_value("from"), "foo") row.set_cell_value("from", "bar") eq_(row.get_cell_value("from"), "bar") def test_sort_table_also_tries_attributes_without_underscores(): # When determining a sort key, after having unsuccessfully tried the attribute with the, # underscore, try the one without one. table = Table() row1 = Row(table) row1._foo = "a" # underscored attr must be checked first row1.foo = "b" row1.bar = "c" row2 = Row(table) row2._foo = "b" row2.foo = "a" row2.bar = "b" table.append(row1) table.append(row2) table.sort_by("foo") assert table[0] is row1 assert table[1] is row2 table.sort_by("bar") assert table[0] is row2 assert table[1] is row1 def test_sort_table_updates_selection(): table = TestGUITable(10) table.refresh() table.select([2, 4]) table.sort_by("index", desc=True) # Now, the updated rows should be 7 and 5 eq_(len(table.updated_rows), 2) r1, r2 = table.updated_rows eq_(r1.index, 7) eq_(r2.index, 5) def test_sort_table_with_footer(): # Sorting a table with a footer keeps it at the bottom table, footer = table_with_footer() table.sort_by("index", desc=True) assert table[-1] is footer def test_sort_table_with_header(): # Sorting a table with a header keeps it at the top table, header = table_with_header() table.sort_by("index", desc=True) assert table[0] is header def test_add_with_view_that_saves_during_refresh(): # Calling save_edits during refresh() called by add() is ignored. class TableView(CallLogger): def refresh(self): self.model.save_edits() table = TestGUITable(10, viewclass=TableView) table.add() assert table.edited is not None # still in edit mode
10,049
Python
.py
282
30.134752
100
0.66646
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,113
conflict_test.py
arsenetar_dupeguru/hscommon/tests/conflict_test.py
# Created By: Virgil Dupras # Created On: 2008-01-08 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import pytest from hscommon.conflict import ( get_conflicted_name, get_unconflicted_name, is_conflicted, smart_copy, smart_move, ) from pathlib import Path from hscommon.testutil import eq_ class TestCaseGetConflictedName: def test_simple(self): name = get_conflicted_name(["bar"], "bar") eq_("[000] bar", name) name = get_conflicted_name(["bar", "[000] bar"], "bar") eq_("[001] bar", name) def test_no_conflict(self): name = get_conflicted_name(["bar"], "foobar") eq_("foobar", name) def test_fourth_digit(self): # This test is long because every time we have to add a conflicted name, # a test must be made for every other conflicted name existing... # Anyway, this has very few chances to happen. names = ["bar"] + ["[%03d] bar" % i for i in range(1000)] name = get_conflicted_name(names, "bar") eq_("[1000] bar", name) def test_auto_unconflict(self): # Automatically unconflict the name if it's already conflicted. name = get_conflicted_name([], "[000] foobar") eq_("foobar", name) name = get_conflicted_name(["bar"], "[001] bar") eq_("[000] bar", name) class TestCaseGetUnconflictedName: def test_main(self): eq_("foobar", get_unconflicted_name("[000] foobar")) eq_("foobar", get_unconflicted_name("[9999] foobar")) eq_("[000]foobar", get_unconflicted_name("[000]foobar")) eq_("[000a] foobar", get_unconflicted_name("[000a] foobar")) eq_("foobar", get_unconflicted_name("foobar")) eq_("foo [000] bar", get_unconflicted_name("foo [000] bar")) class TestCaseIsConflicted: def test_main(self): assert is_conflicted("[000] foobar") assert is_conflicted("[9999] foobar") assert not is_conflicted("[000]foobar") assert not is_conflicted("[000a] foobar") assert not is_conflicted("foobar") assert not is_conflicted("foo [000] bar") class TestCaseMoveCopy: @pytest.fixture def do_setup(self, request): tmpdir = request.getfixturevalue("tmpdir") self.path = Path(str(tmpdir)) self.path.joinpath("foo").touch() self.path.joinpath("bar").touch() self.path.joinpath("dir").mkdir() def test_move_no_conflict(self, do_setup): smart_move(self.path.joinpath("foo"), self.path.joinpath("baz")) assert self.path.joinpath("baz").exists() assert not self.path.joinpath("foo").exists() def test_copy_no_conflict(self, do_setup): # No need to duplicate the rest of the tests... Let's just test on move smart_copy(self.path.joinpath("foo"), self.path.joinpath("baz")) assert self.path.joinpath("baz").exists() assert self.path.joinpath("foo").exists() def test_move_no_conflict_dest_is_dir(self, do_setup): smart_move(self.path.joinpath("foo"), self.path.joinpath("dir")) assert self.path.joinpath("dir", "foo").exists() assert not self.path.joinpath("foo").exists() def test_move_conflict(self, do_setup): smart_move(self.path.joinpath("foo"), self.path.joinpath("bar")) assert self.path.joinpath("[000] bar").exists() assert not self.path.joinpath("foo").exists() def test_move_conflict_dest_is_dir(self, do_setup): smart_move(self.path.joinpath("foo"), self.path.joinpath("dir")) smart_move(self.path.joinpath("bar"), self.path.joinpath("foo")) smart_move(self.path.joinpath("foo"), self.path.joinpath("dir")) assert self.path.joinpath("dir", "foo").exists() assert self.path.joinpath("dir", "[000] foo").exists() assert not self.path.joinpath("foo").exists() assert not self.path.joinpath("bar").exists() def test_copy_folder(self, tmpdir): # smart_copy also works on folders path = Path(str(tmpdir)) path.joinpath("foo").mkdir() path.joinpath("bar").mkdir() smart_copy(path.joinpath("foo"), path.joinpath("bar")) # no crash assert path.joinpath("[000] bar").exists()
4,451
Python
.py
93
40.752688
119
0.64592
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,114
util_test.py
arsenetar_dupeguru/hscommon/tests/util_test.py
# Created By: Virgil Dupras # Created On: 2011-01-11 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from io import StringIO from pytest import raises from hscommon.testutil import eq_ from pathlib import Path from hscommon.util import ( nonone, tryint, first, flatten, dedupe, extract, allsame, format_time, format_time_decimal, format_size, multi_replace, delete_if_empty, open_if_filename, FileOrPath, iterconsume, escape, get_file_ext, rem_file_ext, pluralize, ) def test_nonone(): eq_("foo", nonone("foo", "bar")) eq_("bar", nonone(None, "bar")) def test_tryint(): eq_(42, tryint("42")) eq_(0, tryint("abc")) eq_(0, tryint(None)) eq_(42, tryint(None, 42)) # --- Sequence def test_first(): eq_(first([3, 2, 1]), 3) eq_(first(i for i in [3, 2, 1] if i < 3), 2) def test_flatten(): eq_([1, 2, 3, 4], flatten([[1, 2], [3, 4]])) eq_([], flatten([])) def test_dedupe(): reflist = [0, 7, 1, 2, 3, 4, 4, 5, 6, 7, 1, 2, 3] eq_(dedupe(reflist), [0, 7, 1, 2, 3, 4, 5, 6]) def test_extract(): wheat, shaft = extract(lambda n: n % 2 == 0, list(range(10))) eq_(wheat, [0, 2, 4, 6, 8]) eq_(shaft, [1, 3, 5, 7, 9]) def test_allsame(): assert allsame([42, 42, 42]) assert not allsame([42, 43, 42]) assert not allsame([43, 42, 42]) # Works on non-sequence as well assert allsame(iter([42, 42, 42])) def test_iterconsume(): # We just want to make sure that we return *all* items and that we're not mistakenly skipping # one. eq_(list(range(2500)), list(iterconsume(list(range(2500))))) eq_(list(reversed(range(2500))), list(iterconsume(list(range(2500)), reverse=False))) # --- String def test_escape(): eq_("f\\o\\ob\\ar", escape("foobar", "oa")) eq_("f*o*ob*ar", escape("foobar", "oa", "*")) eq_("f*o*ob*ar", escape("foobar", set("oa"), "*")) def test_get_file_ext(): eq_(get_file_ext("foobar"), "") eq_(get_file_ext("foo.bar"), "bar") eq_(get_file_ext("foobar."), "") eq_(get_file_ext(".foobar"), "foobar") def test_rem_file_ext(): eq_(rem_file_ext("foobar"), "foobar") eq_(rem_file_ext("foo.bar"), "foo") eq_(rem_file_ext("foobar."), "foobar") eq_(rem_file_ext(".foobar"), "") def test_pluralize(): eq_("0 song", pluralize(0, "song")) eq_("1 song", pluralize(1, "song")) eq_("2 songs", pluralize(2, "song")) eq_("1 song", pluralize(1.1, "song")) eq_("2 songs", pluralize(1.5, "song")) eq_("1.1 songs", pluralize(1.1, "song", 1)) eq_("1.5 songs", pluralize(1.5, "song", 1)) eq_("2 entries", pluralize(2, "entry", plural_word="entries")) def test_format_time(): eq_(format_time(0), "00:00:00") eq_(format_time(1), "00:00:01") eq_(format_time(23), "00:00:23") eq_(format_time(60), "00:01:00") eq_(format_time(101), "00:01:41") eq_(format_time(683), "00:11:23") eq_(format_time(3600), "01:00:00") eq_(format_time(3754), "01:02:34") eq_(format_time(36000), "10:00:00") eq_(format_time(366666), "101:51:06") eq_(format_time(0, with_hours=False), "00:00") eq_(format_time(1, with_hours=False), "00:01") eq_(format_time(23, with_hours=False), "00:23") eq_(format_time(60, with_hours=False), "01:00") eq_(format_time(101, with_hours=False), "01:41") eq_(format_time(683, with_hours=False), "11:23") eq_(format_time(3600, with_hours=False), "60:00") eq_(format_time(6036, with_hours=False), "100:36") eq_(format_time(60360, with_hours=False), "1006:00") def test_format_time_decimal(): eq_(format_time_decimal(0), "0.0 second") eq_(format_time_decimal(1), "1.0 second") eq_(format_time_decimal(23), "23.0 seconds") eq_(format_time_decimal(60), "1.0 minute") eq_(format_time_decimal(101), "1.7 minutes") eq_(format_time_decimal(683), "11.4 minutes") eq_(format_time_decimal(3600), "1.0 hour") eq_(format_time_decimal(6036), "1.7 hours") eq_(format_time_decimal(86400), "1.0 day") eq_(format_time_decimal(160360), "1.9 days") def test_format_size(): eq_(format_size(1024), "1 KB") eq_(format_size(1024, 2), "1.00 KB") eq_(format_size(1024, 0, 2), "1 MB") eq_(format_size(1024, 2, 2), "0.01 MB") eq_(format_size(1024, 3, 2), "0.001 MB") eq_(format_size(1024, 3, 2, False), "0.001") eq_(format_size(1023), "1023 B") eq_(format_size(1023, 0, 1), "1 KB") eq_(format_size(511, 0, 1), "1 KB") eq_(format_size(9), "9 B") eq_(format_size(99), "99 B") eq_(format_size(999), "999 B") eq_(format_size(9999), "10 KB") eq_(format_size(99999), "98 KB") eq_(format_size(999999), "977 KB") eq_(format_size(9999999), "10 MB") eq_(format_size(99999999), "96 MB") eq_(format_size(999999999), "954 MB") eq_(format_size(9999999999), "10 GB") eq_(format_size(99999999999), "94 GB") eq_(format_size(999999999999), "932 GB") eq_(format_size(9999999999999), "10 TB") eq_(format_size(99999999999999), "91 TB") eq_(format_size(999999999999999), "910 TB") eq_(format_size(9999999999999999), "9 PB") eq_(format_size(99999999999999999), "89 PB") eq_(format_size(999999999999999999), "889 PB") eq_(format_size(9999999999999999999), "9 EB") eq_(format_size(99999999999999999999), "87 EB") eq_(format_size(999999999999999999999), "868 EB") eq_(format_size(9999999999999999999999), "9 ZB") eq_(format_size(99999999999999999999999), "85 ZB") eq_(format_size(999999999999999999999999), "848 ZB") def test_multi_replace(): eq_("136", multi_replace("123456", ("2", "45"))) eq_("1 3 6", multi_replace("123456", ("2", "45"), " ")) eq_("1 3 6", multi_replace("123456", "245", " ")) eq_("173896", multi_replace("123456", "245", "789")) eq_("173896", multi_replace("123456", "245", ("7", "8", "9"))) eq_("17386", multi_replace("123456", ("2", "45"), "78")) eq_("17386", multi_replace("123456", ("2", "45"), ("7", "8"))) with raises(ValueError): multi_replace("123456", ("2", "45"), ("7", "8", "9")) eq_("17346", multi_replace("12346", ("2", "45"), "78")) # --- Files class TestCaseDeleteIfEmpty: def test_is_empty(self, tmpdir): testpath = Path(str(tmpdir)) assert delete_if_empty(testpath) assert not testpath.exists() def test_not_empty(self, tmpdir): testpath = Path(str(tmpdir)) testpath.joinpath("foo").mkdir() assert not delete_if_empty(testpath) assert testpath.exists() def test_with_files_to_delete(self, tmpdir): testpath = Path(str(tmpdir)) testpath.joinpath("foo").touch() testpath.joinpath("bar").touch() assert delete_if_empty(testpath, ["foo", "bar"]) assert not testpath.exists() def test_directory_in_files_to_delete(self, tmpdir): testpath = Path(str(tmpdir)) testpath.joinpath("foo").mkdir() assert not delete_if_empty(testpath, ["foo"]) assert testpath.exists() def test_delete_files_to_delete_only_if_dir_is_empty(self, tmpdir): testpath = Path(str(tmpdir)) testpath.joinpath("foo").touch() testpath.joinpath("bar").touch() assert not delete_if_empty(testpath, ["foo"]) assert testpath.exists() assert testpath.joinpath("foo").exists() def test_doesnt_exist(self): # When the 'path' doesn't exist, just do nothing. delete_if_empty(Path("does_not_exist")) # no crash def test_is_file(self, tmpdir): # When 'path' is a file, do nothing. p = Path(str(tmpdir)).joinpath("filename") p.touch() delete_if_empty(p) # no crash def test_ioerror(self, tmpdir, monkeypatch): # if an IO error happens during the operation, ignore it. def do_raise(*args, **kw): raise OSError() monkeypatch.setattr(Path, "rmdir", do_raise) delete_if_empty(Path(str(tmpdir))) # no crash class TestCaseOpenIfFilename: FILE_NAME = "test.txt" def test_file_name(self, tmpdir): filepath = str(tmpdir.join(self.FILE_NAME)) open(filepath, "wb").write(b"test_data") file, close = open_if_filename(filepath) assert close eq_(b"test_data", file.read()) file.close() def test_opened_file(self): sio = StringIO() sio.write("test_data") sio.seek(0) file, close = open_if_filename(sio) assert not close eq_("test_data", file.read()) def test_mode_is_passed_to_open(self, tmpdir): filepath = str(tmpdir.join(self.FILE_NAME)) open(filepath, "w").close() file, close = open_if_filename(filepath, "a") eq_("a", file.mode) file.close() class TestCaseFileOrPath: FILE_NAME = "test.txt" def test_path(self, tmpdir): filepath = str(tmpdir.join(self.FILE_NAME)) open(filepath, "wb").write(b"test_data") with FileOrPath(filepath) as fp: eq_(b"test_data", fp.read()) def test_opened_file(self): sio = StringIO() sio.write("test_data") sio.seek(0) with FileOrPath(sio) as fp: eq_("test_data", fp.read()) def test_mode_is_passed_to_open(self, tmpdir): filepath = str(tmpdir.join(self.FILE_NAME)) open(filepath, "w").close() with FileOrPath(filepath, "a") as fp: eq_("a", fp.mode)
9,695
Python
.py
248
33.314516
97
0.606968
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,115
notify_test.py
arsenetar_dupeguru/hscommon/tests/notify_test.py
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.testutil import eq_ from hscommon.notify import Broadcaster, Listener, Repeater class HelloListener(Listener): def __init__(self, broadcaster): Listener.__init__(self, broadcaster) self.hello_count = 0 def hello(self): self.hello_count += 1 class HelloRepeater(Repeater): def __init__(self, broadcaster): Repeater.__init__(self, broadcaster) self.hello_count = 0 def hello(self): self.hello_count += 1 def create_pair(): b = Broadcaster() listener = HelloListener(b) return b, listener def test_disconnect_during_notification(): # When a listener disconnects another listener the other listener will not receive a # notification. # This whole complication scheme below is because the order of the notification is not # guaranteed. We could disconnect everything from self.broadcaster.listeners, but this # member is supposed to be private. Hence, the '.other' scheme class Disconnecter(Listener): def __init__(self, broadcaster): Listener.__init__(self, broadcaster) self.hello_count = 0 def hello(self): self.hello_count += 1 self.other.disconnect() broadcaster = Broadcaster() first = Disconnecter(broadcaster) second = Disconnecter(broadcaster) first.other, second.other = second, first first.connect() second.connect() broadcaster.notify("hello") # only one of them was notified eq_(first.hello_count + second.hello_count, 1) def test_disconnect(): # After a disconnect, the listener doesn't hear anything. b, listener = create_pair() listener.connect() listener.disconnect() b.notify("hello") eq_(listener.hello_count, 0) def test_disconnect_when_not_connected(): # When disconnecting an already disconnected listener, nothing happens. b, listener = create_pair() listener.disconnect() def test_not_connected_on_init(): # A listener is not initialized connected. b, listener = create_pair() b.notify("hello") eq_(listener.hello_count, 0) def test_notify(): # The listener listens to the broadcaster. b, listener = create_pair() listener.connect() b.notify("hello") eq_(listener.hello_count, 1) def test_reconnect(): # It's possible to reconnect a listener after disconnection. b, listener = create_pair() listener.connect() listener.disconnect() listener.connect() b.notify("hello") eq_(listener.hello_count, 1) def test_repeater(): b = Broadcaster() r = HelloRepeater(b) listener = HelloListener(r) r.connect() listener.connect() b.notify("hello") eq_(r.hello_count, 1) eq_(listener.hello_count, 1) def test_repeater_with_repeated_notifications(): # If REPEATED_NOTIFICATIONS is not empty, only notifs in this set are repeated (but they're # still dispatched locally). class MyRepeater(HelloRepeater): REPEATED_NOTIFICATIONS = {"hello"} def __init__(self, broadcaster): HelloRepeater.__init__(self, broadcaster) self.foo_count = 0 def foo(self): self.foo_count += 1 b = Broadcaster() r = MyRepeater(b) listener = HelloListener(r) r.connect() listener.connect() b.notify("hello") b.notify("foo") # if the repeater repeated this notif, we'd get a crash on HelloListener eq_(r.hello_count, 1) eq_(listener.hello_count, 1) eq_(r.foo_count, 1) def test_repeater_doesnt_try_to_dispatch_to_self_if_it_cant(): # if a repeater doesn't handle a particular message, it doesn't crash and simply repeats it. b = Broadcaster() r = Repeater(b) # doesnt handle hello listener = HelloListener(r) r.connect() listener.connect() b.notify("hello") # no crash eq_(listener.hello_count, 1) def test_bind_messages(): b, listener = create_pair() listener.bind_messages({"foo", "bar"}, listener.hello) listener.connect() b.notify("foo") b.notify("bar") b.notify("hello") # Normal dispatching still work eq_(listener.hello_count, 3)
4,444
Python
.py
120
31.541667
96
0.683376
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,116
path_test.py
arsenetar_dupeguru/hscommon/tests/path_test.py
# Created By: Virgil Dupras # Created On: 2006/02/21 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.path import pathify from pathlib import Path def test_pathify(): @pathify def foo(a: Path, b, c: Path): return a, b, c a, b, c = foo("foo", 0, c=Path("bar")) assert isinstance(a, Path) assert a == Path("foo") assert b == 0 assert isinstance(c, Path) assert c == Path("bar") def test_pathify_preserve_none(): # @pathify preserves None value and doesn't try to return a Path @pathify def foo(a: Path): return a a = foo(None) assert a is None
857
Python
.py
25
30.24
89
0.683252
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,117
selectable_list_test.py
arsenetar_dupeguru/hscommon/tests/selectable_list_test.py
# Created By: Virgil Dupras # Created On: 2011-09-06 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.testutil import eq_, callcounter, CallLogger from hscommon.gui.selectable_list import SelectableList, GUISelectableList def test_in(): # When a SelectableList is in a list, doing "in list" with another instance returns false, even # if they're the same as lists. sl = SelectableList() some_list = [sl] assert SelectableList() not in some_list def test_selection_range(): # selection is correctly adjusted on deletion sl = SelectableList(["foo", "bar", "baz"]) sl.selected_index = 3 eq_(sl.selected_index, 2) del sl[2] eq_(sl.selected_index, 1) def test_update_selection_called(): # _update_selection_is called after a change in selection. However, we only do so on select() # calls. I follow the old behavior of the Table class. At the moment, I don't quite remember # why there was a specific select() method for triggering _update_selection(), but I think I # remember there was a reason, so I keep it that way. sl = SelectableList(["foo", "bar"]) sl._update_selection = callcounter() sl.select(1) eq_(sl._update_selection.callcount, 1) sl.selected_index = 0 eq_(sl._update_selection.callcount, 1) # no call def test_guicalls(): # A GUISelectableList appropriately calls its view. sl = GUISelectableList(["foo", "bar"]) sl.view = CallLogger() sl.view.check_gui_calls(["refresh"]) # Upon setting the view, we get a call to refresh() sl[1] = "baz" sl.view.check_gui_calls(["refresh"]) sl.append("foo") sl.view.check_gui_calls(["refresh"]) del sl[2] sl.view.check_gui_calls(["refresh"]) sl.remove("baz") sl.view.check_gui_calls(["refresh"]) sl.insert(0, "foo") sl.view.check_gui_calls(["refresh"]) sl.select(1) sl.view.check_gui_calls(["update_selection"]) # XXX We have to give up on this for now because of a breakage it causes in the tables. # sl.select(1) # don't update when selection stays the same # gui.check_gui_calls([]) def test_search_by_prefix(): sl = SelectableList(["foo", "bAr", "baZ"]) eq_(sl.search_by_prefix("b"), 1) eq_(sl.search_by_prefix("BA"), 1) eq_(sl.search_by_prefix("BAZ"), 2) eq_(sl.search_by_prefix("BAZZ"), -1)
2,577
Python
.py
59
39.440678
99
0.688073
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,118
tree_test.py
arsenetar_dupeguru/hscommon/tests/tree_test.py
# Created By: Virgil Dupras # Created On: 2010-02-12 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.testutil import eq_ from hscommon.gui.tree import Tree, Node def tree_with_some_nodes(): t = Tree() t.append(Node("foo")) t.append(Node("bar")) t.append(Node("baz")) t[0].append(Node("sub1")) t[0].append(Node("sub2")) return t def test_selection(): t = tree_with_some_nodes() assert t.selected_node is None eq_(t.selected_nodes, []) assert t.selected_path is None eq_(t.selected_paths, []) def test_select_one_node(): t = tree_with_some_nodes() t.selected_node = t[0][0] assert t.selected_node is t[0][0] eq_(t.selected_nodes, [t[0][0]]) eq_(t.selected_path, [0, 0]) eq_(t.selected_paths, [[0, 0]]) def test_select_one_path(): t = tree_with_some_nodes() t.selected_path = [0, 1] assert t.selected_node is t[0][1] def test_select_multiple_nodes(): t = tree_with_some_nodes() t.selected_nodes = [t[0], t[1]] eq_(t.selected_paths, [[0], [1]]) def test_select_multiple_paths(): t = tree_with_some_nodes() t.selected_paths = [[0], [1]] eq_(t.selected_nodes, [t[0], t[1]]) def test_select_none_path(): # setting selected_path to None clears the selection t = Tree() t.selected_path = None assert t.selected_path is None def test_select_none_node(): # setting selected_node to None clears the selection t = Tree() t.selected_node = None eq_(t.selected_nodes, []) def test_clear_removes_selection(): # When clearing a tree, we want to clear the selection as well or else we end up with a crash # when calling selected_paths. t = tree_with_some_nodes() t.selected_path = [0] t.clear() assert t.selected_node is None def test_selection_override(): # All selection changed pass through the _select_node() method so it's easy for subclasses to # customize the tree's behavior. class MyTree(Tree): called = False def _select_nodes(self, nodes): self.called = True t = MyTree() t.selected_paths = [] assert t.called t.called = False t.selected_node = None assert t.called def test_findall(): t = tree_with_some_nodes() r = t.findall(lambda n: n.name.startswith("sub")) eq_(set(r), {t[0][0], t[0][1]}) def test_findall_dont_include_self(): # When calling findall with include_self=False, the node itself is never evaluated. t = tree_with_some_nodes() del t._name # so that if the predicate is called on `t`, we crash r = t.findall(lambda n: not n.name.startswith("sub"), include_self=False) # no crash eq_(set(r), {t[0], t[1], t[2]}) def test_find_dont_include_self(): # When calling find with include_self=False, the node itself is never evaluated. t = tree_with_some_nodes() del t._name # so that if the predicate is called on `t`, we crash r = t.find(lambda n: not n.name.startswith("sub"), include_self=False) # no crash assert r is t[0] def test_find_none(): # when find() yields no result, return None t = Tree() assert t.find(lambda n: False) is None # no StopIteration exception
3,443
Python
.py
92
32.913043
97
0.661747
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,119
util.py
arsenetar_dupeguru/core/util.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import time import sys import os import urllib.request import urllib.error import json import semantic_version import logging from typing import Union from hscommon.util import format_time_decimal def format_timestamp(t, delta): if delta: return format_time_decimal(t) else: if t > 0: return time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(t)) else: return "---" def format_words(w): def do_format(w): if isinstance(w, list): return "(%s)" % ", ".join(do_format(item) for item in w) else: return w.replace("\n", " ") return ", ".join(do_format(item) for item in w) def format_perc(p): return "%0.0f" % p def format_dupe_count(c): return str(c) if c else "---" def cmp_value(dupe, attrname): value = getattr(dupe, attrname, "") return value.lower() if isinstance(value, str) else value def fix_surrogate_encoding(s, encoding="utf-8"): # ref #210. It's possible to end up with file paths that, while correct unicode strings, are # decoded with the 'surrogateescape' option, which make the string unencodable to utf-8. We fix # these strings here by trying to encode them and, if it fails, we do an encode/decode dance # to remove the problematic characters. This dance is *lossy* but there's not much we can do # because if we end up with this type of string, it means that we don't know the encoding of the # underlying filesystem that brought them. Don't use this for strings you're going to re-use in # fs-related functions because you're going to lose your path (it's going to change). Use this # if you need to export the path somewhere else, outside of the unicode realm. # See http://lucumr.pocoo.org/2013/7/2/the-updated-guide-to-unicode/ try: s.encode(encoding) except UnicodeEncodeError: return s.encode(encoding, "replace").decode(encoding) else: return s def executable_folder(): return os.path.dirname(os.path.abspath(sys.argv[0])) def check_for_update(current_version: str, include_prerelease: bool = False) -> Union[None, dict]: request = urllib.request.Request( "https://api.github.com/repos/arsenetar/dupeguru/releases", headers={"Accept": "application/vnd.github.v3+json"}, ) try: with urllib.request.urlopen(request) as response: if response.status != 200: logging.warn(f"Error retriving updates. Status: {response.status}") return None try: response_json = json.loads(response.read()) except json.JSONDecodeError as ex: logging.warn(f"Error parsing updates. {ex.msg}") return None except urllib.error.URLError as ex: logging.warn(f"Error retriving updates. {ex.reason}") return None new_version = semantic_version.Version(current_version) new_url = None for release in response_json: release_version = semantic_version.Version(release["name"]) if new_version < release_version and (include_prerelease or not release_version.prerelease): new_version = release_version new_url = release["html_url"] if new_url is not None: return {"version": new_version, "url": new_url} else: return None
3,646
Python
.py
84
36.892857
100
0.674287
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,120
fs.py
arsenetar_dupeguru/core/fs.py
# Created By: Virgil Dupras # Created On: 2009-10-22 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html # This is a fork from hsfs. The reason for this fork is that hsfs has been designed for musicGuru # and was re-used for dupeGuru. The problem is that hsfs is way over-engineered for dupeGuru, # resulting needless complexity and memory usage. It's been a while since I wanted to do that fork, # and I'm doing it now. import os from math import floor import logging import sqlite3 from sys import platform from threading import Lock from typing import Any, AnyStr, Union, Callable from pathlib import Path from hscommon.util import nonone, get_file_ext hasher: Callable try: import xxhash hasher = xxhash.xxh128 except ImportError: import hashlib hasher = hashlib.md5 __all__ = [ "File", "Folder", "get_file", "get_files", "FSError", "AlreadyExistsError", "InvalidPath", "InvalidDestinationError", "OperationError", ] NOT_SET = object() # The goal here is to not run out of memory on really big files. However, the chunk # size has to be large enough so that the python loop isn't too costly in terms of # CPU. CHUNK_SIZE = 1024 * 1024 # 1 MiB # Minimum size below which partial hashing is not used MIN_FILE_SIZE = 3 * CHUNK_SIZE # 3MiB, because we take 3 samples # Partial hashing offset and size PARTIAL_OFFSET_SIZE = (0x4000, 0x4000) class FSError(Exception): cls_message = "An error has occured on '{name}' in '{parent}'" def __init__(self, fsobject, parent=None): message = self.cls_message if isinstance(fsobject, str): name = fsobject elif isinstance(fsobject, File): name = fsobject.name else: name = "" parentname = str(parent) if parent is not None else "" Exception.__init__(self, message.format(name=name, parent=parentname)) class AlreadyExistsError(FSError): "The directory or file name we're trying to add already exists" cls_message = "'{name}' already exists in '{parent}'" class InvalidPath(FSError): "The path of self is invalid, and cannot be worked with." cls_message = "'{name}' is invalid." class InvalidDestinationError(FSError): """A copy/move operation has been called, but the destination is invalid.""" cls_message = "'{name}' is an invalid destination for this operation." class OperationError(FSError): """A copy/move/delete operation has been called, but the checkup after the operation shows that it didn't work.""" cls_message = "Operation on '{name}' failed." class FilesDB: schema_version = 1 schema_version_description = "Changed from md5 to xxhash if available." create_table_query = """CREATE TABLE IF NOT EXISTS files (path TEXT PRIMARY KEY, size INTEGER, mtime_ns INTEGER, entry_dt DATETIME, digest BLOB, digest_partial BLOB, digest_samples BLOB)""" drop_table_query = "DROP TABLE IF EXISTS files;" select_query = "SELECT {key} FROM files WHERE path=:path AND size=:size and mtime_ns=:mtime_ns" select_query_ignore_mtime = "SELECT {key} FROM files WHERE path=:path AND size=:size" insert_query = """ INSERT INTO files (path, size, mtime_ns, entry_dt, {key}) VALUES (:path, :size, :mtime_ns, datetime('now'), :value) ON CONFLICT(path) DO UPDATE SET size=:size, mtime_ns=:mtime_ns, entry_dt=datetime('now'), {key}=:value; """ ignore_mtime = False def __init__(self): self.conn = None self.lock = None def connect(self, path: Union[AnyStr, os.PathLike]) -> None: if platform.startswith("gnu0"): self.conn = sqlite3.connect(path, check_same_thread=False, isolation_level=None) else: self.conn = sqlite3.connect(path, check_same_thread=False) self.lock = Lock() self._check_upgrade() def _check_upgrade(self) -> None: with self.lock, self.conn as conn: has_schema = conn.execute( "SELECT NAME FROM sqlite_master WHERE type='table' AND name='schema_version'" ).fetchall() version = None if has_schema: version = conn.execute("SELECT version FROM schema_version ORDER BY version DESC").fetchone()[0] else: conn.execute("CREATE TABLE schema_version (version int PRIMARY KEY, description TEXT)") if version != self.schema_version: conn.execute(self.drop_table_query) conn.execute( "INSERT OR REPLACE INTO schema_version VALUES (:version, :description)", {"version": self.schema_version, "description": self.schema_version_description}, ) conn.execute(self.create_table_query) def clear(self) -> None: with self.lock, self.conn as conn: conn.execute(self.drop_table_query) conn.execute(self.create_table_query) def get(self, path: Path, key: str) -> Union[bytes, None]: stat = path.stat() size = stat.st_size mtime_ns = stat.st_mtime_ns try: with self.conn as conn: if self.ignore_mtime: cursor = conn.execute( self.select_query_ignore_mtime.format(key=key), {"path": str(path), "size": size} ) else: cursor = conn.execute( self.select_query.format(key=key), {"path": str(path), "size": size, "mtime_ns": mtime_ns}, ) result = cursor.fetchone() cursor.close() if result: return result[0] except Exception as ex: logging.warning(f"Couldn't get {key} for {path} w/{size}, {mtime_ns}: {ex}") return None def put(self, path: Path, key: str, value: Any) -> None: stat = path.stat() size = stat.st_size mtime_ns = stat.st_mtime_ns try: with self.lock, self.conn as conn: conn.execute( self.insert_query.format(key=key), {"path": str(path), "size": size, "mtime_ns": mtime_ns, "value": value}, ) except Exception as ex: logging.warning(f"Couldn't put {key} for {path} w/{size}, {mtime_ns}: {ex}") def commit(self) -> None: with self.lock: self.conn.commit() def close(self) -> None: with self.lock: self.conn.close() filesdb = FilesDB() # Singleton class File: """Represents a file and holds metadata to be used for scanning.""" INITIAL_INFO = {"size": 0, "mtime": 0, "digest": b"", "digest_partial": b"", "digest_samples": b""} # Slots for File make us save quite a bit of memory. In a memory test I've made with a lot of # files, I saved 35% memory usage with "unread" files (no _read_info() call) and gains become # even greater when we take into account read attributes (70%!). Yeah, it's worth it. __slots__ = ("path", "unicode_path", "is_ref", "words") + tuple(INITIAL_INFO.keys()) def __init__(self, path): for attrname in self.INITIAL_INFO: setattr(self, attrname, NOT_SET) if type(path) is os.DirEntry: self.path = Path(path.path) self.size = nonone(path.stat().st_size, 0) self.mtime = nonone(path.stat().st_mtime, 0) else: self.path = path if self.path: self.unicode_path = str(self.path) def __repr__(self): return f"<{self.__class__.__name__} {str(self.path)}>" def __getattribute__(self, attrname): result = object.__getattribute__(self, attrname) if result is NOT_SET: try: self._read_info(attrname) except Exception as e: logging.warning("An error '%s' was raised while decoding '%s'", e, repr(self.path)) result = object.__getattribute__(self, attrname) if result is NOT_SET: result = self.INITIAL_INFO[attrname] return result def _calc_digest(self): # type: () -> bytes with self.path.open("rb") as fp: file_hash = hasher() # The goal here is to not run out of memory on really big files. However, the chunk # size has to be large enough so that the python loop isn't too costly in terms of # CPU. CHUNK_SIZE = 1024 * 1024 # 1 mb filedata = fp.read(CHUNK_SIZE) while filedata: file_hash.update(filedata) filedata = fp.read(CHUNK_SIZE) return file_hash.digest() def _calc_digest_partial(self): # type: () -> bytes with self.path.open("rb") as fp: fp.seek(PARTIAL_OFFSET_SIZE[0]) partial_data = fp.read(PARTIAL_OFFSET_SIZE[1]) return hasher(partial_data).digest() def _calc_digest_samples(self) -> bytes: size = self.size with self.path.open("rb") as fp: # Chunk at 25% of the file fp.seek(floor(size * 25 / 100), 0) file_data = fp.read(CHUNK_SIZE) file_hash = hasher(file_data) # Chunk at 60% of the file fp.seek(floor(size * 60 / 100), 0) file_data = fp.read(CHUNK_SIZE) file_hash.update(file_data) # Last chunk of the file fp.seek(-CHUNK_SIZE, 2) file_data = fp.read(CHUNK_SIZE) file_hash.update(file_data) return file_hash.digest() def _read_info(self, field): # print(f"_read_info({field}) for {self}") if field in ("size", "mtime"): stats = self.path.stat() self.size = nonone(stats.st_size, 0) self.mtime = nonone(stats.st_mtime, 0) elif field == "digest_partial": self.digest_partial = filesdb.get(self.path, "digest_partial") if self.digest_partial is None: # If file is smaller than partial requirements just use the full digest if self.size < PARTIAL_OFFSET_SIZE[0] + PARTIAL_OFFSET_SIZE[1]: self.digest_partial = self.digest else: self.digest_partial = self._calc_digest_partial() filesdb.put(self.path, "digest_partial", self.digest_partial) elif field == "digest": self.digest = filesdb.get(self.path, "digest") if self.digest is None: self.digest = self._calc_digest() filesdb.put(self.path, "digest", self.digest) elif field == "digest_samples": size = self.size # Might as well hash such small files entirely. if size <= MIN_FILE_SIZE: self.digest_samples = self.digest return self.digest_samples = filesdb.get(self.path, "digest_samples") if self.digest_samples is None: self.digest_samples = self._calc_digest_samples() filesdb.put(self.path, "digest_samples", self.digest_samples) def _read_all_info(self, attrnames=None): """Cache all possible info. If `attrnames` is not None, caches only attrnames. """ if attrnames is None: attrnames = self.INITIAL_INFO.keys() for attrname in attrnames: getattr(self, attrname) # --- Public @classmethod def can_handle(cls, path): """Returns whether this file wrapper class can handle ``path``.""" return not path.is_symlink() and path.is_file() def exists(self) -> bool: """Safely check if the underlying file exists, treat error as non-existent""" try: return self.path.exists() except OSError as ex: logging.warning(f"Checking {self.path} raised: {ex}") return False def rename(self, newname): if newname == self.name: return destpath = self.path.parent.joinpath(newname) if destpath.exists(): raise AlreadyExistsError(newname, self.path.parent) try: self.path.rename(destpath) except OSError: raise OperationError(self) if not destpath.exists(): raise OperationError(self) self.path = destpath def get_display_info(self, group, delta): """Returns a display-ready dict of dupe's data.""" raise NotImplementedError() # --- Properties @property def extension(self): return get_file_ext(self.name) @property def name(self): return self.path.name @property def folder_path(self): return self.path.parent class Folder(File): """A wrapper around a folder path. It has the size/digest info of a File, but its value is the sum of its subitems. """ __slots__ = File.__slots__ + ("_subfolders",) def __init__(self, path): File.__init__(self, path) self.size = NOT_SET self._subfolders = None def _all_items(self): folders = self.subfolders files = get_files(self.path) return folders + files def _read_info(self, field): # print(f"_read_info({field}) for Folder {self}") if field in {"size", "mtime"}: size = sum((f.size for f in self._all_items()), 0) self.size = size stats = self.path.stat() self.mtime = nonone(stats.st_mtime, 0) elif field in {"digest", "digest_partial", "digest_samples"}: # What's sensitive here is that we must make sure that subfiles' # digest are always added up in the same order, but we also want a # different digest if a file gets moved in a different subdirectory. def get_dir_digest_concat(): items = self._all_items() items.sort(key=lambda f: f.path) digests = [getattr(f, field) for f in items] return b"".join(digests) digest = hasher(get_dir_digest_concat()).digest() setattr(self, field, digest) @property def subfolders(self): if self._subfolders is None: with os.scandir(self.path) as iter: subfolders = [p for p in iter if not p.is_symlink() and p.is_dir()] self._subfolders = [self.__class__(p) for p in subfolders] return self._subfolders @classmethod def can_handle(cls, path): return not path.is_symlink() and path.is_dir() def get_file(path, fileclasses=[File]): """Wraps ``path`` around its appropriate :class:`File` class. Whether a class is "appropriate" is decided by :meth:`File.can_handle` :param Path path: path to wrap :param fileclasses: List of candidate :class:`File` classes """ for fileclass in fileclasses: if fileclass.can_handle(path): return fileclass(path) def get_files(path, fileclasses=[File]): """Returns a list of :class:`File` for each file contained in ``path``. :param Path path: path to scan :param fileclasses: List of candidate :class:`File` classes """ assert all(issubclass(fileclass, File) for fileclass in fileclasses) try: result = [] with os.scandir(path) as iter: for item in iter: file = get_file(item, fileclasses=fileclasses) if file is not None: result.append(file) return result except OSError: raise InvalidPath(path)
15,932
Python
.py
366
34.046448
116
0.602906
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,121
exclude.py
arsenetar_dupeguru/core/exclude.py
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from core.markable import Markable from xml.etree import ElementTree as ET # TODO: perhaps use regex module for better Unicode support? https://pypi.org/project/regex/ # also https://pypi.org/project/re2/ # TODO update the Result list with newly added regexes if possible import re from os import sep import logging import functools from hscommon.util import FileOrPath from hscommon.plat import ISWINDOWS import time default_regexes = [ r"^thumbs\.db$", # Obsolete after WindowsXP r"^desktop\.ini$", # Windows metadata r"^\.DS_Store$", # MacOS metadata r"^\.Trash\-.*", # Linux trash directories r"^\$Recycle\.Bin$", # Windows r"^\..*", # Hidden files on Unix-like ] # These are too broad forbidden_regexes = [r".*", r"\/.*", r".*\/.*", r".*\\\\.*", r".*\..*"] def timer(func): @functools.wraps(func) def wrapper_timer(*args): start = time.perf_counter_ns() value = func(*args) end = time.perf_counter_ns() print(f"DEBUG: func {func.__name__!r} took {end - start} ns.") return value return wrapper_timer def memoize(func): func.cache = dict() @functools.wraps(func) def _memoize(*args): if args not in func.cache: func.cache[args] = func(*args) return func.cache[args] return _memoize class AlreadyThereException(Exception): """Expression already in the list""" def __init__(self, arg="Expression is already in excluded list."): super().__init__(arg) class ExcludeList(Markable): """A list of lists holding regular expression strings and the compiled re.Pattern""" # Used to filter out directories and files that we would rather avoid scanning. # The list() class allows us to preserve item order without too much hassle. # The downside is we have to compare strings every time we look for an item in the list # since we use regex strings as keys. # If _use_union is True, the compiled regexes will be combined into one single # Pattern instead of separate Patterns which may or may not give better # performance compared to looping through each Pattern individually. # ---Override def __init__(self, union_regex=True): Markable.__init__(self) self._use_union = union_regex # list([str regex, bool iscompilable, re.error exception, Pattern compiled], ...) self._excluded = [] self._excluded_compiled = set() self._dirty = True def __iter__(self): """Iterate in order.""" for item in self._excluded: regex = item[0] yield self.is_marked(regex), regex def __contains__(self, item): return self.has_entry(item) def __len__(self): """Returns the total number of regexes regardless of mark status.""" return len(self._excluded) def __getitem__(self, key): """Returns the list item corresponding to key.""" for item in self._excluded: if item[0] == key: return item raise KeyError(f"Key {key} is not in exclusion list.") def __setitem__(self, key, value): # TODO if necessary pass def __delitem__(self, key): # TODO if necessary pass def get_compiled(self, key): """Returns the (precompiled) Pattern for key""" return self.__getitem__(key)[3] def is_markable(self, regex): return self._is_markable(regex) def _is_markable(self, regex): """Return the cached result of "compilable" property""" for item in self._excluded: if item[0] == regex: return item[1] return False # should not be necessary, the regex SHOULD be in there def _did_mark(self, regex): self._add_compiled(regex) def _did_unmark(self, regex): self._remove_compiled(regex) def _add_compiled(self, regex): self._dirty = True if self._use_union: return for item in self._excluded: # FIXME probably faster to just rebuild the set from the compiled instead of comparing strings if item[0] == regex: # no need to test if already present since it's a set() self._excluded_compiled.add(item[3]) break def _remove_compiled(self, regex): self._dirty = True if self._use_union: return for item in self._excluded_compiled: if regex in item.pattern: self._excluded_compiled.remove(item) break # @timer @memoize def _do_compile(self, expr): return re.compile(expr) # @timer # @memoize # probably not worth memoizing this one if we memoize the above def compile_re(self, regex): compiled = None try: compiled = self._do_compile(regex) except Exception as e: return False, e, compiled return True, None, compiled def error(self, regex): """Return the compilation error Exception for regex. It should have a "msg" attr.""" for item in self._excluded: if item[0] == regex: return item[2] def build_compiled_caches(self, union=False): if not union: self._cached_compiled_files = [x for x in self._excluded_compiled if not has_sep(x.pattern)] self._cached_compiled_paths = [x for x in self._excluded_compiled if has_sep(x.pattern)] self._dirty = False return marked_count = [x for marked, x in self if marked] # If there is no item, the compiled Pattern will be '' and match everything! if not marked_count: self._cached_compiled_union_all = [] self._cached_compiled_union_files = [] self._cached_compiled_union_paths = [] else: # HACK returned as a tuple to get a free iterator and keep interface # the same regardless of whether the client asked for union or not self._cached_compiled_union_all = (re.compile("|".join(marked_count)),) files_marked = [x for x in marked_count if not has_sep(x)] if not files_marked: self._cached_compiled_union_files = tuple() else: self._cached_compiled_union_files = (re.compile("|".join(files_marked)),) paths_marked = [x for x in marked_count if has_sep(x)] if not paths_marked: self._cached_compiled_union_paths = tuple() else: self._cached_compiled_union_paths = (re.compile("|".join(paths_marked)),) self._dirty = False @property def compiled(self): """Should be used by other classes to retrieve the up-to-date list of patterns.""" if self._use_union: if self._dirty: self.build_compiled_caches(self._use_union) return self._cached_compiled_union_all return self._excluded_compiled @property def compiled_files(self): """When matching against filenames only, we probably won't be seeing any directory separator, so we filter out regexes with os.sep in them. The interface should be expected to be a generator, even if it returns only one item (one Pattern in the union case).""" if self._dirty: self.build_compiled_caches(self._use_union) return self._cached_compiled_union_files if self._use_union else self._cached_compiled_files @property def compiled_paths(self): """Returns patterns with only separators in them, for more precise filtering.""" if self._dirty: self.build_compiled_caches(self._use_union) return self._cached_compiled_union_paths if self._use_union else self._cached_compiled_paths # ---Public def add(self, regex, forced=False): """This interface should throw exceptions if there is an error during regex compilation""" if self.has_entry(regex): # This exception should never be ignored raise AlreadyThereException() if regex in forbidden_regexes: raise ValueError("Forbidden (dangerous) expression.") iscompilable, exception, compiled = self.compile_re(regex) if not iscompilable and not forced: # This exception can be ignored, but taken into account # to avoid adding to compiled set raise exception else: self._do_add(regex, iscompilable, exception, compiled) def _do_add(self, regex, iscompilable, exception, compiled): # We need to insert at the top self._excluded.insert(0, [regex, iscompilable, exception, compiled]) @property def marked_count(self): """Returns the number of marked regexes only.""" return len([x for marked, x in self if marked]) def has_entry(self, regex): for item in self._excluded: if regex == item[0]: return True return False def is_excluded(self, dirname, filename): """Return True if the file or the absolute path to file is supposed to be filtered out, False otherwise.""" matched = False for expr in self.compiled_files: if expr.fullmatch(filename): matched = True break if not matched: for expr in self.compiled_paths: if expr.fullmatch(dirname + sep + filename): matched = True break return matched def remove(self, regex): for item in self._excluded: if item[0] == regex: self._excluded.remove(item) self._remove_compiled(regex) def rename(self, regex, newregex): if regex == newregex: return found = False was_marked = False is_compilable = False for item in self._excluded: if item[0] == regex: found = True was_marked = self.is_marked(regex) is_compilable, exception, compiled = self.compile_re(newregex) # We overwrite the found entry self._excluded[self._excluded.index(item)] = [newregex, is_compilable, exception, compiled] self._remove_compiled(regex) break if not found: return if is_compilable: self._add_compiled(newregex) if was_marked: # Not marked by default when added, add it back self.mark(newregex) # def change_index(self, regex, new_index): # """Internal list must be a list, not dict.""" # item = self._excluded.pop(regex) # self._excluded.insert(new_index, item) def restore_defaults(self): for _, regex in self: if regex not in default_regexes: self.unmark(regex) for default_regex in default_regexes: if not self.has_entry(default_regex): self.add(default_regex) self.mark(default_regex) def load_from_xml(self, infile): """Loads the ignore list from a XML created with save_to_xml. infile can be a file object or a filename. """ try: root = ET.parse(infile).getroot() except Exception as e: logging.warning(f"Error while loading {infile}: {e}") self.restore_defaults() return e marked = set() exclude_elems = (e for e in root if e.tag == "exclude") for exclude_item in exclude_elems: regex_string = exclude_item.get("regex") if not regex_string: continue try: # "forced" avoids compilation exceptions and adds anyway self.add(regex_string, forced=True) except AlreadyThereException: logging.error( f'Regex "{regex_string}" \ loaded from XML was already present in the list.' ) continue if exclude_item.get("marked") == "y": marked.add(regex_string) for item in marked: self.mark(item) def save_to_xml(self, outfile): """Create a XML file that can be used by load_from_xml. outfile can be a file object or a filename.""" root = ET.Element("exclude_list") # reversed in order to keep order of entries when reloading from xml later for item in reversed(self._excluded): exclude_node = ET.SubElement(root, "exclude") exclude_node.set("regex", str(item[0])) exclude_node.set("marked", ("y" if self.is_marked(item[0]) else "n")) tree = ET.ElementTree(root) with FileOrPath(outfile, "wb") as fp: tree.write(fp, encoding="utf-8") class ExcludeDict(ExcludeList): """Exclusion list holding a set of regular expressions as keys, the compiled Pattern, compilation error and compilable boolean as values.""" # Implemntation around a dictionary instead of a list, which implies # to keep the index of each string-key as its sub-element and keep it updated # whenever insert/remove is done. def __init__(self, union_regex=False): Markable.__init__(self) self._use_union = union_regex # { "regex string": # { # "index": int, # "compilable": bool, # "error": str, # "compiled": Pattern or None # } # } self._excluded = {} self._excluded_compiled = set() self._dirty = True def __iter__(self): """Iterate in order.""" for regex in ordered_keys(self._excluded): yield self.is_marked(regex), regex def __getitem__(self, key): """Returns the dict item correponding to key""" return self._excluded.__getitem__(key) def get_compiled(self, key): """Returns the compiled item for key""" return self.__getitem__(key).get("compiled") def is_markable(self, regex): return self._is_markable(regex) def _is_markable(self, regex): """Return the cached result of "compilable" property""" exists = self._excluded.get(regex) if exists: return exists.get("compilable") return False def _add_compiled(self, regex): self._dirty = True if self._use_union: return try: self._excluded_compiled.add(self._excluded.get(regex).get("compiled")) except Exception as e: logging.error(f"Exception while adding regex {regex} to compiled set: {e}") return def is_compilable(self, regex): """Returns the cached "compilable" value""" return self._excluded[regex]["compilable"] def error(self, regex): """Return the compilation error message for regex string""" return self._excluded.get(regex).get("error") # ---Public def _do_add(self, regex, iscompilable, exception, compiled): # We always insert at the top, so index should be 0 # and other indices should be pushed by one for value in self._excluded.values(): value["index"] += 1 self._excluded[regex] = {"index": 0, "compilable": iscompilable, "error": exception, "compiled": compiled} def has_entry(self, regex): if regex in self._excluded.keys(): return True return False def remove(self, regex): old_value = self._excluded.pop(regex) # Bring down all indices which where above it index = old_value["index"] if index == len(self._excluded) - 1: # we start at 0... # Old index was at the end, no need to update other indices self._remove_compiled(regex) return for value in self._excluded.values(): if value.get("index") > old_value["index"]: value["index"] -= 1 self._remove_compiled(regex) def rename(self, regex, newregex): if regex == newregex or regex not in self._excluded.keys(): return was_marked = self.is_marked(regex) previous = self._excluded.pop(regex) iscompilable, error, compiled = self.compile_re(newregex) self._excluded[newregex] = { "index": previous.get("index"), "compilable": iscompilable, "error": error, "compiled": compiled, } self._remove_compiled(regex) if iscompilable: self._add_compiled(newregex) if was_marked: self.mark(newregex) def save_to_xml(self, outfile): """Create a XML file that can be used by load_from_xml. outfile can be a file object or a filename. """ root = ET.Element("exclude_list") # reversed in order to keep order of entries when reloading from xml later reversed_list = [] for key in ordered_keys(self._excluded): reversed_list.append(key) for item in reversed(reversed_list): exclude_node = ET.SubElement(root, "exclude") exclude_node.set("regex", str(item)) exclude_node.set("marked", ("y" if self.is_marked(item) else "n")) tree = ET.ElementTree(root) with FileOrPath(outfile, "wb") as fp: tree.write(fp, encoding="utf-8") def ordered_keys(_dict): """Returns an iterator over the keys of dictionary sorted by "index" key""" if not len(_dict): return list_of_items = [] for item in _dict.items(): list_of_items.append(item) list_of_items.sort(key=lambda x: x[1].get("index")) for item in list_of_items: yield item[0] if ISWINDOWS: def has_sep(regexp): return "\\" + sep in regexp else: def has_sep(regexp): return sep in regexp
18,256
Python
.py
434
32.670507
114
0.604238
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,122
export.py
arsenetar_dupeguru/core/export.py
# Created By: Virgil Dupras # Created On: 2006/09/16 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import os.path as op from tempfile import mkdtemp import csv # Yes, this is a very low-tech solution, but at least it doesn't have all these annoying dependency # and resource problems. MAIN_TEMPLATE = """ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <title>dupeGuru Results</title> <style type="text/css"> BODY { background-color:white; } BODY,A,P,UL,TABLE,TR,TD { font-family:Tahoma,Arial,sans-serif; font-size:10pt; color: #4477AA; } TABLE { background-color: #225588; margin-left: auto; margin-right: auto; width: 90%; } TR { background-color: white; } TH { font-weight: bold; color: black; background-color: #C8D6E5; } TH TD { color:black; } TD { padding-left: 2pt; } TD.rightelem { text-align:right; /*padding-left:0pt;*/ padding-right: 2pt; width: 17%; } TD.indented { padding-left: 12pt; } H1 { font-family:&quot;Courier New&quot;,monospace; color:#6699CC; font-size:18pt; color:#6da500; border-color: #70A0CF; border-width: 1pt; border-style: solid; margin-top: 16pt; margin-left: 5%; margin-right: 5%; padding-top: 2pt; padding-bottom:2pt; text-align: center; } </style> </head> <body> <h1>dupeGuru Results</h1> <table> <tr>$colheaders</tr> $rows </table> </body> </html> """ COLHEADERS_TEMPLATE = "<th>{name}</th>" ROW_TEMPLATE = """ <tr> <td class="{indented}">{filename}</td>{cells} </tr> """ CELL_TEMPLATE = """<td>{value}</td>""" def export_to_xhtml(colnames, rows): # a row is a list of values with the first value being a flag indicating if the row should be indented if rows: assert len(rows[0]) == len(colnames) + 1 # + 1 is for the "indented" flag colheaders = "".join(COLHEADERS_TEMPLATE.format(name=name) for name in colnames) rendered_rows = [] previous_group_id = None for row in rows: # [2:] is to remove the indented flag + filename if row[0] != previous_group_id: # We've just changed dupe group, which means that this dupe is a ref. We don't indent it. indented = "" else: indented = "indented" filename = row[1] cells = "".join(CELL_TEMPLATE.format(value=value) for value in row[2:]) rendered_rows.append(ROW_TEMPLATE.format(indented=indented, filename=filename, cells=cells)) previous_group_id = row[0] rendered_rows = "".join(rendered_rows) # The main template can't use format because the css code uses {} content = MAIN_TEMPLATE.replace("$colheaders", colheaders).replace("$rows", rendered_rows) folder = mkdtemp() destpath = op.join(folder, "export.htm") fp = open(destpath, "wt", encoding="utf-8") fp.write(content) fp.close() return destpath def export_to_csv(dest, colnames, rows): writer = csv.writer(open(dest, "wt", encoding="utf-8")) writer.writerow(["Group ID"] + colnames) for row in rows: writer.writerow(row)
3,565
Python
.py
132
23.348485
109
0.668717
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,123
app.py
arsenetar_dupeguru/core/app.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import cProfile import datetime import os import os.path as op import logging import subprocess import re import shutil from pathlib import Path from send2trash import send2trash from hscommon.jobprogress import job from hscommon.notify import Broadcaster from hscommon.conflict import smart_move, smart_copy from hscommon.gui.progress_window import ProgressWindow from hscommon.util import delete_if_empty, first, escape, nonone, allsame from hscommon.trans import tr from hscommon import desktop from core import se, me, pe from core.pe.photo import get_delta_dimensions from core.util import cmp_value, fix_surrogate_encoding from core import directories, results, export, fs, prioritize from core.ignore import IgnoreList from core.exclude import ExcludeDict as ExcludeList from core.scanner import ScanType from core.gui.deletion_options import DeletionOptions from core.gui.details_panel import DetailsPanel from core.gui.directory_tree import DirectoryTree from core.gui.ignore_list_dialog import IgnoreListDialog from core.gui.exclude_list_dialog import ExcludeListDialogCore from core.gui.problem_dialog import ProblemDialog from core.gui.stats_label import StatsLabel HAD_FIRST_LAUNCH_PREFERENCE = "HadFirstLaunch" DEBUG_MODE_PREFERENCE = "DebugMode" MSG_NO_MARKED_DUPES = tr("There are no marked duplicates. Nothing has been done.") MSG_NO_SELECTED_DUPES = tr("There are no selected duplicates. Nothing has been done.") MSG_MANY_FILES_TO_OPEN = tr( "You're about to open many files at once. Depending on what those " "files are opened with, doing so can create quite a mess. Continue?" ) class DestType: DIRECT = 0 RELATIVE = 1 ABSOLUTE = 2 class JobType: SCAN = "job_scan" LOAD = "job_load" MOVE = "job_move" COPY = "job_copy" DELETE = "job_delete" class AppMode: STANDARD = 0 MUSIC = 1 PICTURE = 2 JOBID2TITLE = { JobType.SCAN: tr("Scanning for duplicates"), JobType.LOAD: tr("Loading"), JobType.MOVE: tr("Moving"), JobType.COPY: tr("Copying"), JobType.DELETE: tr("Sending to Trash"), } class DupeGuru(Broadcaster): """Holds everything together. Instantiated once per running application, it holds a reference to every high-level object whose reference needs to be held: :class:`~core.results.Results`, :class:`~core.directories.Directories`, :mod:`core.gui` instances, etc.. It also hosts high level methods and acts as a coordinator for all those elements. This is why some of its methods seem a bit shallow, like for example :meth:`mark_all` and :meth:`remove_duplicates`. These methos are just proxies for a method in :attr:`results`, but they are also followed by a notification call which is very important if we want GUI elements to be correctly notified of a change in the data they're presenting. .. attribute:: directories Instance of :class:`~core.directories.Directories`. It holds the current folder selection. .. attribute:: results Instance of :class:`core.results.Results`. Holds the results of the latest scan. .. attribute:: selected_dupes List of currently selected dupes from our :attr:`results`. Whenever the user changes its selection at the UI level, :attr:`result_table` takes care of updating this attribute, so you can trust that it's always up-to-date. .. attribute:: result_table Instance of :mod:`meta-gui <core.gui>` table listing the results from :attr:`results` """ # --- View interface # get_default(key_name) # set_default(key_name, value) # show_message(msg) # open_url(url) # open_path(path) # reveal_path(path) # ask_yes_no(prompt) --> bool # create_results_window() # show_results_window() # show_problem_dialog() # select_dest_folder(prompt: str) --> str # select_dest_file(prompt: str, ext: str) --> str NAME = PROMPT_NAME = "dupeGuru" def __init__(self, view, portable=False): if view.get_default(DEBUG_MODE_PREFERENCE): logging.getLogger().setLevel(logging.DEBUG) logging.debug("Debug mode enabled") Broadcaster.__init__(self) self.view = view self.appdata = desktop.special_folder_path(desktop.SpecialFolder.APPDATA, portable=portable) if not op.exists(self.appdata): os.makedirs(self.appdata) self.app_mode = AppMode.STANDARD self.discarded_file_count = 0 self.exclude_list = ExcludeList() hash_cache_file = op.join(self.appdata, "hash_cache.db") fs.filesdb.connect(hash_cache_file) self.directories = directories.Directories(self.exclude_list) self.results = results.Results(self) self.ignore_list = IgnoreList() # In addition to "app-level" options, this dictionary also holds options that will be # sent to the scanner. They don't have default values because those defaults values are # defined in the scanner class. self.options = { "escape_filter_regexp": True, "clean_empty_dirs": False, "ignore_hardlink_matches": False, "copymove_dest_type": DestType.RELATIVE, "include_exists_check": True, "rehash_ignore_mtime": False, } self.selected_dupes = [] self.details_panel = DetailsPanel(self) self.directory_tree = DirectoryTree(self) self.problem_dialog = ProblemDialog(self) self.ignore_list_dialog = IgnoreListDialog(self) self.exclude_list_dialog = ExcludeListDialogCore(self) self.stats_label = StatsLabel(self) self.result_table = None self.deletion_options = DeletionOptions() self.progress_window = ProgressWindow(self._job_completed, self._job_error) children = [self.directory_tree, self.stats_label, self.details_panel] for child in children: child.connect() # --- Private def _recreate_result_table(self): if self.result_table is not None: self.result_table.disconnect() if self.app_mode == AppMode.PICTURE: self.result_table = pe.result_table.ResultTable(self) elif self.app_mode == AppMode.MUSIC: self.result_table = me.result_table.ResultTable(self) else: self.result_table = se.result_table.ResultTable(self) self.result_table.connect() self.view.create_results_window() def _get_picture_cache_path(self): cache_name = "cached_pictures.db" return op.join(self.appdata, cache_name) def _get_dupe_sort_key(self, dupe, get_group, key, delta): if self.app_mode in (AppMode.MUSIC, AppMode.PICTURE) and key == "folder_path": dupe_folder_path = getattr(dupe, "display_folder_path", dupe.folder_path) return str(dupe_folder_path).lower() if self.app_mode == AppMode.PICTURE and delta and key == "dimensions": r = cmp_value(dupe, key) ref_value = cmp_value(get_group().ref, key) return get_delta_dimensions(r, ref_value) if key == "marked": return self.results.is_marked(dupe) if key == "percentage": m = get_group().get_match_of(dupe) return m.percentage elif key == "dupe_count": return 0 else: result = cmp_value(dupe, key) if delta: refval = cmp_value(get_group().ref, key) if key in self.result_table.DELTA_COLUMNS: result -= refval else: same = cmp_value(dupe, key) == refval result = (same, result) return result def _get_group_sort_key(self, group, key): if self.app_mode in (AppMode.MUSIC, AppMode.PICTURE) and key == "folder_path": dupe_folder_path = getattr(group.ref, "display_folder_path", group.ref.folder_path) return str(dupe_folder_path).lower() if key == "percentage": return group.percentage if key == "dupe_count": return len(group) if key == "marked": return len([dupe for dupe in group.dupes if self.results.is_marked(dupe)]) return cmp_value(group.ref, key) def _do_delete(self, j, link_deleted, use_hardlinks, direct_deletion): def op(dupe): j.add_progress() return self._do_delete_dupe(dupe, link_deleted, use_hardlinks, direct_deletion) j.start_job(self.results.mark_count) self.results.perform_on_marked(op, True) def _do_delete_dupe(self, dupe, link_deleted, use_hardlinks, direct_deletion): if not dupe.path.exists(): return logging.debug("Sending '%s' to trash", dupe.path) str_path = str(dupe.path) if direct_deletion: if op.isdir(str_path): shutil.rmtree(str_path) else: os.remove(str_path) else: send2trash(str_path) # Raises OSError when there's a problem if link_deleted: group = self.results.get_group_of_duplicate(dupe) ref = group.ref linkfunc = os.link if use_hardlinks else os.symlink linkfunc(str(ref.path), str_path) self.clean_empty_dirs(dupe.path.parent) def _create_file(self, path): # We add fs.Folder to fileclasses in case the file we're loading contains folder paths. return fs.get_file(path, self.fileclasses + [se.fs.Folder]) def _get_file(self, str_path): path = Path(str_path) f = self._create_file(path) if f is None: return None try: f._read_all_info(attrnames=self.METADATA_TO_READ) return f except OSError: return None def _get_export_data(self): columns = [col for col in self.result_table._columns.ordered_columns if col.visible and col.name != "marked"] colnames = [col.display for col in columns] rows = [] for group_id, group in enumerate(self.results.groups): for dupe in group: data = self.get_display_info(dupe, group) row = [fix_surrogate_encoding(data[col.name]) for col in columns] row.insert(0, group_id) rows.append(row) return colnames, rows def _results_changed(self): self.selected_dupes = [d for d in self.selected_dupes if self.results.get_group_of_duplicate(d) is not None] self.notify("results_changed") def _start_job(self, jobid, func, args=()): title = JOBID2TITLE[jobid] try: self.progress_window.run(jobid, title, func, args=args) except job.JobInProgressError: msg = tr( "A previous action is still hanging in there. You can't start a new one yet. Wait " "a few seconds, then try again." ) self.view.show_message(msg) def _job_completed(self, jobid): if jobid == JobType.SCAN: self._results_changed() fs.filesdb.commit() if not self.results.groups: self.view.show_message(tr("No duplicates found.")) else: self.view.show_results_window() if jobid in {JobType.MOVE, JobType.DELETE}: self._results_changed() if jobid == JobType.LOAD: self._recreate_result_table() self._results_changed() self.view.show_results_window() if jobid in {JobType.COPY, JobType.MOVE, JobType.DELETE}: if self.results.problems: self.problem_dialog.refresh() self.view.show_problem_dialog() else: if jobid == JobType.COPY: msg = tr("All marked files were copied successfully.") elif jobid == JobType.MOVE: msg = tr("All marked files were moved successfully.") elif jobid == JobType.DELETE and self.deletion_options.direct: msg = tr("All marked files were deleted successfully.") else: msg = tr("All marked files were successfully sent to Trash.") self.view.show_message(msg) def _job_error(self, jobid, err): if jobid == JobType.LOAD: msg = tr("Could not load file: {}").format(err) self.view.show_message(msg) return False else: raise err @staticmethod def _remove_hardlink_dupes(files): seen_inodes = set() result = [] for file in files: try: inode = file.path.stat().st_ino except OSError: # The file was probably deleted or something continue if inode not in seen_inodes: seen_inodes.add(inode) result.append(file) return result def _select_dupes(self, dupes): if dupes == self.selected_dupes: return self.selected_dupes = dupes self.notify("dupes_selected") # --- Protected def _get_fileclasses(self): if self.app_mode == AppMode.PICTURE: return [pe.photo.PLAT_SPECIFIC_PHOTO_CLASS] elif self.app_mode == AppMode.MUSIC: return [me.fs.MusicFile] else: return [se.fs.File] def _prioritization_categories(self): if self.app_mode == AppMode.PICTURE: return pe.prioritize.all_categories() elif self.app_mode == AppMode.MUSIC: return me.prioritize.all_categories() else: return prioritize.all_categories() # --- Public def add_directory(self, d): """Adds folder ``d`` to :attr:`directories`. Shows an error message dialog if something bad happens. :param str d: path of folder to add """ try: self.directories.add_path(Path(d)) self.notify("directories_changed") except directories.AlreadyThereError: self.view.show_message(tr("'{}' already is in the list.").format(d)) except directories.InvalidPathError: self.view.show_message(tr("'{}' does not exist.").format(d)) def add_selected_to_ignore_list(self): """Adds :attr:`selected_dupes` to :attr:`ignore_list`.""" dupes = self.without_ref(self.selected_dupes) if not dupes: self.view.show_message(MSG_NO_SELECTED_DUPES) return msg = tr("All selected %d matches are going to be ignored in all subsequent scans. Continue?") if not self.view.ask_yes_no(msg % len(dupes)): return for dupe in dupes: g = self.results.get_group_of_duplicate(dupe) for other in g: if other is not dupe: self.ignore_list.ignore(str(other.path), str(dupe.path)) self.remove_duplicates(dupes) self.ignore_list_dialog.refresh() def apply_filter(self, result_filter): """Apply a filter ``filter`` to the results so that it shows only dupe groups that match it. :param str filter: filter to apply """ self.results.apply_filter(None) if self.options["escape_filter_regexp"]: result_filter = escape(result_filter, set("()[]\\.|+?^")) result_filter = escape(result_filter, "*", ".") self.results.apply_filter(result_filter) self._results_changed() def clean_empty_dirs(self, path): if self.options["clean_empty_dirs"]: while delete_if_empty(path, [".DS_Store"]): path = path.parent def clear_picture_cache(self): try: os.remove(self._get_picture_cache_path()) except FileNotFoundError: pass # we don't care def clear_hash_cache(self): fs.filesdb.clear() def copy_or_move(self, dupe, copy: bool, destination: str, dest_type: DestType): source_path = dupe.path location_path = first(p for p in self.directories if p in dupe.path.parents) dest_path = Path(destination) if dest_type in {DestType.RELATIVE, DestType.ABSOLUTE}: # no filename, no windows drive letter source_base = source_path.relative_to(source_path.anchor).parent if dest_type == DestType.RELATIVE: source_base = source_base.relative_to(location_path.relative_to(location_path.anchor)) dest_path = dest_path.joinpath(source_base) if not dest_path.exists(): dest_path.mkdir(parents=True) # Add filename to dest_path. For file move/copy, it's not required, but for folders, yes. dest_path = dest_path.joinpath(source_path.name) logging.debug("Copy/Move operation from '%s' to '%s'", source_path, dest_path) # Raises an EnvironmentError if there's a problem if copy: smart_copy(source_path, dest_path) else: smart_move(source_path, dest_path) self.clean_empty_dirs(source_path.parent) def copy_or_move_marked(self, copy): """Start an async move (or copy) job on marked duplicates. :param bool copy: If True, duplicates will be copied instead of moved """ def do(j): def op(dupe): j.add_progress() self.copy_or_move(dupe, copy, destination, desttype) j.start_job(self.results.mark_count) self.results.perform_on_marked(op, not copy) if not self.results.mark_count: self.view.show_message(MSG_NO_MARKED_DUPES) return destination = self.view.select_dest_folder( tr("Select a directory to copy marked files to") if copy else tr("Select a directory to move marked files to") ) if destination: desttype = self.options["copymove_dest_type"] jobid = JobType.COPY if copy else JobType.MOVE self._start_job(jobid, do) def delete_marked(self): """Start an async job to send marked duplicates to the trash.""" if not self.results.mark_count: self.view.show_message(MSG_NO_MARKED_DUPES) return if not self.deletion_options.show(self.results.mark_count): return args = [ self.deletion_options.link_deleted, self.deletion_options.use_hardlinks, self.deletion_options.direct, ] logging.debug("Starting deletion job with args %r", args) self._start_job(JobType.DELETE, self._do_delete, args=args) def export_to_xhtml(self): """Export current results to XHTML. The configuration of the :attr:`result_table` (columns order and visibility) is used to determine how the data is presented in the export. In other words, the exported table in the resulting XHTML will look just like the results table. """ colnames, rows = self._get_export_data() export_path = export.export_to_xhtml(colnames, rows) desktop.open_path(export_path) def export_to_csv(self): """Export current results to CSV. The columns and their order in the resulting CSV file is determined in the same way as in :meth:`export_to_xhtml`. """ dest_file = self.view.select_dest_file(tr("Select a destination for your exported CSV"), "csv") if dest_file: colnames, rows = self._get_export_data() try: export.export_to_csv(dest_file, colnames, rows) except OSError as e: self.view.show_message(tr("Couldn't write to file: {}").format(str(e))) def get_display_info(self, dupe, group, delta=False): def empty_data(): return {c.name: "---" for c in self.result_table.COLUMNS[1:]} if (dupe is None) or (group is None): return empty_data() try: return dupe.get_display_info(group, delta) except Exception as e: logging.warning("Exception (type: %s) on GetDisplayInfo for %s: %s", type(e), str(dupe.path), str(e)) return empty_data() def invoke_custom_command(self): """Calls command in ``CustomCommand`` pref with ``%d`` and ``%r`` placeholders replaced. Using the current selection, ``%d`` is replaced with the currently selected dupe and ``%r`` is replaced with that dupe's ref file. If there's no selection, the command is not invoked. If the dupe is a ref, ``%d`` and ``%r`` will be the same. """ cmd = self.view.get_default("CustomCommand") if not cmd: msg = tr("You have no custom command set up. Set it up in your preferences.") self.view.show_message(msg) return if not self.selected_dupes: return dupes = self.selected_dupes refs = [self.results.get_group_of_duplicate(dupe).ref for dupe in dupes] for dupe, ref in zip(dupes, refs): dupe_cmd = cmd.replace("%d", str(dupe.path)) dupe_cmd = dupe_cmd.replace("%r", str(ref.path)) match = re.match(r'"([^"]+)"(.*)', dupe_cmd) if match is not None: # This code here is because subprocess. Popen doesn't seem to accept, under Windows, # executable paths with spaces in it, *even* when they're enclosed in "". So this is # a workaround to make the damn thing work. exepath, args = match.groups() path, exename = op.split(exepath) p = subprocess.Popen( exename + args, shell=True, cwd=path, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) output = p.stdout.read() logging.info("Custom command %s %s: %s", exename, args, output) else: p = subprocess.Popen(dupe_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = p.stdout.read() logging.info("Custom command %s: %s", dupe_cmd, output) def load(self): """Load directory selection and ignore list from files in appdata. This method is called during startup so that directory selection and ignore list, which is persistent data, is the same as when the last session was closed (when :meth:`save` was called). """ self.directories.load_from_file(op.join(self.appdata, "last_directories.xml")) self.notify("directories_changed") p = op.join(self.appdata, "ignore_list.xml") self.ignore_list.load_from_xml(p) self.ignore_list_dialog.refresh() p = op.join(self.appdata, "exclude_list.xml") self.exclude_list.load_from_xml(p) self.exclude_list_dialog.refresh() def load_directories(self, filepath): # Clear out previous entries self.directories.__init__() self.directories.load_from_file(filepath) self.notify("directories_changed") def load_from(self, filename): """Start an async job to load results from ``filename``. :param str filename: path of the XML file (created with :meth:`save_as`) to load """ def do(j): self.results.load_from_xml(filename, self._get_file, j) self._start_job(JobType.LOAD, do) def make_selected_reference(self): """Promote :attr:`selected_dupes` to reference position within their respective groups. Each selected dupe will become the :attr:`~core.engine.Group.ref` of its group. If there's more than one dupe selected for the same group, only the first (in the order currently shown in :attr:`result_table`) dupe will be promoted. """ dupes = self.without_ref(self.selected_dupes) changed_groups = set() for dupe in dupes: g = self.results.get_group_of_duplicate(dupe) if g not in changed_groups and self.results.make_ref(dupe): changed_groups.add(g) # It's not always obvious to users what this action does, so to make it a bit clearer, # we change our selection to the ref of all changed groups. However, we also want to keep # the files that were ref before and weren't changed by the action. In effect, what this # does is that we keep our old selection, but remove all non-ref dupes from it. # If no group was changed, however, we don't touch the selection. if not self.result_table.power_marker: if changed_groups: self.selected_dupes = [ d for d in self.selected_dupes if self.results.get_group_of_duplicate(d).ref is d ] self.notify("results_changed") else: # If we're in "Dupes Only" mode (previously called Power Marker), things are a bit # different. The refs are not shown in the table, and if our operation is successful, # this means that there's no way to follow our dupe selection. Then, the best thing to # do is to keep our selection index-wise (different dupe selection, but same index # selection). self.notify("results_changed_but_keep_selection") def mark_all(self): """Set all dupes in the results as marked.""" self.results.mark_all() self.notify("marking_changed") def mark_none(self): """Set all dupes in the results as unmarked.""" self.results.mark_none() self.notify("marking_changed") def mark_invert(self): """Invert the marked state of all dupes in the results.""" self.results.mark_invert() self.notify("marking_changed") def mark_dupe(self, dupe, marked): """Change marked status of ``dupe``. :param dupe: dupe to mark/unmark :type dupe: :class:`~core.fs.File` :param bool marked: True = mark, False = unmark """ if marked: self.results.mark(dupe) else: self.results.unmark(dupe) self.notify("marking_changed") def open_selected(self): """Open :attr:`selected_dupes` with their associated application.""" if len(self.selected_dupes) > 10 and not self.view.ask_yes_no(MSG_MANY_FILES_TO_OPEN): return for dupe in self.selected_dupes: desktop.open_path(dupe.path) def purge_ignore_list(self): """Remove files that don't exist from :attr:`ignore_list`.""" self.ignore_list.filter(lambda f, s: op.exists(f) and op.exists(s)) self.ignore_list_dialog.refresh() def remove_directories(self, indexes): """Remove root directories at ``indexes`` from :attr:`directories`. :param indexes: Indexes of the directories to remove. :type indexes: list of int """ try: indexes = sorted(indexes, reverse=True) for index in indexes: del self.directories[index] self.notify("directories_changed") except IndexError: pass def remove_duplicates(self, duplicates): """Remove ``duplicates`` from :attr:`results`. Calls :meth:`~core.results.Results.remove_duplicates` and send appropriate notifications. :param duplicates: duplicates to remove. :type duplicates: list of :class:`~core.fs.File` """ self.results.remove_duplicates(self.without_ref(duplicates)) self.notify("results_changed_but_keep_selection") def remove_marked(self): """Removed marked duplicates from the results (without touching the files themselves).""" if not self.results.mark_count: self.view.show_message(MSG_NO_MARKED_DUPES) return msg = tr("You are about to remove %d files from results. Continue?") if not self.view.ask_yes_no(msg % self.results.mark_count): return self.results.perform_on_marked(lambda x: None, True) self._results_changed() def remove_selected(self): """Removed :attr:`selected_dupes` from the results (without touching the files themselves).""" dupes = self.without_ref(self.selected_dupes) if not dupes: self.view.show_message(MSG_NO_SELECTED_DUPES) return msg = tr("You are about to remove %d files from results. Continue?") if not self.view.ask_yes_no(msg % len(dupes)): return self.remove_duplicates(dupes) def rename_selected(self, newname): """Renames the selected dupes's file to ``newname``. If there's more than one selected dupes, the first one is used. :param str newname: The filename to rename the dupe's file to. """ try: d = self.selected_dupes[0] d.rename(newname) return True except (IndexError, fs.FSError) as e: logging.warning("dupeGuru Warning: %s" % str(e)) return False def reprioritize_groups(self, sort_key): """Sort dupes in each group (in :attr:`results`) according to ``sort_key``. Called by the re-prioritize dialog. Calls :meth:`~core.engine.Group.prioritize` and, once the sorting is done, show a message that confirms the action. :param sort_key: The key being sent to :meth:`~core.engine.Group.prioritize` :type sort_key: f(dupe) """ count = 0 for group in self.results.groups: if group.prioritize(key_func=sort_key): count += 1 if count: self.results.refresh_required = True self._results_changed() msg = tr("{} duplicate groups were changed by the re-prioritization.").format(count) self.view.show_message(msg) def reveal_selected(self): if self.selected_dupes: desktop.reveal_path(self.selected_dupes[0].path) def save(self): if not op.exists(self.appdata): os.makedirs(self.appdata) self.directories.save_to_file(op.join(self.appdata, "last_directories.xml")) p = op.join(self.appdata, "ignore_list.xml") self.ignore_list.save_to_xml(p) p = op.join(self.appdata, "exclude_list.xml") self.exclude_list.save_to_xml(p) self.notify("save_session") def close(self): fs.filesdb.close() def save_as(self, filename): """Save results in ``filename``. :param str filename: path of the file to save results (as XML) to. """ try: self.results.save_to_xml(filename) except OSError as e: self.view.show_message(tr("Couldn't write to file: {}").format(str(e))) def save_directories_as(self, filename): """Save directories in ``filename``. :param str filename: path of the file to save directories (as XML) to. """ try: self.directories.save_to_file(filename) except OSError as e: self.view.show_message(tr("Couldn't write to file: {}").format(str(e))) def start_scanning(self, profile_scan=False): """Starts an async job to scan for duplicates. Scans folders selected in :attr:`directories` and put the results in :attr:`results` """ scanner = self.SCANNER_CLASS() fs.filesdb.ignore_mtime = self.options["rehash_ignore_mtime"] is True if not self.directories.has_any_file(): self.view.show_message(tr("The selected directories contain no scannable file.")) return # Send relevant options down to the scanner instance for k, v in self.options.items(): if hasattr(scanner, k): setattr(scanner, k, v) if self.app_mode == AppMode.PICTURE: scanner.cache_path = self._get_picture_cache_path() self.results.groups = [] self._recreate_result_table() self._results_changed() def do(j): if profile_scan: pr = cProfile.Profile() pr.enable() j.set_progress(0, tr("Collecting files to scan")) if scanner.scan_type == ScanType.FOLDERS: files = list(self.directories.get_folders(folderclass=se.fs.Folder, j=j)) else: files = list(self.directories.get_files(fileclasses=self.fileclasses, j=j)) if self.options["ignore_hardlink_matches"]: files = self._remove_hardlink_dupes(files) logging.info("Scanning %d files" % len(files)) self.results.groups = scanner.get_dupe_groups(files, self.ignore_list, j) self.discarded_file_count = scanner.discarded_file_count if profile_scan: pr.disable() pr.dump_stats(op.join(self.appdata, f"{datetime.datetime.now():%Y-%m-%d_%H-%M-%S}.profile")) self._start_job(JobType.SCAN, do) def toggle_selected_mark_state(self): selected = self.without_ref(self.selected_dupes) if not selected: return if allsame(self.results.is_marked(d) for d in selected): markfunc = self.results.mark_toggle else: markfunc = self.results.mark for dupe in selected: markfunc(dupe) self.notify("marking_changed") def without_ref(self, dupes): """Returns ``dupes`` with all reference elements removed.""" return [dupe for dupe in dupes if self.results.get_group_of_duplicate(dupe).ref is not dupe] def get_default(self, key, fallback_value=None): result = nonone(self.view.get_default(key), fallback_value) if fallback_value is not None and not isinstance(result, type(fallback_value)): # we don't want to end up with garbage values from the prefs try: result = type(fallback_value)(result) except Exception: result = fallback_value return result def set_default(self, key, value): self.view.set_default(key, value) # --- Properties @property def stat_line(self): result = self.results.stat_line if self.discarded_file_count: result = tr("%s (%d discarded)") % (result, self.discarded_file_count) return result @property def fileclasses(self): return self._get_fileclasses() @property def SCANNER_CLASS(self): if self.app_mode == AppMode.PICTURE: return pe.scanner.ScannerPE elif self.app_mode == AppMode.MUSIC: return me.scanner.ScannerME else: return se.scanner.ScannerSE @property def METADATA_TO_READ(self): if self.app_mode == AppMode.PICTURE: return ["size", "mtime", "dimensions", "exif_timestamp"] elif self.app_mode == AppMode.MUSIC: return [ "size", "mtime", "duration", "bitrate", "samplerate", "title", "artist", "album", "genre", "year", "track", "comment", ] else: return ["size", "mtime"]
35,740
Python
.py
781
35.857875
117
0.620074
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,124
results.py
arsenetar_dupeguru/core/results.py
# Created By: Virgil Dupras # Created On: 2006/02/23 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import logging import re import os import os.path as op from errno import EISDIR, EACCES from xml.etree import ElementTree as ET from hscommon.jobprogress.job import nulljob from hscommon.conflict import get_conflicted_name from hscommon.util import flatten, nonone, FileOrPath, format_size from hscommon.trans import tr from core import engine from core.markable import Markable class Results(Markable): """Manages a collection of duplicate :class:`~core.engine.Group`. This class takes care or marking, sorting and filtering duplicate groups. .. attribute:: groups The list of :class:`~core.engine.Group` contained managed by this instance. .. attribute:: dupes A list of all duplicates (:class:`~core.fs.File` instances), without ref, contained in the currently managed :attr:`groups`. """ # ---Override def __init__(self, app): Markable.__init__(self) self.__groups = [] self.__group_of_duplicate = {} self.__groups_sort_descriptor = None # This is a tuple (key, asc) self.__dupes = None self.__dupes_sort_descriptor = None # This is a tuple (key, asc, delta) self.__filters = None self.__filtered_dupes = None self.__filtered_groups = None self.__recalculate_stats() self.__marked_size = 0 self.app = app self.problems = [] # (dupe, error_msg) self.is_modified = False self.refresh_required = False def _did_mark(self, dupe): self.__marked_size += dupe.size def _did_unmark(self, dupe): self.__marked_size -= dupe.size def _get_markable_count(self): return self.__total_count def _is_markable(self, dupe): if dupe.is_ref: return False g = self.get_group_of_duplicate(dupe) if not g: return False if dupe is g.ref: return False if self.__filtered_dupes and dupe not in self.__filtered_dupes: return False return True def mark_all(self): if self.__filters: self.mark_multiple(self.__filtered_dupes) else: Markable.mark_all(self) def mark_invert(self): if self.__filters: self.mark_toggle_multiple(self.__filtered_dupes) else: Markable.mark_invert(self) def mark_none(self): if self.__filters: self.unmark_multiple(self.__filtered_dupes) else: Markable.mark_none(self) # ---Private def __get_dupe_list(self): if self.__dupes is None or self.refresh_required: self.__dupes = flatten(group.dupes for group in self.groups) self.refresh_required = False if None in self.__dupes: # This is debug logging to try to figure out #44 logging.warning( "There is a None value in the Results' dupe list. dupes: %r groups: %r", self.__dupes, self.groups, ) if self.__filtered_dupes: self.__dupes = [dupe for dupe in self.__dupes if dupe in self.__filtered_dupes] sd = self.__dupes_sort_descriptor if sd: self.sort_dupes(sd[0], sd[1], sd[2]) return self.__dupes def __get_groups(self): if self.__filtered_groups is None: return self.__groups else: return self.__filtered_groups def __get_stat_line(self): if self.__filtered_dupes is None: mark_count = self.mark_count marked_size = self.__marked_size total_count = self.__total_count total_size = self.__total_size else: mark_count = len([dupe for dupe in self.__filtered_dupes if self.is_marked(dupe)]) marked_size = sum(dupe.size for dupe in self.__filtered_dupes if self.is_marked(dupe)) total_count = len([dupe for dupe in self.__filtered_dupes if self.is_markable(dupe)]) total_size = sum(dupe.size for dupe in self.__filtered_dupes if self.is_markable(dupe)) if self.mark_inverted: marked_size = self.__total_size - marked_size result = tr("%d / %d (%s / %s) duplicates marked.") % ( mark_count, total_count, format_size(marked_size, 2), format_size(total_size, 2), ) if self.__filters: result += tr(" filter: %s") % " --> ".join(self.__filters) return result def __recalculate_stats(self): self.__total_size = 0 self.__total_count = 0 for group in self.groups: markable = [dupe for dupe in group.dupes if self._is_markable(dupe)] self.__total_count += len(markable) self.__total_size += sum(dupe.size for dupe in markable) def __set_groups(self, new_groups): self.mark_none() self.__groups = new_groups self.__group_of_duplicate = {} for g in self.__groups: for dupe in g: self.__group_of_duplicate[dupe] = g if not hasattr(dupe, "is_ref"): dupe.is_ref = False self.is_modified = bool(self.__groups) old_filters = nonone(self.__filters, []) self.apply_filter(None) for filter_str in old_filters: self.apply_filter(filter_str) # ---Public def apply_filter(self, filter_str): """Applies a filter ``filter_str`` to :attr:`groups` When you apply the filter, only dupes with the filename matching ``filter_str`` will be in in the results. To cancel the filter, just call apply_filter with ``filter_str`` to None, and the results will go back to normal. If call apply_filter on a filtered results, the filter will be applied *on the filtered results*. :param str filter_str: a string containing a regexp to filter dupes with. """ if not filter_str: self.__filtered_dupes = None self.__filtered_groups = None self.__filters = None else: if not self.__filters: self.__filters = [] try: filter_re = re.compile(filter_str, re.IGNORECASE) except re.error: return # don't apply this filter. self.__filters.append(filter_str) if self.__filtered_dupes is None: self.__filtered_dupes = flatten(g[:] for g in self.groups) self.__filtered_dupes = {dupe for dupe in self.__filtered_dupes if filter_re.search(str(dupe.path))} filtered_groups = set() for dupe in self.__filtered_dupes: filtered_groups.add(self.get_group_of_duplicate(dupe)) self.__filtered_groups = list(filtered_groups) self.__recalculate_stats() sd = self.__groups_sort_descriptor if sd: self.sort_groups(sd[0], sd[1]) self.__dupes = None def get_group_of_duplicate(self, dupe): """Returns :class:`~core.engine.Group` in which ``dupe`` belongs.""" try: return self.__group_of_duplicate[dupe] except (TypeError, KeyError): return None is_markable = _is_markable def load_from_xml(self, infile, get_file, j=nulljob): """Load results from ``infile``. :param infile: a file or path pointing to an XML file created with :meth:`save_to_xml`. :param get_file: a function f(path) returning a :class:`~core.fs.File` wrapping the path. :param j: A :ref:`job progress instance <jobs>`. """ def do_match(ref_file, other_files, group): if not other_files: return for other_file in other_files: group.add_match(engine.get_match(ref_file, other_file)) do_match(other_files[0], other_files[1:], group) self.apply_filter(None) root = ET.parse(infile).getroot() group_elems = list(root.iter("group")) groups = [] marked = set() for group_elem in j.iter_with_progress(group_elems, every=100): group = engine.Group() dupes = [] for file_elem in group_elem.iter("file"): path = file_elem.get("path") words = file_elem.get("words", "") if not path: continue file = get_file(path) if file is None: continue file.words = words.split(",") file.is_ref = file_elem.get("is_ref") == "y" dupes.append(file) if file_elem.get("marked") == "y": marked.add(file) for match_elem in group_elem.iter("match"): try: attrs = match_elem.attrib first_file = dupes[int(attrs["first"])] second_file = dupes[int(attrs["second"])] percentage = int(attrs["percentage"]) group.add_match(engine.Match(first_file, second_file, percentage)) except (IndexError, KeyError, ValueError): # Covers missing attr, non-int values and indexes out of bounds pass if (not group.matches) and (len(dupes) >= 2): do_match(dupes[0], dupes[1:], group) group.prioritize(lambda x: dupes.index(x)) if len(group): groups.append(group) j.add_progress() self.groups = groups for dupe_file in marked: self.mark(dupe_file) self.is_modified = False def make_ref(self, dupe): """Make ``dupe`` take the :attr:`~core.engine.Group.ref` position of its group.""" g = self.get_group_of_duplicate(dupe) r = g.ref if not g.switch_ref(dupe): return False self._remove_mark_flag(dupe) if not r.is_ref: self.__total_count += 1 self.__total_size += r.size if not dupe.is_ref: self.__total_count -= 1 self.__total_size -= dupe.size self.__dupes = None self.is_modified = True return True def perform_on_marked(self, func, remove_from_results): """Performs ``func`` on all marked dupes. If an ``EnvironmentError`` is raised during the call, the problematic dupe is added to self.problems. :param bool remove_from_results: If true, dupes which had ``func`` applied and didn't cause any problem. """ self.problems = [] to_remove = [] marked = (dupe for dupe in self.dupes if self.is_marked(dupe)) for dupe in marked: try: func(dupe) to_remove.append(dupe) except (OSError, UnicodeEncodeError) as e: self.problems.append((dupe, str(e))) if remove_from_results: self.remove_duplicates(to_remove) self.mark_none() for dupe, _ in self.problems: self.mark(dupe) def remove_duplicates(self, dupes): """Remove ``dupes`` from their respective :class:`~core.engine.Group`. Also, remove the group from :attr:`groups` if it ends up empty. """ affected_groups = set() for dupe in dupes: group = self.get_group_of_duplicate(dupe) if dupe not in group.dupes: return ref = group.ref group.remove_dupe(dupe, False) del self.__group_of_duplicate[dupe] self._remove_mark_flag(dupe) self.__total_count -= 1 self.__total_size -= dupe.size if not group: del self.__group_of_duplicate[ref] self.__groups.remove(group) if self.__filtered_groups: self.__filtered_groups.remove(group) else: affected_groups.add(group) for group in affected_groups: group.discard_matches() self.__dupes = None self.is_modified = bool(self.__groups) def save_to_xml(self, outfile): """Save results to ``outfile`` in XML. :param outfile: file object or path. """ self.apply_filter(None) root = ET.Element("results") for g in self.groups: group_elem = ET.SubElement(root, "group") dupe2index = {} for index, d in enumerate(g): dupe2index[d] = index try: words = engine.unpack_fields(d.words) except AttributeError: words = () file_elem = ET.SubElement(group_elem, "file") try: file_elem.set("path", str(d.path)) file_elem.set("words", ",".join(words)) except ValueError: # If there's an invalid character, just skip the file file_elem.set("path", "") file_elem.set("is_ref", ("y" if d.is_ref else "n")) file_elem.set("marked", ("y" if self.is_marked(d) else "n")) for match in g.matches: match_elem = ET.SubElement(group_elem, "match") match_elem.set("first", str(dupe2index[match.first])) match_elem.set("second", str(dupe2index[match.second])) match_elem.set("percentage", str(int(match.percentage))) tree = ET.ElementTree(root) def do_write(outfile): with FileOrPath(outfile, "wb") as fp: tree.write(fp, encoding="utf-8") try: do_write(outfile) except OSError as e: # If our OSError is because dest is already a directory, we want to handle that. 21 is # the code we get on OS X and Linux (EISDIR), 13 is what we get on Windows (EACCES). if e.errno in (EISDIR, EACCES): p = str(outfile) dirname, basename = op.split(p) otherfiles = os.listdir(dirname) newname = get_conflicted_name(otherfiles, basename) do_write(op.join(dirname, newname)) else: raise self.is_modified = False def sort_dupes(self, key, asc=True, delta=False): """Sort :attr:`dupes` according to ``key``. :param str key: key attribute name to sort with. :param bool asc: If false, sorting is reversed. :param bool delta: If true, sorting occurs using :ref:`delta values <deltavalues>`. """ if not self.__dupes: self.__get_dupe_list() self.__dupes.sort( key=lambda d: self.app._get_dupe_sort_key(d, lambda: self.get_group_of_duplicate(d), key, delta), reverse=not asc, ) self.__dupes_sort_descriptor = (key, asc, delta) def sort_groups(self, key, asc=True): """Sort :attr:`groups` according to ``key``. The :attr:`~core.engine.Group.ref` of each group is used to extract values for sorting. :param str key: key attribute name to sort with. :param bool asc: If false, sorting is reversed. """ self.groups.sort(key=lambda g: self.app._get_group_sort_key(g, key), reverse=not asc) self.__groups_sort_descriptor = (key, asc) # ---Properties dupes = property(__get_dupe_list) groups = property(__get_groups, __set_groups) stat_line = property(__get_stat_line)
16,037
Python
.py
371
31.924528
112
0.565153
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,125
prioritize.py
arsenetar_dupeguru/core/prioritize.py
# Created By: Virgil Dupras # Created On: 2011/09/07 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.util import dedupe, flatten, rem_file_ext from hscommon.trans import trget, tr coltr = trget("columns") class CriterionCategory: NAME = "Undefined" def __init__(self, results): self.results = results # --- Virtual def extract_value(self, dupe): raise NotImplementedError() def format_criterion_value(self, value): return value def sort_key(self, dupe, crit_value): raise NotImplementedError() def criteria_list(self): raise NotImplementedError() class Criterion: def __init__(self, category, value): self.category = category self.value = value self.display_value = category.format_criterion_value(value) def sort_key(self, dupe): return self.category.sort_key(dupe, self.value) @property def display(self): return f"{self.category.NAME} ({self.display_value})" class ValueListCategory(CriterionCategory): def sort_key(self, dupe, crit_value): # Use this sort key when the order in the list depends on whether or not the dupe meets the # criteria. If it does, we return 0 (top of the list), if it doesn't, we return 1. if self.extract_value(dupe) == crit_value: return 0 else: return 1 def criteria_list(self): dupes = flatten(g[:] for g in self.results.groups) values = sorted(dedupe(self.extract_value(d) for d in dupes)) return [Criterion(self, value) for value in values] class KindCategory(ValueListCategory): NAME = coltr("Kind") def extract_value(self, dupe): value = dupe.extension if not value: value = tr("None") return value class FolderCategory(ValueListCategory): NAME = coltr("Folder") def extract_value(self, dupe): return dupe.folder_path def format_criterion_value(self, value): return str(value) def sort_key(self, dupe, crit_value): value = self.extract_value(dupe) # This is instead of using is_relative_to() which was added in py 3.9 try: value.relative_to(crit_value) except ValueError: return 1 return 0 class FilenameCategory(CriterionCategory): NAME = coltr("Filename") ENDS_WITH_NUMBER = 0 DOESNT_END_WITH_NUMBER = 1 LONGEST = 2 SHORTEST = 3 LONGEST_PATH = 4 SHORTEST_PATH = 5 def format_criterion_value(self, value): return { self.ENDS_WITH_NUMBER: tr("Ends with number"), self.DOESNT_END_WITH_NUMBER: tr("Doesn't end with number"), self.LONGEST: tr("Longest"), self.SHORTEST: tr("Shortest"), self.LONGEST_PATH: tr("Longest Path"), self.SHORTEST_PATH: tr("Shortest Path"), }[value] def extract_value(self, dupe): return rem_file_ext(dupe.name) def sort_key(self, dupe, crit_value): value = self.extract_value(dupe) if crit_value in {self.ENDS_WITH_NUMBER, self.DOESNT_END_WITH_NUMBER}: ends_with_digit = value.strip()[-1:].isdigit() if crit_value == self.ENDS_WITH_NUMBER: return 0 if ends_with_digit else 1 else: return 1 if ends_with_digit else 0 elif crit_value == self.LONGEST_PATH: return len(str(dupe.folder_path)) * -1 elif crit_value == self.SHORTEST_PATH: return len(str(dupe.folder_path)) else: value = len(value) if crit_value == self.LONGEST: value *= -1 # We want the biggest values on top return value def criteria_list(self): return [ Criterion(self, crit_value) for crit_value in [ self.ENDS_WITH_NUMBER, self.DOESNT_END_WITH_NUMBER, self.LONGEST, self.SHORTEST, self.LONGEST_PATH, self.SHORTEST_PATH, ] ] class NumericalCategory(CriterionCategory): HIGHEST = 0 LOWEST = 1 def format_criterion_value(self, value): return tr("Highest") if value == self.HIGHEST else tr("Lowest") def invert_numerical_value(self, value): # Virtual return value * -1 def sort_key(self, dupe, crit_value): value = self.extract_value(dupe) if crit_value == self.HIGHEST: # we want highest values on top value = self.invert_numerical_value(value) return value def criteria_list(self): return [Criterion(self, self.HIGHEST), Criterion(self, self.LOWEST)] class SizeCategory(NumericalCategory): NAME = coltr("Size") def extract_value(self, dupe): return dupe.size class MtimeCategory(NumericalCategory): NAME = coltr("Modification") def extract_value(self, dupe): return dupe.mtime def format_criterion_value(self, value): return tr("Newest") if value == self.HIGHEST else tr("Oldest") def all_categories(): return [KindCategory, FolderCategory, FilenameCategory, SizeCategory, MtimeCategory]
5,457
Python
.py
140
30.828571
99
0.636571
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,126
engine.py
arsenetar_dupeguru/core/engine.py
# Created By: Virgil Dupras # Created On: 2006/01/29 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import difflib import itertools import logging import string from collections import defaultdict, namedtuple from unicodedata import normalize from hscommon.util import flatten, multi_replace from hscommon.trans import tr from hscommon.jobprogress import job ( WEIGHT_WORDS, MATCH_SIMILAR_WORDS, NO_FIELD_ORDER, ) = range(3) JOB_REFRESH_RATE = 100 PROGRESS_MESSAGE = tr("%d matches found from %d groups") def getwords(s): # We decompose the string so that ascii letters with accents can be part of the word. s = normalize("NFD", s) s = multi_replace(s, "-_&+():;\\[]{}.,<>/?~!@#$*", " ").lower() # logging.debug(f"DEBUG chars for: {s}\n" # f"{[c for c in s if ord(c) != 32]}\n" # f"{[ord(c) for c in s if ord(c) != 32]}") # HACK We shouldn't ignore non-ascii characters altogether. Any Unicode char # above common european characters that cannot be "sanitized" (ie. stripped # of their accents, etc.) are preserved as is. The arbitrary limit is # obtained from this one: ord("\u037e") GREEK QUESTION MARK s = "".join( c for c in s if (ord(c) <= 894 and c in string.ascii_letters + string.digits + string.whitespace) or ord(c) > 894 ) return [_f for _f in s.split(" ") if _f] # remove empty elements def getfields(s): fields = [getwords(field) for field in s.split(" - ")] return [_f for _f in fields if _f] def unpack_fields(fields): result = [] for field in fields: if isinstance(field, list): result += field else: result.append(field) return result def compare(first, second, flags=()): """Returns the % of words that match between ``first`` and ``second`` The result is a ``int`` in the range 0..100. ``first`` and ``second`` can be either a string or a list (of words). """ if not (first and second): return 0 if any(isinstance(element, list) for element in first): return compare_fields(first, second, flags) second = second[:] # We must use a copy of second because we remove items from it match_similar = MATCH_SIMILAR_WORDS in flags weight_words = WEIGHT_WORDS in flags joined = first + second total_count = sum(len(word) for word in joined) if weight_words else len(joined) match_count = 0 in_order = True for word in first: if match_similar and (word not in second): similar = difflib.get_close_matches(word, second, 1, 0.8) if similar: word = similar[0] if word in second: if second[0] != word: in_order = False second.remove(word) match_count += len(word) if weight_words else 1 result = round(((match_count * 2) / total_count) * 100) if (result == 100) and (not in_order): result = 99 # We cannot consider a match exact unless the ordering is the same return result def compare_fields(first, second, flags=()): """Returns the score for the lowest matching :ref:`fields`. ``first`` and ``second`` must be lists of lists of string. Each sub-list is then compared with :func:`compare`. """ if len(first) != len(second): return 0 if NO_FIELD_ORDER in flags: results = [] # We don't want to remove field directly in the list. We must work on a copy. second = second[:] for field1 in first: max_score = 0 matched_field = None for field2 in second: r = compare(field1, field2, flags) if r > max_score: max_score = r matched_field = field2 results.append(max_score) if matched_field: second.remove(matched_field) else: results = [compare(field1, field2, flags) for field1, field2 in zip(first, second)] return min(results) if results else 0 def build_word_dict(objects, j=job.nulljob): """Returns a dict of objects mapped by their words. objects must have a ``words`` attribute being a list of strings or a list of lists of strings (:ref:`fields`). The result will be a dict with words as keys, lists of objects as values. """ result = defaultdict(set) for object in j.iter_with_progress(objects, "Prepared %d/%d files", JOB_REFRESH_RATE): for word in unpack_fields(object.words): result[word].add(object) return result def merge_similar_words(word_dict): """Take all keys in ``word_dict`` that are similar, and merge them together. ``word_dict`` has been built with :func:`build_word_dict`. Similarity is computed with Python's ``difflib.get_close_matches()``, which computes the number of edits that are necessary to make a word equal to the other. """ keys = list(word_dict.keys()) keys.sort(key=len) # we want the shortest word to stay while keys: key = keys.pop(0) similars = difflib.get_close_matches(key, keys, 100, 0.8) if not similars: continue objects = word_dict[key] for similar in similars: objects |= word_dict[similar] del word_dict[similar] keys.remove(similar) def reduce_common_words(word_dict, threshold): """Remove all objects from ``word_dict`` values where the object count >= ``threshold`` ``word_dict`` has been built with :func:`build_word_dict`. The exception to this removal are the objects where all the words of the object are common. Because if we remove them, we will miss some duplicates! """ uncommon_words = {word for word, objects in word_dict.items() if len(objects) < threshold} for word, objects in list(word_dict.items()): if len(objects) < threshold: continue reduced = set() for o in objects: if not any(w in uncommon_words for w in unpack_fields(o.words)): reduced.add(o) if reduced: word_dict[word] = reduced else: del word_dict[word] # Writing docstrings in a namedtuple is tricky. From Python 3.3, it's possible to set __doc__, but # some research allowed me to find a more elegant solution, which is what is done here. See # http://stackoverflow.com/questions/1606436/adding-docstrings-to-namedtuples-in-python class Match(namedtuple("Match", "first second percentage")): """Represents a match between two :class:`~core.fs.File`. Regarless of the matching method, when two files are determined to match, a Match pair is created, which holds, of course, the two matched files, but also their match "level". .. attribute:: first first file of the pair. .. attribute:: second second file of the pair. .. attribute:: percentage their match level according to the scan method which found the match. int from 1 to 100. For exact scan methods, such as Contents scans, this will always be 100. """ __slots__ = () def get_match(first, second, flags=()): # it is assumed here that first and second both have a "words" attribute percentage = compare(first.words, second.words, flags) return Match(first, second, percentage) def getmatches( objects, min_match_percentage=0, match_similar_words=False, weight_words=False, no_field_order=False, j=job.nulljob, ): """Returns a list of :class:`Match` within ``objects`` after fuzzily matching their words. :param objects: List of :class:`~core.fs.File` to match. :param int min_match_percentage: minimum % of words that have to match. :param bool match_similar_words: make similar words (see :func:`merge_similar_words`) match. :param bool weight_words: longer words are worth more in match % computations. :param bool no_field_order: match :ref:`fields` regardless of their order. :param j: A :ref:`job progress instance <jobs>`. """ COMMON_WORD_THRESHOLD = 50 LIMIT = 5000000 j = j.start_subjob(2) sj = j.start_subjob(2) for o in objects: if not hasattr(o, "words"): o.words = getwords(o.name) word_dict = build_word_dict(objects, sj) reduce_common_words(word_dict, COMMON_WORD_THRESHOLD) if match_similar_words: merge_similar_words(word_dict) match_flags = [] if weight_words: match_flags.append(WEIGHT_WORDS) if match_similar_words: match_flags.append(MATCH_SIMILAR_WORDS) if no_field_order: match_flags.append(NO_FIELD_ORDER) j.start_job(len(word_dict), PROGRESS_MESSAGE % (0, 0)) compared = defaultdict(set) result = [] try: word_count = 0 # This whole 'popping' thing is there to avoid taking too much memory at the same time. while word_dict: items = word_dict.popitem()[1] while items: ref = items.pop() compared_already = compared[ref] to_compare = items - compared_already compared_already |= to_compare for other in to_compare: m = get_match(ref, other, match_flags) if m.percentage >= min_match_percentage: result.append(m) if len(result) >= LIMIT: return result word_count += 1 j.add_progress(desc=PROGRESS_MESSAGE % (len(result), word_count)) except MemoryError: # This is the place where the memory usage is at its peak during the scan. # Just continue the process with an incomplete list of matches. del compared # This should give us enough room to call logging. logging.warning("Memory Overflow. Matches: %d. Word dict: %d" % (len(result), len(word_dict))) return result return result def getmatches_by_contents(files, bigsize=0, j=job.nulljob): """Returns a list of :class:`Match` within ``files`` if their contents is the same. :param bigsize: The size in bytes over which we consider files big enough to justify taking samples of the file for hashing. If 0, compute digest as usual. :param j: A :ref:`job progress instance <jobs>`. """ size2files = defaultdict(set) for f in files: size2files[f.size].add(f) del files possible_matches = [files for files in size2files.values() if len(files) > 1] del size2files result = [] j.start_job(len(possible_matches), PROGRESS_MESSAGE % (0, 0)) group_count = 0 for group in possible_matches: for first, second in itertools.combinations(group, 2): if first.is_ref and second.is_ref: continue # Don't spend time comparing two ref pics together. if first.size == 0 and second.size == 0: # skip hashing for zero length files result.append(Match(first, second, 100)) continue # if digests are the same (and not None) then files match if first.digest_partial is not None and first.digest_partial == second.digest_partial: if bigsize > 0 and first.size > bigsize: if first.digest_samples is not None and first.digest_samples == second.digest_samples: result.append(Match(first, second, 100)) else: if first.digest is not None and first.digest == second.digest: result.append(Match(first, second, 100)) group_count += 1 j.add_progress(desc=PROGRESS_MESSAGE % (len(result), group_count)) return result class Group: """A group of :class:`~core.fs.File` that match together. This manages match pairs into groups and ensures that all files in the group match to each other. .. attribute:: ref The "reference" file, which is the file among the group that isn't going to be deleted. .. attribute:: ordered Ordered list of duplicates in the group (including the :attr:`ref`). .. attribute:: unordered Set duplicates in the group (including the :attr:`ref`). .. attribute:: dupes An ordered list of the group's duplicate, without :attr:`ref`. Equivalent to ``ordered[1:]`` .. attribute:: percentage Average match percentage of match pairs containing :attr:`ref`. """ # ---Override def __init__(self): self._clear() def __contains__(self, item): return item in self.unordered def __getitem__(self, key): return self.ordered.__getitem__(key) def __iter__(self): return iter(self.ordered) def __len__(self): return len(self.ordered) # ---Private def _clear(self): self._percentage = None self._matches_for_ref = None self.matches = set() self.candidates = defaultdict(set) self.ordered = [] self.unordered = set() def _get_matches_for_ref(self): if self._matches_for_ref is None: ref = self.ref self._matches_for_ref = [match for match in self.matches if ref in match] return self._matches_for_ref # ---Public def add_match(self, match): """Adds ``match`` to internal match list and possibly add duplicates to the group. A duplicate can only be considered as such if it matches all other duplicates in the group. This method registers that pair (A, B) represented in ``match`` as possible candidates and, if A and/or B end up matching every other duplicates in the group, add these duplicates to the group. :param tuple match: pair of :class:`~core.fs.File` to add """ def add_candidate(item, match): matches = self.candidates[item] matches.add(match) if self.unordered <= matches: self.ordered.append(item) self.unordered.add(item) if match in self.matches: return self.matches.add(match) first, second, _ = match if first not in self.unordered: add_candidate(first, second) if second not in self.unordered: add_candidate(second, first) self._percentage = None self._matches_for_ref = None def discard_matches(self): """Remove all recorded matches that didn't result in a duplicate being added to the group. You can call this after the duplicate scanning process to free a bit of memory. """ discarded = {m for m in self.matches if not all(obj in self.unordered for obj in [m.first, m.second])} self.matches -= discarded self.candidates = defaultdict(set) return discarded def get_match_of(self, item): """Returns the match pair between ``item`` and :attr:`ref`.""" if item is self.ref: return for m in self._get_matches_for_ref(): if item in m: return m def prioritize(self, key_func, tie_breaker=None): """Reorders :attr:`ordered` according to ``key_func``. :param key_func: Key (f(x)) to be used for sorting :param tie_breaker: function to be used to select the reference position in case the top duplicates have the same key_func() result. """ # tie_breaker(ref, dupe) --> True if dupe should be ref # Returns True if anything changed during prioritization. new_order = sorted(self.ordered, key=lambda x: (-x.is_ref, key_func(x))) changed = new_order != self.ordered self.ordered = new_order if tie_breaker is None: return changed ref = self.ref key_value = key_func(ref) for dupe in self.dupes: if key_func(dupe) != key_value: break if tie_breaker(ref, dupe): ref = dupe if ref is not self.ref: self.switch_ref(ref) return True return changed def remove_dupe(self, item, discard_matches=True): try: self.ordered.remove(item) self.unordered.remove(item) self._percentage = None self._matches_for_ref = None if (len(self) > 1) and any(not getattr(item, "is_ref", False) for item in self): if discard_matches: self.matches = {m for m in self.matches if item not in m} else: self._clear() except ValueError: pass def switch_ref(self, with_dupe): """Make the :attr:`ref` dupe of the group switch position with ``with_dupe``.""" if self.ref.is_ref: return False try: self.ordered.remove(with_dupe) self.ordered.insert(0, with_dupe) self._percentage = None self._matches_for_ref = None return True except ValueError: return False dupes = property(lambda self: self[1:]) @property def percentage(self): if self._percentage is None: if self.dupes: matches = self._get_matches_for_ref() self._percentage = sum(match.percentage for match in matches) // len(matches) else: self._percentage = 0 return self._percentage @property def ref(self): if self: return self[0] def get_groups(matches): """Returns a list of :class:`Group` from ``matches``. Create groups out of match pairs in the smartest way possible. """ matches.sort(key=lambda match: -match.percentage) dupe2group = {} groups = [] try: for match in matches: first, second, _ = match first_group = dupe2group.get(first) second_group = dupe2group.get(second) if first_group: if second_group: if first_group is second_group: target_group = first_group else: continue else: target_group = first_group dupe2group[second] = target_group else: if second_group: target_group = second_group dupe2group[first] = target_group else: target_group = Group() groups.append(target_group) dupe2group[first] = target_group dupe2group[second] = target_group target_group.add_match(match) except MemoryError: del dupe2group del matches # should free enough memory to continue logging.warning(f"Memory Overflow. Groups: {len(groups)}") # Now that we have a group, we have to discard groups' matches and see if there're any "orphan" # matches, that is, matches that were candidate in a group but that none of their 2 files were # accepted in the group. With these orphan groups, it's safe to build additional groups matched_files = set(flatten(groups)) orphan_matches = [] for group in groups: orphan_matches += { m for m in group.discard_matches() if not any(obj in matched_files for obj in [m.first, m.second]) } if groups and orphan_matches: groups += get_groups(orphan_matches) # no job, as it isn't supposed to take a long time return groups
19,921
Python
.py
460
34.373913
110
0.618291
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,127
markable.py
arsenetar_dupeguru/core/markable.py
# Created By: Virgil Dupras # Created On: 2006/02/23 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html class Markable: def __init__(self): self.__marked = set() self.__inverted = False # ---Virtual # About did_mark and did_unmark: They only happen what an object is actually added/removed # in self.__marked, and is not affected by __inverted. Thus, self.mark while __inverted # is True will launch _DidUnmark. def _did_mark(self, o): # Implemented in child classes pass def _did_unmark(self, o): # Implemented in child classes pass def _get_markable_count(self): return 0 def _is_markable(self, o): return True # ---Protected def _remove_mark_flag(self, o): try: self.__marked.remove(o) self._did_unmark(o) except KeyError: pass # ---Public def is_marked(self, o): if not self._is_markable(o): return False is_marked = o in self.__marked if self.__inverted: is_marked = not is_marked return is_marked def mark(self, o): if self.is_marked(o): return False if not self._is_markable(o): return False return self.mark_toggle(o) def mark_multiple(self, objects): for o in objects: self.mark(o) def mark_all(self): self.mark_none() self.__inverted = True def mark_invert(self): self.__inverted = not self.__inverted def mark_none(self): for o in self.__marked: self._did_unmark(o) self.__marked = set() self.__inverted = False def mark_toggle(self, o): try: self.__marked.remove(o) self._did_unmark(o) except KeyError: if not self._is_markable(o): return False self.__marked.add(o) self._did_mark(o) return True def mark_toggle_multiple(self, objects): for o in objects: self.mark_toggle(o) def unmark(self, o): if not self.is_marked(o): return False return self.mark_toggle(o) def unmark_multiple(self, objects): for o in objects: self.unmark(o) # --- Properties @property def mark_count(self): if self.__inverted: return self._get_markable_count() - len(self.__marked) else: return len(self.__marked) @property def mark_inverted(self): return self.__inverted class MarkableList(list, Markable): def __init__(self): list.__init__(self) Markable.__init__(self) def _get_markable_count(self): return len(self) def _is_markable(self, o): return o in self
3,064
Python
.py
96
23.708333
94
0.583899
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,128
directories.py
arsenetar_dupeguru/core/directories.py
# Copyright 2017 Virgil Dupras # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import os from xml.etree import ElementTree as ET import logging from pathlib import Path from hscommon.jobprogress import job from hscommon.util import FileOrPath from hscommon.trans import tr from core import fs __all__ = [ "Directories", "DirectoryState", "AlreadyThereError", "InvalidPathError", ] class DirectoryState: """Enum describing how a folder should be considered. * DirectoryState.Normal: Scan all files normally * DirectoryState.Reference: Scan files, but make sure never to delete any of them * DirectoryState.Excluded: Don't scan this folder """ NORMAL = 0 REFERENCE = 1 EXCLUDED = 2 class AlreadyThereError(Exception): """The path being added is already in the directory list""" class InvalidPathError(Exception): """The path being added is invalid""" class Directories: """Holds user folder selection. Manages the selection that the user make through the folder selection dialog. It also manages folder states, and how recursion applies to them. Then, when the user starts the scan, :meth:`get_files` is called to retrieve all files (wrapped in :mod:`core.fs`) that have to be scanned according to the chosen folders/states. """ # ---Override def __init__(self, exclude_list=None): self._dirs = [] # {path: state} self.states = {} self._exclude_list = exclude_list def __contains__(self, path): for p in self._dirs: if path == p or p in path.parents: return True return False def __delitem__(self, key): self._dirs.__delitem__(key) def __getitem__(self, key): return self._dirs.__getitem__(key) def __len__(self): return len(self._dirs) # ---Private def _default_state_for_path(self, path): # New logic with regex filters if self._exclude_list is not None and self._exclude_list.mark_count > 0: # We iterate even if we only have one item here for denied_path_re in self._exclude_list.compiled: if denied_path_re.match(str(path.name)): return DirectoryState.EXCLUDED return DirectoryState.NORMAL # Override this in subclasses to specify the state of some special folders. if path.name.startswith("."): return DirectoryState.EXCLUDED return DirectoryState.NORMAL def _get_files(self, from_path, fileclasses, j): try: with os.scandir(from_path) as iter: root_path = Path(from_path) state = self.get_state(root_path) # if we have no un-excluded dirs under this directory skip going deeper skip_dirs = state == DirectoryState.EXCLUDED and not any( p.parts[: len(root_path.parts)] == root_path.parts for p in self.states ) count = 0 for item in iter: j.check_if_cancelled() try: if item.is_dir(): if skip_dirs: continue yield from self._get_files(item.path, fileclasses, j) continue elif state == DirectoryState.EXCLUDED: continue # File excluding or not if ( self._exclude_list is None or not self._exclude_list.mark_count or not self._exclude_list.is_excluded(str(from_path), item.name) ): file = fs.get_file(item, fileclasses=fileclasses) if file: file.is_ref = state == DirectoryState.REFERENCE count += 1 yield file except (OSError, fs.InvalidPath): pass logging.debug( "Collected %d files in folder %s", count, str(root_path), ) except OSError: pass def _get_folders(self, from_folder, j): j.check_if_cancelled() try: for subfolder in from_folder.subfolders: yield from self._get_folders(subfolder, j) state = self.get_state(from_folder.path) if state != DirectoryState.EXCLUDED: from_folder.is_ref = state == DirectoryState.REFERENCE logging.debug("Yielding Folder %r state: %d", from_folder, state) yield from_folder except (OSError, fs.InvalidPath): pass # ---Public def add_path(self, path): """Adds ``path`` to self, if not already there. Raises :exc:`AlreadyThereError` if ``path`` is already in self. If path is a directory containing some of the directories already present in self, ``path`` will be added, but all directories under it will be removed. Can also raise :exc:`InvalidPathError` if ``path`` does not exist. :param Path path: path to add """ if path in self: raise AlreadyThereError() if not path.exists(): raise InvalidPathError() self._dirs = [p for p in self._dirs if path not in p.parents] self._dirs.append(path) @staticmethod def get_subfolders(path): """Returns a sorted list of paths corresponding to subfolders in ``path``. :param Path path: get subfolders from there :rtype: list of Path """ try: subpaths = [p for p in path.glob("*") if p.is_dir()] subpaths.sort(key=lambda x: x.name.lower()) return subpaths except OSError: return [] def get_files(self, fileclasses=None, j=job.nulljob): """Returns a list of all files that are not excluded. Returned files also have their ``is_ref`` attr set if applicable. """ if fileclasses is None: fileclasses = [fs.File] file_count = 0 for path in self._dirs: for file in self._get_files(path, fileclasses=fileclasses, j=j): file_count += 1 if not isinstance(j, job.NullJob): j.set_progress(-1, tr("Collected {} files to scan").format(file_count)) yield file def get_folders(self, folderclass=None, j=job.nulljob): """Returns a list of all folders that are not excluded. Returned folders also have their ``is_ref`` attr set if applicable. """ if folderclass is None: folderclass = fs.Folder folder_count = 0 for path in self._dirs: from_folder = folderclass(path) for folder in self._get_folders(from_folder, j): folder_count += 1 if not isinstance(j, job.NullJob): j.set_progress(-1, tr("Collected {} folders to scan").format(folder_count)) yield folder def get_state(self, path): """Returns the state of ``path``. :rtype: :class:`DirectoryState` """ # direct match? easy result. if path in self.states: return self.states[path] state = self._default_state_for_path(path) # Save non-default states in cache, necessary for _get_files() if state != DirectoryState.NORMAL: self.states[path] = state return state # find the longest parent path that is in states and return that state if found # NOTE: path.parents is ordered longest to shortest for parent_path in path.parents: if parent_path in self.states: return self.states[parent_path] return state def has_any_file(self): """Returns whether selected folders contain any file. Because it stops at the first file it finds, it's much faster than get_files(). :rtype: bool """ try: next(self.get_files()) return True except StopIteration: return False def load_from_file(self, infile): """Load folder selection from ``infile``. :param file infile: path or file pointer to XML generated through :meth:`save_to_file` """ try: root = ET.parse(infile).getroot() except Exception: return for rdn in root.iter("root_directory"): attrib = rdn.attrib if "path" not in attrib: continue path = attrib["path"] try: self.add_path(Path(path)) except (AlreadyThereError, InvalidPathError): pass for sn in root.iter("state"): attrib = sn.attrib if not ("path" in attrib and "value" in attrib): continue path = attrib["path"] state = attrib["value"] self.states[Path(path)] = int(state) def save_to_file(self, outfile): """Save folder selection as XML to ``outfile``. :param file outfile: path or file pointer to XML file to save to. """ with FileOrPath(outfile, "wb") as fp: root = ET.Element("directories") for root_path in self: root_path_node = ET.SubElement(root, "root_directory") root_path_node.set("path", str(root_path)) for path, state in self.states.items(): state_node = ET.SubElement(root, "state") state_node.set("path", str(path)) state_node.set("value", str(state)) tree = ET.ElementTree(root) tree.write(fp, encoding="utf-8") def set_state(self, path, state): """Set the state of folder at ``path``. :param Path path: path of the target folder :param state: state to set folder to :type state: :class:`DirectoryState` """ if self.get_state(path) == state: return for iter_path in list(self.states.keys()): if path in iter_path.parents: del self.states[iter_path] self.states[path] = state
10,673
Python
.py
254
30.389764
99
0.570217
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,129
scanner.py
arsenetar_dupeguru/core/scanner.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import logging import re import os.path as op from collections import namedtuple from hscommon.jobprogress import job from hscommon.util import dedupe, rem_file_ext, get_file_ext from hscommon.trans import tr from core import engine # It's quite ugly to have scan types from all editions all put in the same class, but because there's # there will be some nasty bugs popping up (ScanType is used in core when in should exclusively be # used in core_*). One day I'll clean this up. class ScanType: FILENAME = 0 FIELDS = 1 FIELDSNOORDER = 2 TAG = 3 FOLDERS = 4 CONTENTS = 5 # PE FUZZYBLOCK = 10 EXIFTIMESTAMP = 11 ScanOption = namedtuple("ScanOption", "scan_type label") SCANNABLE_TAGS = ["track", "artist", "album", "title", "genre", "year"] RE_DIGIT_ENDING = re.compile(r"\d+|\(\d+\)|\[\d+\]|{\d+}") def is_same_with_digit(name, refname): # Returns True if name is the same as refname, but with digits (with brackets or not) at the end if not name.startswith(refname): return False end = name[len(refname) :].strip() return RE_DIGIT_ENDING.match(end) is not None def remove_dupe_paths(files): # Returns files with duplicates-by-path removed. Files with the exact same path are considered # duplicates and only the first file to have a path is kept. In certain cases, we have files # that have the same path, but not with the same case, that's why we normalize. However, we also # have case-sensitive filesystems, and in those, we don't want to falsely remove duplicates, # that's why we have a `samefile` mechanism. result = [] path2file = {} for f in files: normalized = str(f.path).lower() if normalized in path2file: try: if op.samefile(normalized, str(path2file[normalized].path)): continue # same file, it's a dupe else: pass # We don't treat them as dupes except OSError: continue # File doesn't exist? Well, treat them as dupes else: path2file[normalized] = f result.append(f) return result class Scanner: def __init__(self): self.discarded_file_count = 0 def _getmatches(self, files, j): if ( self.size_threshold or self.large_size_threshold or self.scan_type in { ScanType.CONTENTS, ScanType.FOLDERS, } ): j = j.start_subjob([2, 8]) if self.size_threshold: files = [f for f in files if f.size >= self.size_threshold] if self.large_size_threshold: files = [f for f in files if f.size <= self.large_size_threshold] if self.scan_type in {ScanType.CONTENTS, ScanType.FOLDERS}: return engine.getmatches_by_contents(files, bigsize=self.big_file_size_threshold, j=j) else: j = j.start_subjob([2, 8]) kw = {} kw["match_similar_words"] = self.match_similar_words kw["weight_words"] = self.word_weighting kw["min_match_percentage"] = self.min_match_percentage if self.scan_type == ScanType.FIELDSNOORDER: self.scan_type = ScanType.FIELDS kw["no_field_order"] = True func = { ScanType.FILENAME: lambda f: engine.getwords(rem_file_ext(f.name)), ScanType.FIELDS: lambda f: engine.getfields(rem_file_ext(f.name)), ScanType.TAG: lambda f: [ engine.getwords(str(getattr(f, attrname))) for attrname in SCANNABLE_TAGS if attrname in self.scanned_tags ], }[self.scan_type] for f in j.iter_with_progress(files, tr("Read metadata of %d/%d files")): logging.debug("Reading metadata of %s", f.path) f.words = func(f) return engine.getmatches(files, j=j, **kw) @staticmethod def _key_func(dupe): return -dupe.size @staticmethod def _tie_breaker(ref, dupe): refname = rem_file_ext(ref.name).lower() dupename = rem_file_ext(dupe.name).lower() if "copy" in dupename: return False if "copy" in refname: return True if is_same_with_digit(dupename, refname): return False if is_same_with_digit(refname, dupename): return True return len(dupe.path.parts) > len(ref.path.parts) @staticmethod def get_scan_options(): """Returns a list of scanning options for this scanner. Returns a list of ``ScanOption``. """ raise NotImplementedError() def get_dupe_groups(self, files, ignore_list=None, j=job.nulljob): for f in (f for f in files if not hasattr(f, "is_ref")): f.is_ref = False files = remove_dupe_paths(files) logging.info("Getting matches. Scan type: %d", self.scan_type) matches = self._getmatches(files, j) logging.info("Found %d matches" % len(matches)) j.set_progress(100, tr("Almost done! Fiddling with results...")) # In removing what we call here "false matches", we first want to remove, if we scan by # folders, we want to remove folder matches for which the parent is also in a match (they're # "duplicated duplicates if you will). Then, we also don't want mixed file kinds if the # option isn't enabled, we want matches for which both files exist and, lastly, we don't # want matches with both files as ref. if self.scan_type == ScanType.FOLDERS and matches: allpath = {m.first.path for m in matches} allpath |= {m.second.path for m in matches} sortedpaths = sorted(allpath) toremove = set() last_parent_path = sortedpaths[0] for p in sortedpaths[1:]: if last_parent_path in p.parents: toremove.add(p) else: last_parent_path = p matches = [m for m in matches if m.first.path not in toremove or m.second.path not in toremove] if not self.mix_file_kind: matches = [m for m in matches if get_file_ext(m.first.name) == get_file_ext(m.second.name)] if self.include_exists_check: matches = [m for m in matches if m.first.exists() and m.second.exists()] # Contents already handles ref checks, other scan types might not catch during scan if self.scan_type != ScanType.CONTENTS: matches = [m for m in matches if not (m.first.is_ref and m.second.is_ref)] if ignore_list: matches = [m for m in matches if not ignore_list.are_ignored(str(m.first.path), str(m.second.path))] logging.info("Grouping matches") groups = engine.get_groups(matches) if self.scan_type in { ScanType.FILENAME, ScanType.FIELDS, ScanType.FIELDSNOORDER, ScanType.TAG, }: matched_files = dedupe([m.first for m in matches] + [m.second for m in matches]) self.discarded_file_count = len(matched_files) - sum(len(g) for g in groups) else: # Ticket #195 # To speed up the scan, we don't bother comparing contents of files that are both ref # files. However, this messes up "discarded" counting because there's a missing match # in cases where we end up with a dupe group anyway (with a non-ref file). Because it's # impossible to have discarded matches in exact dupe scans, we simply set it at 0, thus # bypassing our tricky problem. # Also, although ScanType.FuzzyBlock is not always doing exact comparisons, we also # bypass ref comparison, thus messing up with our "discarded" count. So we're # effectively disabling the "discarded" feature in PE, but it's better than falsely # reporting discarded matches. self.discarded_file_count = 0 groups = [g for g in groups if any(not f.is_ref for f in g)] logging.info("Created %d groups" % len(groups)) for g in groups: g.prioritize(self._key_func, self._tie_breaker) return groups match_similar_words = False min_match_percentage = 80 mix_file_kind = True scan_type = ScanType.FILENAME scanned_tags = {"artist", "title"} size_threshold = 0 large_size_threshold = 0 big_file_size_threshold = 0 word_weighting = False include_exists_check = True
8,974
Python
.py
192
37.114583
112
0.619662
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,130
ignore.py
arsenetar_dupeguru/core/ignore.py
# Created By: Virgil Dupras # Created On: 2006/05/02 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from xml.etree import ElementTree as ET from hscommon.util import FileOrPath class IgnoreList: """An ignore list implementation that is iterable, filterable and exportable to XML. Call Ignore to add an ignore list entry, and AreIgnore to check if 2 items are in the list. When iterated, 2 sized tuples will be returned, the tuples containing 2 items ignored together. """ # ---Override def __init__(self): self.clear() def __iter__(self): for first, seconds in self._ignored.items(): for second in seconds: yield (first, second) def __len__(self): return self._count # ---Public def are_ignored(self, first, second): def do_check(first, second): try: matches = self._ignored[first] return second in matches except KeyError: return False return do_check(first, second) or do_check(second, first) def clear(self): self._ignored = {} self._count = 0 def filter(self, func): """Applies a filter on all ignored items, and remove all matches where func(first,second) doesn't return True. """ filtered = IgnoreList() for first, second in self: if func(first, second): filtered.ignore(first, second) self._ignored = filtered._ignored self._count = filtered._count def ignore(self, first, second): if self.are_ignored(first, second): return try: matches = self._ignored[first] matches.add(second) except KeyError: try: matches = self._ignored[second] matches.add(first) except KeyError: matches = set() matches.add(second) self._ignored[first] = matches self._count += 1 def remove(self, first, second): def inner(first, second): try: matches = self._ignored[first] if second in matches: matches.discard(second) if not matches: del self._ignored[first] self._count -= 1 return True else: return False except KeyError: return False if not inner(first, second) and not inner(second, first): raise ValueError() def load_from_xml(self, infile): """Loads the ignore list from a XML created with save_to_xml. infile can be a file object or a filename. """ try: root = ET.parse(infile).getroot() except Exception: return file_elems = (e for e in root if e.tag == "file") for fn in file_elems: file_path = fn.get("path") if not file_path: continue subfile_elems = (e for e in fn if e.tag == "file") for sfn in subfile_elems: subfile_path = sfn.get("path") if subfile_path: self.ignore(file_path, subfile_path) def save_to_xml(self, outfile): """Create a XML file that can be used by load_from_xml. outfile can be a file object or a filename. """ root = ET.Element("ignore_list") for filename, subfiles in self._ignored.items(): file_node = ET.SubElement(root, "file") file_node.set("path", filename) for subfilename in subfiles: subfile_node = ET.SubElement(file_node, "file") subfile_node.set("path", subfilename) tree = ET.ElementTree(root) with FileOrPath(outfile, "wb") as fp: tree.write(fp, encoding="utf-8")
4,193
Python
.py
108
27.944444
99
0.568126
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,131
exif.py
arsenetar_dupeguru/core/pe/exif.py
# Created By: Virgil Dupras # Created On: 2011-04-20 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html # Heavily based on http://topo.math.u-psud.fr/~bousch/exifdump.py by Thierry Bousch (Public Domain) import logging EXIF_TAGS = { 0x0100: "ImageWidth", 0x0101: "ImageLength", 0x0102: "BitsPerSample", 0x0103: "Compression", 0x0106: "PhotometricInterpretation", 0x010A: "FillOrder", 0x010D: "DocumentName", 0x010E: "ImageDescription", 0x010F: "Make", 0x0110: "Model", 0x0111: "StripOffsets", 0x0112: "Orientation", 0x0115: "SamplesPerPixel", 0x0116: "RowsPerStrip", 0x0117: "StripByteCounts", 0x011A: "XResolution", 0x011B: "YResolution", 0x011C: "PlanarConfiguration", 0x0128: "ResolutionUnit", 0x012D: "TransferFunction", 0x0131: "Software", 0x0132: "DateTime", 0x013B: "Artist", 0x013E: "WhitePoint", 0x013F: "PrimaryChromaticities", 0x0156: "TransferRange", 0x0200: "JPEGProc", 0x0201: "JPEGInterchangeFormat", 0x0202: "JPEGInterchangeFormatLength", 0x0211: "YCbCrCoefficients", 0x0212: "YCbCrSubSampling", 0x0213: "YCbCrPositioning", 0x0214: "ReferenceBlackWhite", 0x828F: "BatteryLevel", 0x8298: "Copyright", 0x829A: "ExposureTime", 0x829D: "FNumber", 0x83BB: "IPTC/NAA", 0x8769: "ExifIFDPointer", 0x8773: "InterColorProfile", 0x8822: "ExposureProgram", 0x8824: "SpectralSensitivity", 0x8825: "GPSInfoIFDPointer", 0x8827: "ISOSpeedRatings", 0x8828: "OECF", 0x9000: "ExifVersion", 0x9003: "DateTimeOriginal", 0x9004: "DateTimeDigitized", 0x9101: "ComponentsConfiguration", 0x9102: "CompressedBitsPerPixel", 0x9201: "ShutterSpeedValue", 0x9202: "ApertureValue", 0x9203: "BrightnessValue", 0x9204: "ExposureBiasValue", 0x9205: "MaxApertureValue", 0x9206: "SubjectDistance", 0x9207: "MeteringMode", 0x9208: "LightSource", 0x9209: "Flash", 0x920A: "FocalLength", 0x9214: "SubjectArea", 0x927C: "MakerNote", 0x9286: "UserComment", 0x9290: "SubSecTime", 0x9291: "SubSecTimeOriginal", 0x9292: "SubSecTimeDigitized", 0xA000: "FlashPixVersion", 0xA001: "ColorSpace", 0xA002: "PixelXDimension", 0xA003: "PixelYDimension", 0xA004: "RelatedSoundFile", 0xA005: "InteroperabilityIFDPointer", 0xA20B: "FlashEnergy", # 0x920B in TIFF/EP 0xA20C: "SpatialFrequencyResponse", # 0x920C - - 0xA20E: "FocalPlaneXResolution", # 0x920E - - 0xA20F: "FocalPlaneYResolution", # 0x920F - - 0xA210: "FocalPlaneResolutionUnit", # 0x9210 - - 0xA214: "SubjectLocation", # 0x9214 - - 0xA215: "ExposureIndex", # 0x9215 - - 0xA217: "SensingMethod", # 0x9217 - - 0xA300: "FileSource", 0xA301: "SceneType", 0xA302: "CFAPattern", # 0x828E in TIFF/EP 0xA401: "CustomRendered", 0xA402: "ExposureMode", 0xA403: "WhiteBalance", 0xA404: "DigitalZoomRatio", 0xA405: "FocalLengthIn35mmFilm", 0xA406: "SceneCaptureType", 0xA407: "GainControl", 0xA408: "Contrast", 0xA409: "Saturation", 0xA40A: "Sharpness", 0xA40B: "DeviceSettingDescription", 0xA40C: "SubjectDistanceRange", 0xA420: "ImageUniqueID", } INTR_TAGS = { 0x0001: "InteroperabilityIndex", 0x0002: "InteroperabilityVersion", 0x1000: "RelatedImageFileFormat", 0x1001: "RelatedImageWidth", 0x1002: "RelatedImageLength", } GPS_TA0GS = { 0x00: "GPSVersionID", 0x01: "GPSLatitudeRef", 0x02: "GPSLatitude", 0x03: "GPSLongitudeRef", 0x04: "GPSLongitude", 0x05: "GPSAltitudeRef", 0x06: "GPSAltitude", 0x07: "GPSTimeStamp", 0x08: "GPSSatellites", 0x09: "GPSStatus", 0x0A: "GPSMeasureMode", 0x0B: "GPSDOP", 0x0C: "GPSSpeedRef", 0x0D: "GPSSpeed", 0x0E: "GPSTrackRef", 0x0F: "GPSTrack", 0x10: "GPSImgDirectionRef", 0x11: "GPSImgDirection", 0x12: "GPSMapDatum", 0x13: "GPSDestLatitudeRef", 0x14: "GPSDestLatitude", 0x15: "GPSDestLongitudeRef", 0x16: "GPSDestLongitude", 0x17: "GPSDestBearingRef", 0x18: "GPSDestBearing", 0x19: "GPSDestDistanceRef", 0x1A: "GPSDestDistance", 0x1B: "GPSProcessingMethod", 0x1C: "GPSAreaInformation", 0x1D: "GPSDateStamp", 0x1E: "GPSDifferential", } INTEL_ENDIAN = ord("I") MOTOROLA_ENDIAN = ord("M") # About MAX_COUNT: It's possible to have corrupted exif tags where the entry count is way too high # and thus makes us loop, not endlessly, but for heck of a long time for nothing. Therefore, we put # an arbitrary limit on the entry count we'll allow ourselves to read and any IFD reporting more # entries than that will be considered corrupt. MAX_COUNT = 0xFFFF def s2n_motorola(bytes): x = 0 for c in bytes: x = (x << 8) | c return x def s2n_intel(bytes): x = 0 y = 0 for c in bytes: x = x | (c << y) y = y + 8 return x class Fraction: def __init__(self, num, den): self.num = num self.den = den def __repr__(self): return "%d/%d" % (self.num, self.den) class TIFF_file: def __init__(self, data): self.data = data self.endian = data[0] self.s2nfunc = s2n_intel if self.endian == INTEL_ENDIAN else s2n_motorola def s2n(self, offset, length, signed=0, debug=False): data_slice = self.data[offset : offset + length] val = self.s2nfunc(data_slice) # Sign extension ? if signed: msb = 1 << (8 * length - 1) if val & msb: val = val - (msb << 1) if debug: logging.debug(self.endian) logging.debug( "Slice for offset %d length %d: %r and value: %d", offset, length, data_slice, val, ) return val def first_IFD(self): return self.s2n(4, 4) def next_IFD(self, ifd): entries = self.s2n(ifd, 2) return self.s2n(ifd + 2 + 12 * entries, 4) def list_IFDs(self): i = self.first_IFD() a = [] while i: a.append(i) i = self.next_IFD(i) return a def dump_IFD(self, ifd): entries = self.s2n(ifd, 2) logging.debug("Entries for IFD %d: %d", ifd, entries) if entries > MAX_COUNT: logging.debug("Probably corrupt. Aborting.") return [] a = [] for i in range(entries): entry = ifd + 2 + 12 * i tag = self.s2n(entry, 2) entry_type = self.s2n(entry + 2, 2) if not 1 <= entry_type <= 10: continue # not handled typelen = [1, 1, 2, 4, 8, 1, 1, 2, 4, 8][entry_type - 1] count = self.s2n(entry + 4, 4) if count > MAX_COUNT: logging.debug("Probably corrupt. Aborting.") return [] offset = entry + 8 if count * typelen > 4: offset = self.s2n(offset, 4) if entry_type == 2: # Special case: nul-terminated ASCII string values = str(self.data[offset : offset + count - 1], encoding="latin-1") else: values = [] signed = entry_type == 6 or entry_type >= 8 for _ in range(count): if entry_type in {5, 10}: # The type is either 5 or 10 value_j = Fraction(self.s2n(offset, 4, signed), self.s2n(offset + 4, 4, signed)) else: # Not a fraction value_j = self.s2n(offset, typelen, signed) values.append(value_j) offset = offset + typelen # Now "values" is either a string or an array a.append((tag, entry_type, values)) return a def read_exif_header(fp): # If `fp`'s first bytes are not exif, it tries to find it in the next 4kb def isexif(data): return data[0:4] == b"\377\330\377\341" and data[6:10] == b"Exif" data = fp.read(12) if isexif(data): return data # ok, not exif, try to find it large_data = fp.read(4096) try: index = large_data.index(b"Exif") data = large_data[index - 6 : index + 6] # large_data omits the first 12 bytes, and the index is at the middle of the header, so we # must seek index + 18 fp.seek(index + 18) return data except ValueError: raise ValueError("Not an Exif file") def get_fields(fp): data = read_exif_header(fp) length = data[4] * 256 + data[5] logging.debug("Exif header length: %d bytes", length) data = fp.read(length - 8) data_format = data[0] logging.debug("%s format", {INTEL_ENDIAN: "Intel", MOTOROLA_ENDIAN: "Motorola"}[data_format]) T = TIFF_file(data) # There may be more than one IFD per file, but we only read the first one because others are # most likely thumbnails. main_ifd_offset = T.first_IFD() result = {} def add_tag_to_result(tag, values): try: stag = EXIF_TAGS[tag] except KeyError: stag = "0x%04X" % tag if stag in result: return # don't overwrite data result[stag] = values logging.debug("IFD at offset %d", main_ifd_offset) IFD = T.dump_IFD(main_ifd_offset) exif_off = gps_off = 0 for tag, type, values in IFD: if tag == 0x8769: exif_off = values[0] continue if tag == 0x8825: gps_off = values[0] continue add_tag_to_result(tag, values) if exif_off: logging.debug("Exif SubIFD at offset %d:", exif_off) IFD = T.dump_IFD(exif_off) # Recent digital cameras have a little subdirectory # here, pointed to by tag 0xA005. Apparently, it's the # "Interoperability IFD", defined in Exif 2.1 and DCF. intr_off = 0 for tag, type, values in IFD: if tag == 0xA005: intr_off = values[0] continue add_tag_to_result(tag, values) if intr_off: logging.debug("Exif Interoperability SubSubIFD at offset %d:", intr_off) IFD = T.dump_IFD(intr_off) for tag, type, values in IFD: add_tag_to_result(tag, values) if gps_off: logging.debug("GPS SubIFD at offset %d:", gps_off) IFD = T.dump_IFD(gps_off) for tag, type, values in IFD: add_tag_to_result(tag, values) return result
10,920
Python
.py
318
26.899371
104
0.600908
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,132
cache_sqlite.py
arsenetar_dupeguru/core/pe/cache_sqlite.py
# Copyright 2016 Virgil Dupras # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import os import os.path as op import logging import sqlite3 as sqlite from core.pe.cache import bytes_to_colors, colors_to_bytes class SqliteCache: """A class to cache picture blocks in a sqlite backend.""" schema_version = 2 schema_version_description = "Added blocks for all 8 orientations." create_table_query = ( "CREATE TABLE IF NOT EXISTS " "pictures(path TEXT, mtime_ns INTEGER, blocks BLOB, blocks2 BLOB, blocks3 BLOB, " "blocks4 BLOB, blocks5 BLOB, blocks6 BLOB, blocks7 BLOB, blocks8 BLOB)" ) create_index_query = "CREATE INDEX IF NOT EXISTS idx_path on pictures (path)" drop_table_query = "DROP TABLE IF EXISTS pictures" drop_index_query = "DROP INDEX IF EXISTS idx_path" def __init__(self, db=":memory:", readonly=False): # readonly is not used in the sqlite version of the cache self.dbname = db self.con = None self._create_con() def __contains__(self, key): sql = "select count(*) from pictures where path = ?" result = self.con.execute(sql, [key]).fetchall() return result[0][0] > 0 def __delitem__(self, key): if key not in self: raise KeyError(key) sql = "delete from pictures where path = ?" self.con.execute(sql, [key]) # Optimized def __getitem__(self, key): if isinstance(key, int): sql = ( "select blocks, blocks2, blocks3, blocks4, blocks5, blocks6, blocks7, blocks8 " "from pictures " "where rowid = ?" ) else: sql = ( "select blocks, blocks2, blocks3, blocks4, blocks5, blocks6, blocks7, blocks8 " "from pictures " "where path = ?" ) blocks = self.con.execute(sql, [key]).fetchone() if blocks: result = [bytes_to_colors(block) for block in blocks] return result else: raise KeyError(key) def __iter__(self): sql = "select path from pictures" result = self.con.execute(sql) return (row[0] for row in result) def __len__(self): sql = "select count(*) from pictures" result = self.con.execute(sql).fetchall() return result[0][0] def __setitem__(self, path_str, blocks): blocks = [colors_to_bytes(block) for block in blocks] if op.exists(path_str): mtime = int(os.stat(path_str).st_mtime) else: mtime = 0 if path_str in self: sql = ( "update pictures set blocks = ?, blocks2 = ?, blocks3 = ?, blocks4 = ?, blocks5 = ?, blocks6 = ?, " "blocks7 = ?, blocks8 = ?, mtime_ns = ?" "where path = ?" ) else: sql = ( "insert into pictures(blocks,blocks2,blocks3,blocks4,blocks5,blocks6,blocks7,blocks8,mtime_ns,path) " "values(?,?,?,?,?,?,?,?,?,?)" ) try: self.con.execute(sql, blocks + [mtime, path_str]) except sqlite.OperationalError: logging.warning("Picture cache could not set value for key %r", path_str) except sqlite.DatabaseError as e: logging.warning("DatabaseError while setting value for key %r: %s", path_str, str(e)) def _create_con(self, second_try=False): try: self.con = sqlite.connect(self.dbname, isolation_level=None) self._check_upgrade() except sqlite.DatabaseError as e: # corrupted db if second_try: raise # Something really strange is happening logging.warning("Could not create picture cache because of an error: %s", str(e)) self.con.close() os.remove(self.dbname) self._create_con(second_try=True) def _check_upgrade(self) -> None: with self.con as conn: has_schema = conn.execute( "SELECT NAME FROM sqlite_master WHERE type='table' AND name='schema_version'" ).fetchall() version = None if has_schema: version = conn.execute("SELECT version FROM schema_version ORDER BY version DESC").fetchone()[0] else: conn.execute("CREATE TABLE schema_version (version int PRIMARY KEY, description TEXT)") if version != self.schema_version: conn.execute(self.drop_table_query) conn.execute( "INSERT OR REPLACE INTO schema_version VALUES (:version, :description)", {"version": self.schema_version, "description": self.schema_version_description}, ) conn.execute(self.create_table_query) conn.execute(self.create_index_query) def clear(self): self.close() if self.dbname != ":memory:": os.remove(self.dbname) self._create_con() def close(self): if self.con is not None: self.con.close() self.con = None def filter(self, func): to_delete = [key for key in self if not func(key)] for key in to_delete: del self[key] def get_id(self, path): sql = "select rowid from pictures where path = ?" result = self.con.execute(sql, [path]).fetchone() if result: return result[0] else: raise ValueError(path) def get_multiple(self, rowids): ids = ",".join(map(str, rowids)) sql = ( "select rowid, blocks, blocks2, blocks3, blocks4, blocks5, blocks6, blocks7, blocks8 " f"from pictures where rowid in ({ids})" ) cur = self.con.execute(sql) return ( ( rowid, [ bytes_to_colors(blocks), bytes_to_colors(blocks2), bytes_to_colors(blocks3), bytes_to_colors(blocks4), bytes_to_colors(blocks5), bytes_to_colors(blocks6), bytes_to_colors(blocks7), bytes_to_colors(blocks8), ], ) for rowid, blocks, blocks2, blocks3, blocks4, blocks5, blocks6, blocks7, blocks8 in cur ) def purge_outdated(self): """Go through the cache and purge outdated records. A record is outdated if the picture doesn't exist or if its mtime is greater than the one in the db. """ todelete = [] sql = "select rowid, path, mtime_ns from pictures" cur = self.con.execute(sql) for rowid, path_str, mtime_ns in cur: if mtime_ns and op.exists(path_str): picture_mtime = os.stat(path_str).st_mtime if int(picture_mtime) <= mtime_ns: # not outdated continue todelete.append(rowid) if todelete: sql = "delete from pictures where rowid in (%s)" % ",".join(map(str, todelete)) self.con.execute(sql)
7,379
Python
.py
177
30.711864
117
0.565738
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,133
cache.pyi
arsenetar_dupeguru/core/pe/cache.pyi
from typing import Union, Tuple, List _block = Tuple[int, int, int] def colors_to_bytes(colors: List[_block]) -> bytes: ... # noqa: E302 def bytes_to_colors(s: bytes) -> Union[List[_block], None]: ...
204
Python
.py
4
49.5
69
0.671717
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,134
block.pyi
arsenetar_dupeguru/core/pe/block.pyi
from typing import Tuple, List, Union, Sequence _block = Tuple[int, int, int] class NoBlocksError(Exception): ... # noqa: E302, E701 class DifferentBlockCountError(Exception): ... # noqa E701 def getblock(image: object) -> Union[_block, None]: ... # noqa: E302 def getblocks2(image: object, block_count_per_side: int) -> Union[List[_block], None]: ... def diff(first: _block, second: _block) -> int: ... def avgdiff( # noqa: E302 first: Sequence[_block], second: Sequence[_block], limit: int = 768, min_iterations: int = 1 ) -> Union[int, None]: ...
561
Python
.py
10
54.4
96
0.682482
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,135
matchblock.py
arsenetar_dupeguru/core/pe/matchblock.py
# Created By: Virgil Dupras # Created On: 2007/02/25 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import logging import multiprocessing from itertools import combinations from hscommon.util import extract, iterconsume from hscommon.trans import tr from hscommon.jobprogress import job from core.engine import Match from core.pe.block import avgdiff, DifferentBlockCountError, NoBlocksError from core.pe.cache_sqlite import SqliteCache # OPTIMIZATION NOTES: # The bottleneck of the matching phase is CPU, which is why we use multiprocessing. However, another # bottleneck that shows up when a lot of pictures are involved is Disk IO's because blocks # constantly have to be read from disks by subprocesses. This problem is especially big on CPUs # with a lot of cores. Therefore, we must minimize Disk IOs. The best way to achieve that is to # separate the files to scan in "chunks" and it's by chunk that blocks are read in memory and # compared to each other. Each file in a chunk has to be compared to each other, of course, but also # to files in other chunks. So chunkifying doesn't save us any actual comparison, but the advantage # is that instead of reading blocks from disk number_of_files**2 times, we read it # number_of_files*number_of_chunks times. # Determining the right chunk size is tricky, because if it's too big, too many blocks will be in # memory at the same time and we might end up with memory trashing, which is awfully slow. So, # because our *real* bottleneck is CPU, the chunk size must simply be enough so that the CPU isn't # starved by Disk IOs. MIN_ITERATIONS = 3 BLOCK_COUNT_PER_SIDE = 15 DEFAULT_CHUNK_SIZE = 1000 MIN_CHUNK_SIZE = 100 # Enough so that we're sure that the main thread will not wait after a result.get() call # cpucount+1 should be enough to be sure that the spawned process will not wait after the results # collection made by the main process. try: RESULTS_QUEUE_LIMIT = multiprocessing.cpu_count() + 1 except Exception: # I had an IOError on app launch once. It seems to be a freak occurrence. In any case, we want # the app to launch, so let's just put an arbitrary value. logging.warning("Had problems to determine cpu count on launch.") RESULTS_QUEUE_LIMIT = 8 def get_cache(cache_path, readonly=False): return SqliteCache(cache_path, readonly=readonly) def prepare_pictures(pictures, cache_path, with_dimensions, match_rotated, j=job.nulljob): # The MemoryError handlers in there use logging without first caring about whether or not # there is enough memory left to carry on the operation because it is assumed that the # MemoryError happens when trying to read an image file, which is freed from memory by the # time that MemoryError is raised. cache = get_cache(cache_path) cache.purge_outdated() prepared = [] # only pictures for which there was no error getting blocks try: for picture in j.iter_with_progress(pictures, tr("Analyzed %d/%d pictures")): if not picture.path: # XXX Find the root cause of this. I've received reports of crashes where we had # "Analyzing picture at " (without a path) in the debug log. It was an iPhoto scan. # For now, I'm simply working around the crash by ignoring those, but it would be # interesting to know exactly why this happens. I'm suspecting a malformed # entry in iPhoto library. logging.warning("We have a picture with a null path here") continue logging.debug("Analyzing picture at %s", picture.unicode_path) if with_dimensions: picture.dimensions # pre-read dimensions try: if picture.unicode_path not in cache or ( match_rotated and any(block == [] for block in cache[picture.unicode_path]) ): if match_rotated: blocks = [picture.get_blocks(BLOCK_COUNT_PER_SIDE, orientation) for orientation in range(1, 9)] else: blocks = [[]] * 8 blocks[max(picture.get_orientation() - 1, 0)] = picture.get_blocks(BLOCK_COUNT_PER_SIDE) cache[picture.unicode_path] = blocks prepared.append(picture) except (OSError, ValueError) as e: logging.warning(str(e)) except MemoryError: logging.warning( "Ran out of memory while reading %s of size %d", picture.unicode_path, picture.size, ) if picture.size < 10 * 1024 * 1024: # We're really running out of memory raise except MemoryError: logging.warning("Ran out of memory while preparing pictures") cache.close() return prepared def get_chunks(pictures): min_chunk_count = multiprocessing.cpu_count() * 2 # have enough chunks to feed all subprocesses chunk_count = len(pictures) // DEFAULT_CHUNK_SIZE chunk_count = max(min_chunk_count, chunk_count) chunk_size = (len(pictures) // chunk_count) + 1 chunk_size = max(MIN_CHUNK_SIZE, chunk_size) logging.info( "Creating %d chunks with a chunk size of %d for %d pictures", chunk_count, chunk_size, len(pictures), ) chunks = [pictures[i : i + chunk_size] for i in range(0, len(pictures), chunk_size)] return chunks def get_match(first, second, percentage): if percentage < 0: percentage = 0 return Match(first, second, percentage) def async_compare(ref_ids, other_ids, dbname, threshold, picinfo, match_rotated=False): # The list of ids in ref_ids have to be compared to the list of ids in other_ids. other_ids # can be None. In this case, ref_ids has to be compared with itself # picinfo is a dictionary {pic_id: (dimensions, is_ref)} cache = get_cache(dbname, readonly=True) limit = 100 - threshold ref_pairs = list(cache.get_multiple(ref_ids)) # (rowid, [b, b2, ..., b8]) if other_ids is not None: other_pairs = list(cache.get_multiple(other_ids)) comparisons_to_do = [(r, o) for r in ref_pairs for o in other_pairs] else: comparisons_to_do = list(combinations(ref_pairs, 2)) results = [] for (ref_id, ref_blocks), (other_id, other_blocks) in comparisons_to_do: ref_dimensions, ref_is_ref = picinfo[ref_id] other_dimensions, other_is_ref = picinfo[other_id] if ref_is_ref and other_is_ref: continue if ref_dimensions != other_dimensions: if match_rotated: rotated_ref_dimensions = (ref_dimensions[1], ref_dimensions[0]) if rotated_ref_dimensions != other_dimensions: continue else: continue orientation_range = 1 if match_rotated: orientation_range = 8 for orientation_ref in range(orientation_range): try: diff = avgdiff(ref_blocks[orientation_ref], other_blocks[0], limit, MIN_ITERATIONS) percentage = 100 - diff except (DifferentBlockCountError, NoBlocksError): percentage = 0 if percentage >= threshold: results.append((ref_id, other_id, percentage)) break cache.close() return results def getmatches(pictures, cache_path, threshold, match_scaled=False, match_rotated=False, j=job.nulljob): def get_picinfo(p): if match_scaled: return ((None, None), p.is_ref) else: return (p.dimensions, p.is_ref) def collect_results(collect_all=False): # collect results and wait until the queue is small enough to accomodate a new results. nonlocal async_results, matches, comparison_count, comparisons_to_do limit = 0 if collect_all else RESULTS_QUEUE_LIMIT while len(async_results) > limit: ready, working = extract(lambda r: r.ready(), async_results) for result in ready: matches += result.get() async_results.remove(result) comparison_count += 1 # About the NOQA below: I think there's a bug in pyflakes. To investigate... progress_msg = tr("Performed %d/%d chunk matches") % ( comparison_count, len(comparisons_to_do), ) # NOQA j.set_progress(comparison_count, progress_msg) j = j.start_subjob([3, 7]) pictures = prepare_pictures(pictures, cache_path, not match_scaled, match_rotated, j=j) j = j.start_subjob([9, 1], tr("Preparing for matching")) cache = get_cache(cache_path) id2picture = {} for picture in pictures: try: picture.cache_id = cache.get_id(picture.unicode_path) id2picture[picture.cache_id] = picture except ValueError: pass cache.close() pictures = [p for p in pictures if hasattr(p, "cache_id")] pool = multiprocessing.Pool() async_results = [] matches = [] chunks = get_chunks(pictures) # We add a None element at the end of the chunk list because each chunk has to be compared # with itself. Thus, each chunk will show up as a ref_chunk having other_chunk set to None once. comparisons_to_do = list(combinations(chunks + [None], 2)) comparison_count = 0 j.start_job(len(comparisons_to_do)) try: for ref_chunk, other_chunk in comparisons_to_do: picinfo = {p.cache_id: get_picinfo(p) for p in ref_chunk} ref_ids = [p.cache_id for p in ref_chunk] if other_chunk is not None: other_ids = [p.cache_id for p in other_chunk] picinfo.update({p.cache_id: get_picinfo(p) for p in other_chunk}) else: other_ids = None args = (ref_ids, other_ids, cache_path, threshold, picinfo, match_rotated) async_results.append(pool.apply_async(async_compare, args)) collect_results() collect_results(collect_all=True) except MemoryError: # Rare, but possible, even in 64bit situations (ref #264). What do we do now? We free us # some wiggle room, log about the incident, and stop matching right here. We then process # the matches we have. The rest of the process doesn't allocate much and we should be # alright. del ( comparisons_to_do, chunks, pictures, ) # some wiggle room for the next statements logging.warning("Ran out of memory when scanning! We had %d matches.", len(matches)) del matches[-len(matches) // 3 :] # some wiggle room to ensure we don't run out of memory again. pool.close() result = [] myiter = j.iter_with_progress( iterconsume(matches, reverse=False), tr("Verified %d/%d matches"), every=10, count=len(matches), ) for ref_id, other_id, percentage in myiter: ref = id2picture[ref_id] other = id2picture[other_id] if percentage == 100 and ref.digest != other.digest: percentage = 99 if percentage >= threshold: ref.dimensions # pre-read dimensions for display in results other.dimensions result.append(get_match(ref, other, percentage)) pool.join() return result multiprocessing.freeze_support()
11,751
Python
.py
238
40.722689
119
0.652333
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,136
block.py
arsenetar_dupeguru/core/pe/block.py
# Created By: Virgil Dupras # Created On: 2006/09/01 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from core.pe._block import NoBlocksError, DifferentBlockCountError, avgdiff, getblocks2 # NOQA # Converted to C # def getblock(image): # """Returns a 3 sized tuple containing the mean color of 'image'. # # image: a PIL image or crop. # """ # if image.size[0]: # pixel_count = image.size[0] * image.size[1] # red = green = blue = 0 # for r,g,b in image.getdata(): # red += r # green += g # blue += b # return (red // pixel_count, green // pixel_count, blue // pixel_count) # else: # return (0,0,0) # This is not used anymore # def getblocks(image,blocksize): # """Returns a list of blocks (3 sized tuples). # # image: A PIL image to base the blocks on. # blocksize: The size of the blocks to be create. This is a single integer, defining # both width and height (blocks are square). # """ # if min(image.size) < blocksize: # return () # result = [] # for i in xrange(image.size[1] // blocksize): # for j in xrange(image.size[0] // blocksize): # box = (blocksize * j, blocksize * i, blocksize * (j + 1), blocksize * (i + 1)) # crop = image.crop(box) # result.append(getblock(crop)) # return result # Converted to C # def getblocks2(image,block_count_per_side): # """Returns a list of blocks (3 sized tuples). # # image: A PIL image to base the blocks on. # block_count_per_side: This integer determine the number of blocks the function will return. # If it is 10, for example, 100 blocks will be returns (10 width, 10 height). The blocks will not # necessarely cover square areas. The area covered by each block will be proportional to the image # itself. # """ # if not image.size[0]: # return [] # width,height = image.size # block_width = max(width // block_count_per_side,1) # block_height = max(height // block_count_per_side,1) # result = [] # for ih in range(block_count_per_side): # top = min(ih * block_height, height - block_height) # bottom = top + block_height # for iw in range(block_count_per_side): # left = min(iw * block_width, width - block_width) # right = left + block_width # box = (left,top,right,bottom) # crop = image.crop(box) # result.append(getblock(crop)) # return result # Converted to C # def diff(first, second): # """Returns the difference between the first block and the second. # # It returns an absolute sum of the 3 differences (RGB). # """ # r1, g1, b1 = first # r2, g2, b2 = second # return abs(r1 - r2) + abs(g1 - g2) + abs(b1 - b2) # Converted to C # def avgdiff(first, second, limit=768, min_iterations=1): # """Returns the average diff between first blocks and seconds. # # If the result surpasses limit, limit + 1 is returned, except if less than min_iterations # iterations have been made in the blocks. # """ # if len(first) != len(second): # raise DifferentBlockCountError # if not first: # raise NoBlocksError # count = len(first) # sum = 0 # zipped = izip(xrange(1, count + 1), first, second) # for i, first, second in zipped: # sum += diff(first, second) # if sum > limit * i and i >= min_iterations: # return limit + 1 # result = sum // count # if (not result) and sum: # result = 1 # return result # This is not used anymore # def maxdiff(first,second,limit=768): # """Returns the max diff between first blocks and seconds. # # If the result surpasses limit, the first max being over limit is returned. # """ # if len(first) != len(second): # raise DifferentBlockCountError # if not first: # raise NoBlocksError # result = 0 # zipped = zip(first,second) # for first,second in zipped: # result = max(result,diff(first,second)) # if result > limit: # return result # return result
4,409
Python
.py
115
37.278261
102
0.62118
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,137
cache.py
arsenetar_dupeguru/core/pe/cache.py
# Copyright 2016 Virgil Dupras # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from core.pe._cache import bytes_to_colors # noqa def colors_to_bytes(colors): """Transform the 3 sized tuples 'colors' into a bytes string. [(0,100,255)] --> b'\x00d\xff' [(1,2,3),(4,5,6)] --> b'\x01\x02\x03\x04\x05\x06' """ return b"".join(map(bytes, colors))
531
Python
.py
12
41.25
89
0.693204
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,138
prioritize.py
arsenetar_dupeguru/core/pe/prioritize.py
# Created On: 2011/09/16 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.trans import trget from core.prioritize import ( KindCategory, FolderCategory, FilenameCategory, NumericalCategory, SizeCategory, MtimeCategory, ) coltr = trget("columns") class DimensionsCategory(NumericalCategory): NAME = coltr("Dimensions") def extract_value(self, dupe): return dupe.dimensions def invert_numerical_value(self, value): width, height = value return (-width, -height) def all_categories(): return [ KindCategory, FolderCategory, FilenameCategory, SizeCategory, DimensionsCategory, MtimeCategory, ]
956
Python
.py
32
24.96875
89
0.714754
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,139
__init__.py
arsenetar_dupeguru/core/pe/__init__.py
from core.pe import ( # noqa block, cache, exif, matchblock, matchexif, photo, prioritize, result_table, scanner, )
153
Python
.py
11
9.636364
29
0.605634
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,140
matchexif.py
arsenetar_dupeguru/core/pe/matchexif.py
# Created By: Virgil Dupras # Created On: 2011-04-20 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from collections import defaultdict from itertools import combinations from hscommon.trans import tr from core.engine import Match def getmatches(files, match_scaled, j): timestamp2pic = defaultdict(set) for picture in j.iter_with_progress(files, tr("Read EXIF of %d/%d pictures")): timestamp = picture.exif_timestamp if timestamp: timestamp2pic[timestamp].add(picture) if "0000:00:00 00:00:00" in timestamp2pic: # very likely false matches del timestamp2pic["0000:00:00 00:00:00"] matches = [] for pictures in timestamp2pic.values(): for p1, p2 in combinations(pictures, 2): if (not match_scaled) and (p1.dimensions != p2.dimensions): continue matches.append(Match(p1, p2, 100)) return matches
1,138
Python
.py
26
38.423077
89
0.71093
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,141
scanner.py
arsenetar_dupeguru/core/pe/scanner.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.trans import tr from core.scanner import Scanner, ScanType, ScanOption from core.pe import matchblock, matchexif class ScannerPE(Scanner): cache_path = None match_scaled = False match_rotated = False @staticmethod def get_scan_options(): return [ ScanOption(ScanType.FUZZYBLOCK, tr("Contents")), ScanOption(ScanType.EXIFTIMESTAMP, tr("EXIF Timestamp")), ] def _getmatches(self, files, j): if self.scan_type == ScanType.FUZZYBLOCK: return matchblock.getmatches( files, cache_path=self.cache_path, threshold=self.min_match_percentage, match_scaled=self.match_scaled, match_rotated=self.match_rotated, j=j, ) elif self.scan_type == ScanType.EXIFTIMESTAMP: return matchexif.getmatches(files, self.match_scaled, j) else: raise ValueError("Invalid scan type")
1,283
Python
.py
32
31.625
89
0.654341
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,142
photo.py
arsenetar_dupeguru/core/pe/photo.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import logging from hscommon.util import get_file_ext, format_size from core.util import format_timestamp, format_perc, format_dupe_count from core import fs from core.pe import exif # This global value is set by the platform-specific subclasser of the Photo base class PLAT_SPECIFIC_PHOTO_CLASS = None def format_dimensions(dimensions): return "%d x %d" % (dimensions[0], dimensions[1]) def get_delta_dimensions(value, ref_value): return (value[0] - ref_value[0], value[1] - ref_value[1]) class Photo(fs.File): INITIAL_INFO = fs.File.INITIAL_INFO.copy() INITIAL_INFO.update({"dimensions": (0, 0), "exif_timestamp": ""}) __slots__ = fs.File.__slots__ + tuple(INITIAL_INFO.keys()) # These extensions are supported on all platforms HANDLED_EXTS = {"png", "jpg", "jpeg", "gif", "bmp", "tiff", "tif", "webp"} def _plat_get_dimensions(self): raise NotImplementedError() def _plat_get_blocks(self, block_count_per_side, orientation): raise NotImplementedError() def get_orientation(self): if not hasattr(self, "_cached_orientation"): try: with self.path.open("rb") as fp: exifdata = exif.get_fields(fp) # the value is a list (probably one-sized) of ints orientations = exifdata["Orientation"] self._cached_orientation = orientations[0] except Exception: # Couldn't read EXIF data, no transforms self._cached_orientation = 0 return self._cached_orientation def _get_exif_timestamp(self): try: with self.path.open("rb") as fp: exifdata = exif.get_fields(fp) return exifdata["DateTimeOriginal"] except Exception: logging.info("Couldn't read EXIF of picture: %s", self.path) return "" @classmethod def can_handle(cls, path): return fs.File.can_handle(path) and get_file_ext(path.name) in cls.HANDLED_EXTS def get_display_info(self, group, delta): size = self.size mtime = self.mtime dimensions = self.dimensions m = group.get_match_of(self) if m: percentage = m.percentage dupe_count = 0 if delta: r = group.ref size -= r.size mtime -= r.mtime dimensions = get_delta_dimensions(dimensions, r.dimensions) else: percentage = group.percentage dupe_count = len(group.dupes) dupe_folder_path = getattr(self, "display_folder_path", self.folder_path) return { "name": self.name, "folder_path": str(dupe_folder_path), "size": format_size(size, 0, 1, False), "extension": self.extension, "dimensions": format_dimensions(dimensions), "exif_timestamp": self.exif_timestamp, "mtime": format_timestamp(mtime, delta and m), "percentage": format_perc(percentage), "dupe_count": format_dupe_count(dupe_count), } def _read_info(self, field): fs.File._read_info(self, field) if field == "dimensions": self.dimensions = self._plat_get_dimensions() if self.get_orientation() in {5, 6, 7, 8}: self.dimensions = (self.dimensions[1], self.dimensions[0]) elif field == "exif_timestamp": self.exif_timestamp = self._get_exif_timestamp() def get_blocks(self, block_count_per_side, orientation: int = None): if orientation is None: return self._plat_get_blocks(block_count_per_side, self.get_orientation()) else: return self._plat_get_blocks(block_count_per_side, orientation)
4,075
Python
.py
89
36.269663
89
0.618952
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,143
result_table.py
arsenetar_dupeguru/core/pe/result_table.py
# Created On: 2011-11-27 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.gui.column import Column from hscommon.trans import trget from core.gui.result_table import ResultTable as ResultTableBase coltr = trget("columns") class ResultTable(ResultTableBase): COLUMNS = [ Column("marked", ""), Column("name", coltr("Filename")), Column("folder_path", coltr("Folder"), optional=True), Column("size", coltr("Size (KB)"), optional=True), Column("extension", coltr("Kind"), visible=False, optional=True), Column("dimensions", coltr("Dimensions"), optional=True), Column("exif_timestamp", coltr("EXIF Timestamp"), visible=False, optional=True), Column("mtime", coltr("Modification"), visible=False, optional=True), Column("percentage", coltr("Match %"), optional=True), Column("dupe_count", coltr("Dupe Count"), visible=False, optional=True), ] DELTA_COLUMNS = {"size", "dimensions", "mtime"}
1,224
Python
.py
24
45.958333
89
0.696234
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,144
fs.py
arsenetar_dupeguru/core/me/fs.py
# Created By: Virgil Dupras # Created On: 2009-10-23 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import mutagen from hscommon.util import get_file_ext, format_size, format_time from core.util import format_timestamp, format_perc, format_words, format_dupe_count from core import fs TAG_FIELDS = { "audiosize", "duration", "bitrate", "samplerate", "title", "artist", "album", "genre", "year", "track", "comment", } # This is a temporary workaround for migration from hsaudiotag for the can_handle method SUPPORTED_EXTS = {"mp3", "wma", "m4a", "m4p", "ogg", "flac", "aif", "aiff", "aifc"} class MusicFile(fs.File): INITIAL_INFO = fs.File.INITIAL_INFO.copy() INITIAL_INFO.update( { "audiosize": 0, "bitrate": 0, "duration": 0, "samplerate": 0, "artist": "", "album": "", "title": "", "genre": "", "comment": "", "year": "", "track": 0, } ) __slots__ = fs.File.__slots__ + tuple(INITIAL_INFO.keys()) @classmethod def can_handle(cls, path): if not fs.File.can_handle(path): return False return get_file_ext(path.name) in SUPPORTED_EXTS def get_display_info(self, group, delta): size = self.size duration = self.duration bitrate = self.bitrate samplerate = self.samplerate mtime = self.mtime m = group.get_match_of(self) if m: percentage = m.percentage dupe_count = 0 if delta: r = group.ref size -= r.size duration -= r.duration bitrate -= r.bitrate samplerate -= r.samplerate mtime -= r.mtime else: percentage = group.percentage dupe_count = len(group.dupes) dupe_folder_path = getattr(self, "display_folder_path", self.folder_path) return { "name": self.name, "folder_path": str(dupe_folder_path), "size": format_size(size, 2, 2, False), "duration": format_time(duration, with_hours=False), "bitrate": str(bitrate), "samplerate": str(samplerate), "extension": self.extension, "mtime": format_timestamp(mtime, delta and m), "title": self.title, "artist": self.artist, "album": self.album, "genre": self.genre, "year": self.year, "track": str(self.track), "comment": self.comment, "percentage": format_perc(percentage), "words": format_words(self.words) if hasattr(self, "words") else "", "dupe_count": format_dupe_count(dupe_count), } def _read_info(self, field): fs.File._read_info(self, field) if field in TAG_FIELDS: # The various conversions here are to make this look like the previous implementation file = mutagen.File(str(self.path), easy=True) self.audiosize = self.path.stat().st_size self.bitrate = file.info.bitrate / 1000 self.duration = file.info.length self.samplerate = file.info.sample_rate self.artist = ", ".join(file.tags.get("artist") or []) self.album = ", ".join(file.tags.get("album") or []) self.title = ", ".join(file.tags.get("title") or []) self.genre = ", ".join(file.tags.get("genre") or []) self.comment = ", ".join(file.tags.get("comment") or [""]) self.year = ", ".join(file.tags.get("date") or []) self.track = (file.tags.get("tracknumber") or [""])[0]
4,008
Python
.py
106
28.386792
97
0.559466
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,145
prioritize.py
arsenetar_dupeguru/core/me/prioritize.py
# Created On: 2011/09/16 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.trans import trget from core.prioritize import ( KindCategory, FolderCategory, FilenameCategory, NumericalCategory, SizeCategory, MtimeCategory, ) coltr = trget("columns") class DurationCategory(NumericalCategory): NAME = coltr("Duration") def extract_value(self, dupe): return dupe.duration class BitrateCategory(NumericalCategory): NAME = coltr("Bitrate") def extract_value(self, dupe): return dupe.bitrate class SamplerateCategory(NumericalCategory): NAME = coltr("Samplerate") def extract_value(self, dupe): return dupe.samplerate def all_categories(): return [ KindCategory, FolderCategory, FilenameCategory, SizeCategory, DurationCategory, BitrateCategory, SamplerateCategory, MtimeCategory, ]
1,173
Python
.py
39
25.025641
89
0.722321
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,146
scanner.py
arsenetar_dupeguru/core/me/scanner.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.trans import tr from core.scanner import Scanner as ScannerBase, ScanOption, ScanType class ScannerME(ScannerBase): @staticmethod def _key_func(dupe): return (-dupe.bitrate, -dupe.size) @staticmethod def get_scan_options(): return [ ScanOption(ScanType.FILENAME, tr("Filename")), ScanOption(ScanType.FIELDS, tr("Filename - Fields")), ScanOption(ScanType.FIELDSNOORDER, tr("Filename - Fields (No Order)")), ScanOption(ScanType.TAG, tr("Tags")), ScanOption(ScanType.CONTENTS, tr("Contents")), ]
913
Python
.py
20
38.15
90
0.677237
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,147
result_table.py
arsenetar_dupeguru/core/me/result_table.py
# Created On: 2011-11-27 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.gui.column import Column from hscommon.trans import trget from core.gui.result_table import ResultTable as ResultTableBase coltr = trget("columns") class ResultTable(ResultTableBase): COLUMNS = [ Column("marked", ""), Column("name", coltr("Filename")), Column("folder_path", coltr("Folder"), visible=False, optional=True), Column("size", coltr("Size (MB)"), optional=True), Column("duration", coltr("Time"), optional=True), Column("bitrate", coltr("Bitrate"), optional=True), Column("samplerate", coltr("Sample Rate"), visible=False, optional=True), Column("extension", coltr("Kind"), optional=True), Column("mtime", coltr("Modification"), visible=False, optional=True), Column("title", coltr("Title"), visible=False, optional=True), Column("artist", coltr("Artist"), visible=False, optional=True), Column("album", coltr("Album"), visible=False, optional=True), Column("genre", coltr("Genre"), visible=False, optional=True), Column("year", coltr("Year"), visible=False, optional=True), Column("track", coltr("Track Number"), visible=False, optional=True), Column("comment", coltr("Comment"), visible=False, optional=True), Column("percentage", coltr("Match %"), optional=True), Column("words", coltr("Words Used"), visible=False, optional=True), Column("dupe_count", coltr("Dupe Count"), visible=False, optional=True), ] DELTA_COLUMNS = {"size", "duration", "bitrate", "samplerate", "mtime"}
1,876
Python
.py
33
50.727273
89
0.676823
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,148
ignore_list_table.py
arsenetar_dupeguru/core/gui/ignore_list_table.py
# Created By: Virgil Dupras # Created On: 2012-03-13 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.gui.table import GUITable, Row from hscommon.gui.column import Column, Columns from hscommon.trans import trget coltr = trget("columns") class IgnoreListTable(GUITable): COLUMNS = [ # the str concat below saves us needless localization. Column("path1", coltr("File Path") + " 1"), Column("path2", coltr("File Path") + " 2"), ] def __init__(self, ignore_list_dialog): GUITable.__init__(self) self._columns = Columns(self) self.view = None self.dialog = ignore_list_dialog # --- Override def _fill(self): for path1, path2 in self.dialog.ignore_list: self.append(IgnoreListRow(self, path1, path2)) class IgnoreListRow(Row): def __init__(self, table, path1, path2): Row.__init__(self, table) self.path1_original = path1 self.path2_original = path2 self.path1 = str(path1) self.path2 = str(path2)
1,283
Python
.py
33
33.393939
89
0.671498
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,149
exclude_list_table.py
arsenetar_dupeguru/core/gui/exclude_list_table.py
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from core.gui.base import DupeGuruGUIObject from hscommon.gui.table import GUITable, Row from hscommon.gui.column import Column, Columns from hscommon.trans import trget tr = trget("ui") class ExcludeListTable(GUITable, DupeGuruGUIObject): COLUMNS = [Column("marked", ""), Column("regex", tr("Regular Expressions"))] def __init__(self, exclude_list_dialog, app): GUITable.__init__(self) DupeGuruGUIObject.__init__(self, app) self._columns = Columns(self) self.dialog = exclude_list_dialog def rename_selected(self, newname): row = self.selected_row if row is None: return False row._data = None return self.dialog.rename_selected(newname) # --- Virtual def _do_add(self, regex): """(Virtual) Creates a new row, adds it in the table. Returns ``(row, insert_index)``.""" # Return index 0 to insert at the top return ExcludeListRow(self, self.dialog.exclude_list.is_marked(regex), regex), 0 def _do_delete(self): self.dialog.exclude_list.remove(self.selected_row.regex) # --- Override def add(self, regex): row, insert_index = self._do_add(regex) self.insert(insert_index, row) self.view.refresh() def _fill(self): for enabled, regex in self.dialog.exclude_list: self.append(ExcludeListRow(self, enabled, regex)) def refresh(self, refresh_view=True): """Override to avoid keeping previous selection in case of multiple rows selected previously.""" self.cancel_edits() del self[:] self._fill() if refresh_view: self.view.refresh() class ExcludeListRow(Row): def __init__(self, table, enabled, regex): Row.__init__(self, table) self._app = table.app self._data = None self.enabled = str(enabled) self.regex = str(regex) self.highlight = False @property def data(self): if self._data is None: self._data = {"marked": self.enabled, "regex": self.regex} return self._data @property def markable(self): return self._app.exclude_list.is_markable(self.regex) @property def marked(self): return self._app.exclude_list.is_marked(self.regex) @marked.setter def marked(self, value): if value: self._app.exclude_list.mark(self.regex) else: self._app.exclude_list.unmark(self.regex) @property def error(self): # This assumes error() returns an Exception() message = self._app.exclude_list.error(self.regex) if hasattr(message, "msg"): return self._app.exclude_list.error(self.regex).msg else: return message # Exception object
3,032
Python
.py
78
31.333333
89
0.641349
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,150
problem_dialog.py
arsenetar_dupeguru/core/gui/problem_dialog.py
# Created By: Virgil Dupras # Created On: 2010-04-12 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon import desktop from core.gui.problem_table import ProblemTable class ProblemDialog: def __init__(self, app): self.app = app self._selected_dupe = None self.problem_table = ProblemTable(self) def refresh(self): self._selected_dupe = None self.problem_table.refresh() def reveal_selected_dupe(self): if self._selected_dupe is not None: desktop.reveal_path(self._selected_dupe.path) def select_dupe(self, dupe): self._selected_dupe = dupe
870
Python
.py
22
34.409091
89
0.707491
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,151
__init__.py
arsenetar_dupeguru/core/gui/__init__.py
""" Meta GUI elements in dupeGuru ----------------------------- dupeGuru is designed with a `cross-toolkit`_ approach in mind. It means that its core code (which doesn't depend on any GUI toolkit) has elements which preformat core information in a way that makes it easy for a UI layer to consume. For example, we have :class:`~core.gui.ResultTable` which takes information from :class:`~core.results.Results` and mashes it in rows and columns which are ready to be fetched by either Cocoa's ``NSTableView`` or Qt's ``QTableView``. It tells them which cell is supposed to be blue, which is supposed to be orange, does the sorting logic, holds selection, etc.. .. _cross-toolkit: http://www.hardcoded.net/articles/cross-toolkit-software """
743
Python
.py
12
60.666667
97
0.748626
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,152
base.py
arsenetar_dupeguru/core/gui/base.py
# Created By: Virgil Dupras # Created On: 2010-02-06 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.notify import Listener class DupeGuruGUIObject(Listener): def __init__(self, app): Listener.__init__(self, app) self.app = app def directories_changed(self): # Implemented in child classes pass def dupes_selected(self): # Implemented in child classes pass def marking_changed(self): # Implemented in child classes pass def results_changed(self): # Implemented in child classes pass def results_changed_but_keep_selection(self): # Implemented in child classes pass
935
Python
.py
27
28.888889
89
0.691111
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,153
prioritize_dialog.py
arsenetar_dupeguru/core/gui/prioritize_dialog.py
# Created By: Virgil Dupras # Created On: 2011-09-06 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.gui.base import GUIObject from hscommon.gui.selectable_list import GUISelectableList class CriterionCategoryList(GUISelectableList): def __init__(self, dialog): self.dialog = dialog GUISelectableList.__init__(self, [c.NAME for c in dialog.categories]) def _update_selection(self): self.dialog.select_category(self.dialog.categories[self.selected_index]) GUISelectableList._update_selection(self) class PrioritizationList(GUISelectableList): def __init__(self, dialog): self.dialog = dialog GUISelectableList.__init__(self) def _refresh_contents(self): self[:] = [crit.display for crit in self.dialog.prioritizations] def move_indexes(self, indexes, dest_index): indexes.sort() prilist = self.dialog.prioritizations selected = [prilist[i] for i in indexes] for i in reversed(indexes): del prilist[i] prilist[dest_index:dest_index] = selected self._refresh_contents() def remove_selected(self): prilist = self.dialog.prioritizations for i in sorted(self.selected_indexes, reverse=True): del prilist[i] self._refresh_contents() class PrioritizeDialog(GUIObject): def __init__(self, app): GUIObject.__init__(self) self.app = app self.categories = [cat(app.results) for cat in app._prioritization_categories()] self.category_list = CriterionCategoryList(self) self.criteria = [] self.criteria_list = GUISelectableList() self.prioritizations = [] self.prioritization_list = PrioritizationList(self) # --- Override def _view_updated(self): self.category_list.select(0) # --- Private def _sort_key(self, dupe): return tuple(crit.sort_key(dupe) for crit in self.prioritizations) # --- Public def select_category(self, category): self.criteria = category.criteria_list() self.criteria_list[:] = [c.display_value for c in self.criteria] def add_selected(self): # Add selected criteria in criteria_list to prioritization_list. if self.criteria_list.selected_index is None: return for i in self.criteria_list.selected_indexes: crit = self.criteria[i] self.prioritizations.append(crit) del crit self.prioritization_list[:] = [crit.display for crit in self.prioritizations] def remove_selected(self): self.prioritization_list.remove_selected() self.prioritization_list.select([]) def perform_reprioritization(self): self.app.reprioritize_groups(self._sort_key)
3,022
Python
.py
69
36.521739
89
0.682902
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,154
stats_label.py
arsenetar_dupeguru/core/gui/stats_label.py
# Created By: Virgil Dupras # Created On: 2010-02-11 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from core.gui.base import DupeGuruGUIObject class StatsLabel(DupeGuruGUIObject): def _view_updated(self): self.view.refresh() @property def display(self): return self.app.stat_line def results_changed(self): self.view.refresh() marking_changed = results_changed
641
Python
.py
17
33.764706
89
0.7411
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,155
deletion_options.py
arsenetar_dupeguru/core/gui/deletion_options.py
# Created On: 2012-05-30 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import os from hscommon.gui.base import GUIObject from hscommon.trans import tr class DeletionOptionsView: """Expected interface for :class:`DeletionOptions`'s view. *Not actually used in the code. For documentation purposes only.* Our view presents the user with an appropriate way (probably a mix of checkboxes and radio buttons) to set the different flags in :class:`DeletionOptions`. Note that :attr:`DeletionOptions.use_hardlinks` is only relevant if :attr:`DeletionOptions.link_deleted` is true. This is why we toggle the "enabled" state of that flag. We expect the view to set :attr:`DeletionOptions.link_deleted` immediately as the user changes its value because it will toggle :meth:`set_hardlink_option_enabled` Other than the flags, there's also a prompt message which has a dynamic content, defined by :meth:`update_msg`. """ def update_msg(self, msg: str): """Update the dialog's prompt with ``str``.""" def show(self): """Show the dialog in a modal fashion. Returns whether the dialog was "accepted" (the user pressed OK). """ def set_hardlink_option_enabled(self, is_enabled: bool): """Enable or disable the widget controlling :attr:`DeletionOptions.use_hardlinks`.""" class DeletionOptions(GUIObject): """Present the user with deletion options before proceeding. When the user activates "Send to trash", we present him with a couple of options that changes the behavior of that deletion operation. """ def __init__(self): GUIObject.__init__(self) #: Whether symlinks or hardlinks are used when doing :attr:`link_deleted`. #: *bool*. *get/set* self.use_hardlinks = False #: Delete dupes directly and don't send to trash. #: *bool*. *get/set* self.direct = False def show(self, mark_count): """Prompt the user with a modal dialog offering our deletion options. :param int mark_count: Number of dupes marked for deletion. :rtype: bool :returns: Whether the user accepted the dialog (we cancel deletion if false). """ self._link_deleted = False self.view.set_hardlink_option_enabled(False) self.use_hardlinks = False self.direct = False msg = tr("You are sending {} file(s) to the Trash.").format(mark_count) self.view.update_msg(msg) return self.view.show() def supports_links(self): """Returns whether our platform supports symlinks.""" # When on a platform that doesn't implement it, calling os.symlink() (with the wrong number # of arguments) raises NotImplementedError, which allows us to gracefully check for the # feature. try: os.symlink() except NotImplementedError: # Windows XP, not supported return False except OSError: # Vista+, symbolic link privilege not held return False except TypeError: # wrong number of arguments return True @property def link_deleted(self): """Replace deleted dupes with symlinks (or hardlinks) to the dupe group reference. *bool*. *get/set* Whether the link is a symlink or hardlink is decided by :attr:`use_hardlinks`. """ return self._link_deleted @link_deleted.setter def link_deleted(self, value): self._link_deleted = value hardlinks_enabled = value and self.supports_links() self.view.set_hardlink_option_enabled(hardlinks_enabled)
3,919
Python
.py
83
39.86747
99
0.679517
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,156
result_table.py
arsenetar_dupeguru/core/gui/result_table.py
# Created By: Virgil Dupras # Created On: 2010-02-11 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from operator import attrgetter from hscommon.gui.table import GUITable, Row from hscommon.gui.column import Columns from core.gui.base import DupeGuruGUIObject class DupeRow(Row): def __init__(self, table, group, dupe): Row.__init__(self, table) self._app = table.app self._group = group self._dupe = dupe self._data = None self._data_delta = None self._delta_columns = None def is_cell_delta(self, column_name): """Returns whether a cell is in delta mode (orange color). If the result table is in delta mode, returns True if the column is one of the "delta columns", that is, one of the columns that display a a differential value rather than an absolute value. If not, returns True if the dupe's value is different from its ref value. """ if not self.table.delta_values: return False if self.isref: return False if self._delta_columns is None: # table.DELTA_COLUMNS are always "delta" self._delta_columns = self.table.DELTA_COLUMNS.copy() dupe_info = self.data if self._group.ref is None: return False ref_info = self._group.ref.get_display_info(group=self._group, delta=False) for key, value in dupe_info.items(): if (key not in self._delta_columns) and (ref_info[key].lower() != value.lower()): self._delta_columns.add(key) return column_name in self._delta_columns @property def data(self): if self._data is None: self._data = self._app.get_display_info(self._dupe, self._group, False) return self._data @property def data_delta(self): if self._data_delta is None: self._data_delta = self._app.get_display_info(self._dupe, self._group, True) return self._data_delta @property def isref(self): return self._dupe is self._group.ref @property def markable(self): return self._app.results.is_markable(self._dupe) @property def marked(self): return self._app.results.is_marked(self._dupe) @marked.setter def marked(self, value): self._app.mark_dupe(self._dupe, value) class ResultTable(GUITable, DupeGuruGUIObject): def __init__(self, app): GUITable.__init__(self) DupeGuruGUIObject.__init__(self, app) self._columns = Columns(self, prefaccess=app, savename="ResultTable") self._power_marker = False self._delta_values = False self._sort_descriptors = ("name", True) # --- Override def _view_updated(self): self._refresh_with_view() def _restore_selection(self, previous_selection): if self.app.selected_dupes: to_find = set(self.app.selected_dupes) indexes = [i for i, r in enumerate(self) if r._dupe in to_find] self.selected_indexes = indexes def _update_selection(self): rows = self.selected_rows self.app._select_dupes(list(map(attrgetter("_dupe"), rows))) def _fill(self): if not self.power_marker: for group in self.app.results.groups: self.append(DupeRow(self, group, group.ref)) for dupe in group.dupes: self.append(DupeRow(self, group, dupe)) else: for dupe in self.app.results.dupes: group = self.app.results.get_group_of_duplicate(dupe) self.append(DupeRow(self, group, dupe)) def _refresh_with_view(self): self.refresh() self.view.show_selected_row() # --- Public def get_row_value(self, index, column): try: row = self[index] except IndexError: return "---" if self.delta_values: return row.data_delta[column] else: return row.data[column] def rename_selected(self, newname): row = self.selected_row if row is None: # There's all kinds of way the current row can be swept off during rename. When it # happens, selected_row will be None. return False row._data = None row._data_delta = None return self.app.rename_selected(newname) def sort(self, key, asc): if self.power_marker: self.app.results.sort_dupes(key, asc, self.delta_values) else: self.app.results.sort_groups(key, asc) self._sort_descriptors = (key, asc) self._refresh_with_view() # --- Properties @property def power_marker(self): return self._power_marker @power_marker.setter def power_marker(self, value): if value == self._power_marker: return self._power_marker = value key, asc = self._sort_descriptors self.sort(key, asc) # no need to refresh, it has happened in sort() @property def delta_values(self): return self._delta_values @delta_values.setter def delta_values(self, value): if value == self._delta_values: return self._delta_values = value self.refresh() @property def selected_dupe_count(self): return sum(1 for row in self.selected_rows if not row.isref) # --- Event Handlers def marking_changed(self): self.view.invalidate_markings() def results_changed(self): self._refresh_with_view() def results_changed_but_keep_selection(self): # What we want to to here is that instead of restoring selected *dupes* after refresh, we # restore selected *paths*. indexes = self.selected_indexes self.refresh(refresh_view=False) self.select(indexes) self.view.refresh() def save_session(self): self._columns.save_columns()
6,256
Python
.py
160
30.46875
97
0.62098
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,157
problem_table.py
arsenetar_dupeguru/core/gui/problem_table.py
# Created By: Virgil Dupras # Created On: 2010-04-12 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.gui.table import GUITable, Row from hscommon.gui.column import Column, Columns from hscommon.trans import trget coltr = trget("columns") class ProblemTable(GUITable): COLUMNS = [ Column("path", coltr("File Path")), Column("msg", coltr("Error Message")), ] def __init__(self, problem_dialog): GUITable.__init__(self) self._columns = Columns(self) self.dialog = problem_dialog # --- Override def _update_selection(self): row = self.selected_row dupe = row.dupe if row is not None else None self.dialog.select_dupe(dupe) def _fill(self): problems = self.dialog.app.results.problems for dupe, msg in problems: self.append(ProblemRow(self, dupe, msg)) class ProblemRow(Row): def __init__(self, table, dupe, msg): Row.__init__(self, table) self.dupe = dupe self.msg = msg self.path = str(dupe.path)
1,297
Python
.py
35
31.457143
89
0.667997
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,158
ignore_list_dialog.py
arsenetar_dupeguru/core/gui/ignore_list_dialog.py
# Created On: 2012/03/13 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.trans import tr from core.gui.ignore_list_table import IgnoreListTable class IgnoreListDialog: # --- View interface # show() # def __init__(self, app): self.app = app self.ignore_list = self.app.ignore_list self.ignore_list_table = IgnoreListTable(self) # GUITable def clear(self): if not self.ignore_list: return msg = tr("Do you really want to remove all %d items from the ignore list?") % len(self.ignore_list) if self.app.view.ask_yes_no(msg): self.ignore_list.clear() self.refresh() def refresh(self): self.ignore_list_table.refresh() def remove_selected(self): for row in self.ignore_list_table.selected_rows: self.ignore_list.remove(row.path1_original, row.path2_original) self.refresh() def show(self): self.view.show()
1,212
Python
.py
31
32.677419
107
0.670077
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,159
details_panel.py
arsenetar_dupeguru/core/gui/details_panel.py
# Created By: Virgil Dupras # Created On: 2010-02-05 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.gui.base import GUIObject from core.gui.base import DupeGuruGUIObject class DetailsPanel(GUIObject, DupeGuruGUIObject): def __init__(self, app): GUIObject.__init__(self, multibind=True) DupeGuruGUIObject.__init__(self, app) self._table = [] def _view_updated(self): self._refresh() self.view.refresh() # --- Private def _refresh(self): if self.app.selected_dupes: dupe = self.app.selected_dupes[0] group = self.app.results.get_group_of_duplicate(dupe) else: dupe = None group = None data1 = self.app.get_display_info(dupe, group, False) # we don't want the two sides of the table to display the stats for the same file ref = group.ref if group is not None and group.ref is not dupe else None data2 = self.app.get_display_info(ref, group, False) columns = self.app.result_table.COLUMNS[1:] # first column is the 'marked' column self._table = [(c.display, data1[c.name], data2[c.name]) for c in columns] # --- Public def row_count(self): return len(self._table) def row(self, row_index): return self._table[row_index] # --- Event Handlers def dupes_selected(self): self._view_updated()
1,648
Python
.py
39
35.615385
90
0.658339
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,160
directory_tree.py
arsenetar_dupeguru/core/gui/directory_tree.py
# Created By: Virgil Dupras # Created On: 2010-02-06 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.gui.tree import Tree, Node from core.directories import DirectoryState from core.gui.base import DupeGuruGUIObject STATE_ORDER = [DirectoryState.NORMAL, DirectoryState.REFERENCE, DirectoryState.EXCLUDED] # Lazily loads children class DirectoryNode(Node): def __init__(self, tree, path, name): Node.__init__(self, name) self._tree = tree self._directory_path = path self._loaded = False self._state = STATE_ORDER.index(self._tree.app.directories.get_state(path)) def __len__(self): if not self._loaded: self._load() return Node.__len__(self) def _load(self): self.clear() subpaths = self._tree.app.directories.get_subfolders(self._directory_path) for path in subpaths: self.append(DirectoryNode(self._tree, path, path.name)) self._loaded = True def update_all_states(self): self._state = STATE_ORDER.index(self._tree.app.directories.get_state(self._directory_path)) for node in self: node.update_all_states() # The state propery is an index to the combobox @property def state(self): return self._state @state.setter def state(self, value): if value == self._state: return self._state = value state = STATE_ORDER[value] self._tree.app.directories.set_state(self._directory_path, state) self._tree.update_all_states() class DirectoryTree(Tree, DupeGuruGUIObject): # --- model -> view calls: # refresh() # refresh_states() # when only states label need to be refreshed # def __init__(self, app): Tree.__init__(self) DupeGuruGUIObject.__init__(self, app) def _view_updated(self): self._refresh() self.view.refresh() def _refresh(self): self.clear() for path in self.app.directories: self.append(DirectoryNode(self, path, str(path))) def add_directory(self, path): self.app.add_directory(path) def remove_selected(self): selected_paths = self.selected_paths if not selected_paths: return to_delete = [path[0] for path in selected_paths if len(path) == 1] if to_delete: self.app.remove_directories(to_delete) else: # All selected nodes or on second-or-more level, exclude them. nodes = self.selected_nodes newstate = DirectoryState.EXCLUDED if all(node.state == DirectoryState.EXCLUDED for node in nodes): newstate = DirectoryState.NORMAL for node in nodes: node.state = newstate def select_all(self): self.selected_nodes = list(self) self.view.refresh() def update_all_states(self): for node in self: node.update_all_states() self.view.refresh_states() # --- Event Handlers def directories_changed(self): self._view_updated()
3,347
Python
.py
87
30.770115
99
0.641469
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,161
exclude_list_dialog.py
arsenetar_dupeguru/core/gui/exclude_list_dialog.py
# Created On: 2012/03/13 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from core.gui.exclude_list_table import ExcludeListTable from core.exclude import has_sep from os import sep import logging class ExcludeListDialogCore: def __init__(self, app): self.app = app self.exclude_list = self.app.exclude_list # Markable from exclude.py self.exclude_list_table = ExcludeListTable(self, app) # GUITable, this is the "model" def restore_defaults(self): self.exclude_list.restore_defaults() self.refresh() def refresh(self): self.exclude_list_table.refresh() def remove_selected(self): for row in self.exclude_list_table.selected_rows: self.exclude_list_table.remove(row) self.exclude_list.remove(row.regex) self.refresh() def rename_selected(self, newregex): """Rename the selected regex to ``newregex``. If there is more than one selected row, the first one is used. :param str newregex: The regex to rename the row's regex to. :return bool: true if success, false if error. """ try: r = self.exclude_list_table.selected_rows[0] self.exclude_list.rename(r.regex, newregex) self.refresh() return True except Exception as e: logging.warning(f"Error while renaming regex to {newregex}: {e}") return False def add(self, regex): self.exclude_list.add(regex) self.exclude_list.mark(regex) self.exclude_list_table.add(regex) def test_string(self, test_string): """Set the highlight property on each row when its regex matches the test_string supplied. Return True if any row matched.""" matched = False for row in self.exclude_list_table.rows: compiled_regex = self.exclude_list.get_compiled(row.regex) if self.is_match(test_string, compiled_regex): row.highlight = True matched = True else: row.highlight = False return matched def is_match(self, test_string, compiled_regex): # This method is like an inverted version of ExcludeList.is_excluded() if not compiled_regex: return False matched = False # Test only the filename portion of the path if not has_sep(compiled_regex.pattern) and sep in test_string: filename = test_string.rsplit(sep, 1)[1] if compiled_regex.fullmatch(filename): matched = True return matched # Test the entire path + filename if compiled_regex.fullmatch(test_string): matched = True return matched def reset_rows_highlight(self): for row in self.exclude_list_table.rows: row.highlight = False def show(self): self.view.show()
3,156
Python
.py
75
33.306667
94
0.645793
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,162
engine_test.py
arsenetar_dupeguru/core/tests/engine_test.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import sys from hscommon.jobprogress import job from hscommon.util import first from hscommon.testutil import eq_, log_calls from core.tests.base import NamedObject from core import engine from core.engine import ( get_match, getwords, Group, getfields, unpack_fields, compare_fields, compare, WEIGHT_WORDS, MATCH_SIMILAR_WORDS, NO_FIELD_ORDER, build_word_dict, get_groups, getmatches, Match, getmatches_by_contents, merge_similar_words, reduce_common_words, ) no = NamedObject def get_match_triangle(): o1 = NamedObject(with_words=True) o2 = NamedObject(with_words=True) o3 = NamedObject(with_words=True) m1 = get_match(o1, o2) m2 = get_match(o1, o3) m3 = get_match(o2, o3) return [m1, m2, m3] def get_test_group(): m1, m2, m3 = get_match_triangle() result = Group() result.add_match(m1) result.add_match(m2) result.add_match(m3) return result def assert_match(m, name1, name2): # When testing matches, whether objects are in first or second position very often doesn't # matter. This function makes this test more convenient. if m.first.name == name1: eq_(m.second.name, name2) else: eq_(m.first.name, name2) eq_(m.second.name, name1) class TestCasegetwords: def test_spaces(self): eq_(["a", "b", "c", "d"], getwords("a b c d")) eq_(["a", "b", "c", "d"], getwords(" a b c d ")) def test_unicode(self): eq_(["e", "c", "0", "a", "o", "u", "e", "u"], getwords("é ç 0 à ö û è ¤ ù")) eq_( ["02", "君のこころは輝いてるかい?", "国木田花丸", "solo", "ver"], getwords("02 君のこころは輝いてるかい? 国木田花丸 Solo Ver"), ) def test_splitter_chars(self): eq_( [chr(i) for i in range(ord("a"), ord("z") + 1)], getwords("a-b_c&d+e(f)g;h\\i[j]k{l}m:n.o,p<q>r/s?t~u!v@w#x$y*z"), ) def test_joiner_chars(self): eq_(["aec"], getwords("a'e\u0301c")) def test_empty(self): eq_([], getwords("")) def test_returns_lowercase(self): eq_(["foo", "bar"], getwords("FOO BAR")) def test_decompose_unicode(self): eq_(["fooebar"], getwords("foo\xe9bar")) class TestCasegetfields: def test_simple(self): eq_([["a", "b"], ["c", "d", "e"]], getfields("a b - c d e")) def test_empty(self): eq_([], getfields("")) def test_cleans_empty_fields(self): expected = [["a", "bc", "def"]] actual = getfields(" - a bc def") eq_(expected, actual) class TestCaseUnpackFields: def test_with_fields(self): expected = ["a", "b", "c", "d", "e", "f"] actual = unpack_fields([["a"], ["b", "c"], ["d", "e", "f"]]) eq_(expected, actual) def test_without_fields(self): expected = ["a", "b", "c", "d", "e", "f"] actual = unpack_fields(["a", "b", "c", "d", "e", "f"]) eq_(expected, actual) def test_empty(self): eq_([], unpack_fields([])) class TestCaseWordCompare: def test_list(self): eq_(100, compare(["a", "b", "c", "d"], ["a", "b", "c", "d"])) eq_(86, compare(["a", "b", "c", "d"], ["a", "b", "c"])) def test_unordered(self): # Sometimes, users don't want fuzzy matching too much When they set the slider # to 100, they don't expect a filename with the same words, but not the same order, to match. # Thus, we want to return 99 in that case. eq_(99, compare(["a", "b", "c", "d"], ["d", "b", "c", "a"])) def test_word_occurs_twice(self): # if a word occurs twice in first, but once in second, we want the word to be only counted once eq_(89, compare(["a", "b", "c", "d", "a"], ["d", "b", "c", "a"])) def test_uses_copy_of_lists(self): first = ["foo", "bar"] second = ["bar", "bleh"] compare(first, second) eq_(["foo", "bar"], first) eq_(["bar", "bleh"], second) def test_word_weight(self): eq_( int((6.0 / 13.0) * 100), compare(["foo", "bar"], ["bar", "bleh"], (WEIGHT_WORDS,)), ) def test_similar_words(self): eq_( 100, compare( ["the", "white", "stripes"], ["the", "whites", "stripe"], (MATCH_SIMILAR_WORDS,), ), ) def test_empty(self): eq_(0, compare([], [])) def test_with_fields(self): eq_(67, compare([["a", "b"], ["c", "d", "e"]], [["a", "b"], ["c", "d", "f"]])) def test_propagate_flags_with_fields(self, monkeypatch): def mock_compare(first, second, flags): eq_((0, 1, 2, 3, 5), flags) monkeypatch.setattr(engine, "compare_fields", mock_compare) compare([["a"]], [["a"]], (0, 1, 2, 3, 5)) class TestCaseWordCompareWithFields: def test_simple(self): eq_( 67, compare_fields([["a", "b"], ["c", "d", "e"]], [["a", "b"], ["c", "d", "f"]]), ) def test_empty(self): eq_(0, compare_fields([], [])) def test_different_length(self): eq_(0, compare_fields([["a"], ["b"]], [["a"], ["b"], ["c"]])) def test_propagates_flags(self, monkeypatch): def mock_compare(first, second, flags): eq_((0, 1, 2, 3, 5), flags) monkeypatch.setattr(engine, "compare_fields", mock_compare) compare_fields([["a"]], [["a"]], (0, 1, 2, 3, 5)) def test_order(self): first = [["a", "b"], ["c", "d", "e"]] second = [["c", "d", "f"], ["a", "b"]] eq_(0, compare_fields(first, second)) def test_no_order(self): first = [["a", "b"], ["c", "d", "e"]] second = [["c", "d", "f"], ["a", "b"]] eq_(67, compare_fields(first, second, (NO_FIELD_ORDER,))) first = [["a", "b"], ["a", "b"]] # a field can only be matched once. second = [["c", "d", "f"], ["a", "b"]] eq_(0, compare_fields(first, second, (NO_FIELD_ORDER,))) first = [["a", "b"], ["a", "b", "c"]] second = [["c", "d", "f"], ["a", "b"]] eq_(33, compare_fields(first, second, (NO_FIELD_ORDER,))) def test_compare_fields_without_order_doesnt_alter_fields(self): # The NO_ORDER comp type altered the fields! first = [["a", "b"], ["c", "d", "e"]] second = [["c", "d", "f"], ["a", "b"]] eq_(67, compare_fields(first, second, (NO_FIELD_ORDER,))) eq_([["a", "b"], ["c", "d", "e"]], first) eq_([["c", "d", "f"], ["a", "b"]], second) class TestCaseBuildWordDict: def test_with_standard_words(self): item_list = [NamedObject("foo bar", True)] item_list.append(NamedObject("bar baz", True)) item_list.append(NamedObject("baz bleh foo", True)) d = build_word_dict(item_list) eq_(4, len(d)) eq_(2, len(d["foo"])) assert item_list[0] in d["foo"] assert item_list[2] in d["foo"] eq_(2, len(d["bar"])) assert item_list[0] in d["bar"] assert item_list[1] in d["bar"] eq_(2, len(d["baz"])) assert item_list[1] in d["baz"] assert item_list[2] in d["baz"] eq_(1, len(d["bleh"])) assert item_list[2] in d["bleh"] def test_unpack_fields(self): o = NamedObject("") o.words = [["foo", "bar"], ["baz"]] d = build_word_dict([o]) eq_(3, len(d)) eq_(1, len(d["foo"])) def test_words_are_unaltered(self): o = NamedObject("") o.words = [["foo", "bar"], ["baz"]] build_word_dict([o]) eq_([["foo", "bar"], ["baz"]], o.words) def test_object_instances_can_only_be_once_in_words_object_list(self): o = NamedObject("foo foo", True) d = build_word_dict([o]) eq_(1, len(d["foo"])) def test_job(self): def do_progress(p, d=""): self.log.append(p) return True j = job.Job(1, do_progress) self.log = [] s = "foo bar" build_word_dict([NamedObject(s, True), NamedObject(s, True), NamedObject(s, True)], j) # We don't have intermediate log because iter_with_progress is called with every > 1 eq_(0, self.log[0]) eq_(100, self.log[1]) class TestCaseMergeSimilarWords: def test_some_similar_words(self): d = { "foobar": {1}, "foobar1": {2}, "foobar2": {3}, } merge_similar_words(d) eq_(1, len(d)) eq_(3, len(d["foobar"])) class TestCaseReduceCommonWords: def test_typical(self): d = { "foo": {NamedObject("foo bar", True) for _ in range(50)}, "bar": {NamedObject("foo bar", True) for _ in range(49)}, } reduce_common_words(d, 50) assert "foo" not in d eq_(49, len(d["bar"])) def test_dont_remove_objects_with_only_common_words(self): d = { "common": set([NamedObject("common uncommon", True) for _ in range(50)] + [NamedObject("common", True)]), "uncommon": {NamedObject("common uncommon", True)}, } reduce_common_words(d, 50) eq_(1, len(d["common"])) eq_(1, len(d["uncommon"])) def test_values_still_are_set_instances(self): d = { "common": set([NamedObject("common uncommon", True) for _ in range(50)] + [NamedObject("common", True)]), "uncommon": {NamedObject("common uncommon", True)}, } reduce_common_words(d, 50) assert isinstance(d["common"], set) assert isinstance(d["uncommon"], set) def test_dont_raise_keyerror_when_a_word_has_been_removed(self): # If a word has been removed by the reduce, an object in a subsequent common word that # contains the word that has been removed would cause a KeyError. d = { "foo": {NamedObject("foo bar baz", True) for _ in range(50)}, "bar": {NamedObject("foo bar baz", True) for _ in range(50)}, "baz": {NamedObject("foo bar baz", True) for _ in range(49)}, } try: reduce_common_words(d, 50) except KeyError: self.fail() def test_unpack_fields(self): # object.words may be fields. def create_it(): o = NamedObject("") o.words = [["foo", "bar"], ["baz"]] return o d = {"foo": {create_it() for _ in range(50)}} try: reduce_common_words(d, 50) except TypeError: self.fail("must support fields.") def test_consider_a_reduced_common_word_common_even_after_reduction(self): # There was a bug in the code that causeda word that has already been reduced not to # be counted as a common word for subsequent words. For example, if 'foo' is processed # as a common word, keeping a "foo bar" file in it, and the 'bar' is processed, "foo bar" # would not stay in 'bar' because 'foo' is not a common word anymore. only_common = NamedObject("foo bar", True) d = { "foo": set([NamedObject("foo bar baz", True) for _ in range(49)] + [only_common]), "bar": set([NamedObject("foo bar baz", True) for _ in range(49)] + [only_common]), "baz": {NamedObject("foo bar baz", True) for _ in range(49)}, } reduce_common_words(d, 50) eq_(1, len(d["foo"])) eq_(1, len(d["bar"])) eq_(49, len(d["baz"])) class TestCaseGetMatch: def test_simple(self): o1 = NamedObject("foo bar", True) o2 = NamedObject("bar bleh", True) m = get_match(o1, o2) eq_(50, m.percentage) eq_(["foo", "bar"], m.first.words) eq_(["bar", "bleh"], m.second.words) assert m.first is o1 assert m.second is o2 def test_in(self): o1 = NamedObject("foo", True) o2 = NamedObject("bar", True) m = get_match(o1, o2) assert o1 in m assert o2 in m assert object() not in m def test_word_weight(self): m = get_match(NamedObject("foo bar", True), NamedObject("bar bleh", True), (WEIGHT_WORDS,)) eq_(m.percentage, int((6.0 / 13.0) * 100)) class TestCaseGetMatches: def test_empty(self): eq_(getmatches([]), []) def test_simple(self): item_list = [ NamedObject("foo bar"), NamedObject("bar bleh"), NamedObject("a b c foo"), ] r = getmatches(item_list) eq_(2, len(r)) m = first(m for m in r if m.percentage == 50) # "foo bar" and "bar bleh" assert_match(m, "foo bar", "bar bleh") m = first(m for m in r if m.percentage == 33) # "foo bar" and "a b c foo" assert_match(m, "foo bar", "a b c foo") def test_null_and_unrelated_objects(self): item_list = [ NamedObject("foo bar"), NamedObject("bar bleh"), NamedObject(""), NamedObject("unrelated object"), ] r = getmatches(item_list) eq_(len(r), 1) m = r[0] eq_(m.percentage, 50) assert_match(m, "foo bar", "bar bleh") def test_twice_the_same_word(self): item_list = [NamedObject("foo foo bar"), NamedObject("bar bleh")] r = getmatches(item_list) eq_(1, len(r)) def test_twice_the_same_word_when_preworded(self): item_list = [NamedObject("foo foo bar", True), NamedObject("bar bleh", True)] r = getmatches(item_list) eq_(1, len(r)) def test_two_words_match(self): item_list = [NamedObject("foo bar"), NamedObject("foo bar bleh")] r = getmatches(item_list) eq_(1, len(r)) def test_match_files_with_only_common_words(self): # If a word occurs more than 50 times, it is excluded from the matching process # The problem with the common_word_threshold is that the files containing only common # words will never be matched together. We *should* match them. # This test assumes that the common word threshold const is 50 item_list = [NamedObject("foo") for _ in range(50)] r = getmatches(item_list) eq_(1225, len(r)) def test_use_words_already_there_if_there(self): o1 = NamedObject("foo") o2 = NamedObject("bar") o2.words = ["foo"] eq_(1, len(getmatches([o1, o2]))) def test_job(self): def do_progress(p, d=""): self.log.append(p) return True j = job.Job(1, do_progress) self.log = [] s = "foo bar" getmatches([NamedObject(s), NamedObject(s), NamedObject(s)], j=j) assert len(self.log) > 2 eq_(0, self.log[0]) eq_(100, self.log[-1]) def test_weight_words(self): item_list = [NamedObject("foo bar"), NamedObject("bar bleh")] m = getmatches(item_list, weight_words=True)[0] eq_(int((6.0 / 13.0) * 100), m.percentage) def test_similar_word(self): item_list = [NamedObject("foobar"), NamedObject("foobars")] eq_(len(getmatches(item_list, match_similar_words=True)), 1) eq_(getmatches(item_list, match_similar_words=True)[0].percentage, 100) item_list = [NamedObject("foobar"), NamedObject("foo")] eq_(len(getmatches(item_list, match_similar_words=True)), 0) # too far item_list = [NamedObject("bizkit"), NamedObject("bizket")] eq_(len(getmatches(item_list, match_similar_words=True)), 1) item_list = [NamedObject("foobar"), NamedObject("foosbar")] eq_(len(getmatches(item_list, match_similar_words=True)), 1) def test_single_object_with_similar_words(self): item_list = [NamedObject("foo foos")] eq_(len(getmatches(item_list, match_similar_words=True)), 0) def test_double_words_get_counted_only_once(self): item_list = [NamedObject("foo bar foo bleh"), NamedObject("foo bar bleh bar")] m = getmatches(item_list)[0] eq_(75, m.percentage) def test_with_fields(self): o1 = NamedObject("foo bar - foo bleh") o2 = NamedObject("foo bar - bleh bar") o1.words = getfields(o1.name) o2.words = getfields(o2.name) m = getmatches([o1, o2])[0] eq_(50, m.percentage) def test_with_fields_no_order(self): o1 = NamedObject("foo bar - foo bleh") o2 = NamedObject("bleh bang - foo bar") o1.words = getfields(o1.name) o2.words = getfields(o2.name) m = getmatches([o1, o2], no_field_order=True)[0] eq_(m.percentage, 50) def test_only_match_similar_when_the_option_is_set(self): item_list = [NamedObject("foobar"), NamedObject("foobars")] eq_(len(getmatches(item_list, match_similar_words=False)), 0) def test_dont_recurse_do_match(self): # with nosetests, the stack is increased. The number has to be high enough not to be failing falsely sys.setrecursionlimit(200) files = [NamedObject("foo bar") for _ in range(201)] try: getmatches(files) except RuntimeError: self.fail() finally: sys.setrecursionlimit(1000) def test_min_match_percentage(self): item_list = [ NamedObject("foo bar"), NamedObject("bar bleh"), NamedObject("a b c foo"), ] r = getmatches(item_list, min_match_percentage=50) eq_(1, len(r)) # Only "foo bar" / "bar bleh" should match def test_memory_error(self, monkeypatch): @log_calls def mocked_match(first, second, flags): if len(mocked_match.calls) > 42: raise MemoryError() return Match(first, second, 0) objects = [NamedObject() for _ in range(10)] # results in 45 matches monkeypatch.setattr(engine, "get_match", mocked_match) try: r = getmatches(objects) except MemoryError: self.fail("MemoryError must be handled") eq_(42, len(r)) class TestCaseGetMatchesByContents: def test_big_file_partial_hashing(self): smallsize = 1 bigsize = 100 * 1024 * 1024 # 100MB f = [ no("bigfoo", size=bigsize), no("bigbar", size=bigsize), no("smallfoo", size=smallsize), no("smallbar", size=smallsize), ] f[0].digest = f[0].digest_partial = f[0].digest_samples = "foobar" f[1].digest = f[1].digest_partial = f[1].digest_samples = "foobar" f[2].digest = f[2].digest_partial = "bleh" f[3].digest = f[3].digest_partial = "bleh" r = getmatches_by_contents(f, bigsize=bigsize) eq_(len(r), 2) # User disabled optimization for big files, compute digests as usual r = getmatches_by_contents(f, bigsize=0) eq_(len(r), 2) # Other file is now slightly different, digest_partial is still the same f[1].digest = f[1].digest_samples = "foobardiff" r = getmatches_by_contents(f, bigsize=bigsize) # Successfully filter it out eq_(len(r), 1) r = getmatches_by_contents(f, bigsize=0) eq_(len(r), 1) class TestCaseGroup: def test_empty(self): g = Group() eq_(None, g.ref) eq_([], g.dupes) eq_(0, len(g.matches)) def test_add_match(self): g = Group() m = get_match(NamedObject("foo", True), NamedObject("bar", True)) g.add_match(m) assert g.ref is m.first eq_([m.second], g.dupes) eq_(1, len(g.matches)) assert m in g.matches def test_multiple_add_match(self): g = Group() o1 = NamedObject("a", True) o2 = NamedObject("b", True) o3 = NamedObject("c", True) o4 = NamedObject("d", True) g.add_match(get_match(o1, o2)) assert g.ref is o1 eq_([o2], g.dupes) eq_(1, len(g.matches)) g.add_match(get_match(o1, o3)) eq_([o2], g.dupes) eq_(2, len(g.matches)) g.add_match(get_match(o2, o3)) eq_([o2, o3], g.dupes) eq_(3, len(g.matches)) g.add_match(get_match(o1, o4)) eq_([o2, o3], g.dupes) eq_(4, len(g.matches)) g.add_match(get_match(o2, o4)) eq_([o2, o3], g.dupes) eq_(5, len(g.matches)) g.add_match(get_match(o3, o4)) eq_([o2, o3, o4], g.dupes) eq_(6, len(g.matches)) def test_len(self): g = Group() eq_(0, len(g)) g.add_match(get_match(NamedObject("foo", True), NamedObject("bar", True))) eq_(2, len(g)) def test_add_same_match_twice(self): g = Group() m = get_match(NamedObject("foo", True), NamedObject("foo", True)) g.add_match(m) eq_(2, len(g)) eq_(1, len(g.matches)) g.add_match(m) eq_(2, len(g)) eq_(1, len(g.matches)) def test_in(self): g = Group() o1 = NamedObject("foo", True) o2 = NamedObject("bar", True) assert o1 not in g g.add_match(get_match(o1, o2)) assert o1 in g assert o2 in g def test_remove(self): g = Group() o1 = NamedObject("foo", True) o2 = NamedObject("bar", True) o3 = NamedObject("bleh", True) g.add_match(get_match(o1, o2)) g.add_match(get_match(o1, o3)) g.add_match(get_match(o2, o3)) eq_(3, len(g.matches)) eq_(3, len(g)) g.remove_dupe(o3) eq_(1, len(g.matches)) eq_(2, len(g)) g.remove_dupe(o1) eq_(0, len(g.matches)) eq_(0, len(g)) def test_remove_with_ref_dupes(self): g = Group() o1 = NamedObject("foo", True) o2 = NamedObject("bar", True) o3 = NamedObject("bleh", True) g.add_match(get_match(o1, o2)) g.add_match(get_match(o1, o3)) g.add_match(get_match(o2, o3)) o1.is_ref = True o2.is_ref = True g.remove_dupe(o3) eq_(0, len(g)) def test_switch_ref(self): o1 = NamedObject(with_words=True) o2 = NamedObject(with_words=True) g = Group() g.add_match(get_match(o1, o2)) assert o1 is g.ref g.switch_ref(o2) assert o2 is g.ref eq_([o1], g.dupes) g.switch_ref(o2) assert o2 is g.ref g.switch_ref(NamedObject("", True)) assert o2 is g.ref def test_switch_ref_from_ref_dir(self): # When the ref dupe is from a ref dir, switch_ref() does nothing o1 = no(with_words=True) o2 = no(with_words=True) o1.is_ref = True g = Group() g.add_match(get_match(o1, o2)) g.switch_ref(o2) assert o1 is g.ref def test_get_match_of(self): g = Group() for m in get_match_triangle(): g.add_match(m) o = g.dupes[0] m = g.get_match_of(o) assert g.ref in m assert o in m assert g.get_match_of(NamedObject("", True)) is None assert g.get_match_of(g.ref) is None def test_percentage(self): # percentage should return the avg percentage in relation to the ref m1, m2, m3 = get_match_triangle() m1 = Match(m1[0], m1[1], 100) m2 = Match(m2[0], m2[1], 50) m3 = Match(m3[0], m3[1], 33) g = Group() g.add_match(m1) g.add_match(m2) g.add_match(m3) eq_(75, g.percentage) g.switch_ref(g.dupes[0]) eq_(66, g.percentage) g.remove_dupe(g.dupes[0]) eq_(33, g.percentage) g.add_match(m1) g.add_match(m2) eq_(66, g.percentage) def test_percentage_on_empty_group(self): g = Group() eq_(0, g.percentage) def test_prioritize(self): m1, m2, m3 = get_match_triangle() o1 = m1.first o2 = m1.second o3 = m2.second o1.name = "c" o2.name = "b" o3.name = "a" g = Group() g.add_match(m1) g.add_match(m2) g.add_match(m3) assert o1 is g.ref assert g.prioritize(lambda x: x.name) assert o3 is g.ref def test_prioritize_with_tie_breaker(self): # if the ref has the same key as one or more of the dupe, run the tie_breaker func among them g = get_test_group() o1, o2, o3 = g.ordered g.prioritize(lambda x: 0, lambda ref, dupe: dupe is o3) assert g.ref is o3 def test_prioritize_with_tie_breaker_runs_on_all_dupes(self): # Even if a dupe is chosen to switch with ref with a tie breaker, we still run the tie breaker # with other dupes and the newly chosen ref g = get_test_group() o1, o2, o3 = g.ordered o1.foo = 1 o2.foo = 2 o3.foo = 3 g.prioritize(lambda x: 0, lambda ref, dupe: dupe.foo > ref.foo) assert g.ref is o3 def test_prioritize_with_tie_breaker_runs_only_on_tie_dupes(self): # The tie breaker only runs on dupes that had the same value for the key_func g = get_test_group() o1, o2, o3 = g.ordered o1.foo = 2 o2.foo = 2 o3.foo = 1 o1.bar = 1 o2.bar = 2 o3.bar = 3 g.prioritize(lambda x: -x.foo, lambda ref, dupe: dupe.bar > ref.bar) assert g.ref is o2 def test_prioritize_with_ref_dupe(self): # when the ref dupe of a group is from a ref dir, make it stay on top. g = get_test_group() o1, o2, o3 = g o1.is_ref = True o2.size = 2 g.prioritize(lambda x: -x.size) assert g.ref is o1 def test_prioritize_nothing_changes(self): # prioritize() returns False when nothing changes in the group. g = get_test_group() g[0].name = "a" g[1].name = "b" g[2].name = "c" assert not g.prioritize(lambda x: x.name) def test_list_like(self): g = Group() o1, o2 = (NamedObject("foo", True), NamedObject("bar", True)) g.add_match(get_match(o1, o2)) assert g[0] is o1 assert g[1] is o2 def test_discard_matches(self): g = Group() o1, o2, o3 = ( NamedObject("foo", True), NamedObject("bar", True), NamedObject("baz", True), ) g.add_match(get_match(o1, o2)) g.add_match(get_match(o1, o3)) g.discard_matches() eq_(1, len(g.matches)) eq_(0, len(g.candidates)) class TestCaseGetGroups: def test_empty(self): r = get_groups([]) eq_([], r) def test_simple(self): item_list = [NamedObject("foo bar"), NamedObject("bar bleh")] matches = getmatches(item_list) m = matches[0] r = get_groups(matches) eq_(1, len(r)) g = r[0] assert g.ref is m.first eq_([m.second], g.dupes) def test_group_with_multiple_matches(self): # This results in 3 matches item_list = [NamedObject("foo"), NamedObject("foo"), NamedObject("foo")] matches = getmatches(item_list) r = get_groups(matches) eq_(1, len(r)) g = r[0] eq_(3, len(g)) def test_must_choose_a_group(self): item_list = [ NamedObject("a b"), NamedObject("a b"), NamedObject("b c"), NamedObject("c d"), NamedObject("c d"), ] # There will be 2 groups here: group "a b" and group "c d" # "b c" can go either of them, but not both. matches = getmatches(item_list) r = get_groups(matches) eq_(2, len(r)) eq_(5, len(r[0]) + len(r[1])) def test_should_all_go_in_the_same_group(self): item_list = [ NamedObject("a b"), NamedObject("a b"), NamedObject("a b"), NamedObject("a b"), ] # There will be 2 groups here: group "a b" and group "c d" # "b c" can fit in both, but it must be in only one of them matches = getmatches(item_list) r = get_groups(matches) eq_(1, len(r)) def test_give_priority_to_matches_with_higher_percentage(self): o1 = NamedObject(with_words=True) o2 = NamedObject(with_words=True) o3 = NamedObject(with_words=True) m1 = Match(o1, o2, 1) m2 = Match(o2, o3, 2) r = get_groups([m1, m2]) eq_(1, len(r)) g = r[0] eq_(2, len(g)) assert o1 not in g assert o2 in g assert o3 in g def test_four_sized_group(self): item_list = [NamedObject("foobar") for _ in range(4)] m = getmatches(item_list) r = get_groups(m) eq_(1, len(r)) eq_(4, len(r[0])) def test_referenced_by_ref2(self): o1 = NamedObject(with_words=True) o2 = NamedObject(with_words=True) o3 = NamedObject(with_words=True) m1 = get_match(o1, o2) m2 = get_match(o3, o1) m3 = get_match(o3, o2) r = get_groups([m1, m2, m3]) eq_(3, len(r[0])) def test_group_admissible_discarded_dupes(self): # If, with a (A, B, C, D) set, all match with A, but C and D don't match with B and that the # (A, B) match is the highest (thus resulting in an (A, B) group), still match C and D # in a separate group instead of discarding them. A, B, C, D = (NamedObject() for _ in range(4)) m1 = Match(A, B, 90) # This is the strongest "A" match m2 = Match(A, C, 80) # Because C doesn't match with B, it won't be in the group m3 = Match(A, D, 80) # Same thing for D m4 = Match(C, D, 70) # However, because C and D match, they should have their own group. groups = get_groups([m1, m2, m3, m4]) eq_(len(groups), 2) g1, g2 = groups assert A in g1 assert B in g1 assert C in g2 assert D in g2
30,268
Python
.py
778
30.194087
117
0.550551
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,163
app_test.py
arsenetar_dupeguru/core/tests/app_test.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import os import os.path as op import logging import tempfile import pytest from pathlib import Path import hscommon.conflict import hscommon.util from hscommon.testutil import eq_, log_calls from hscommon.jobprogress.job import Job from core.tests.base import TestApp from core.tests.results_test import GetTestGroups from core import app, fs, engine from core.scanner import ScanType def add_fake_files_to_directories(directories, files): directories.get_files = lambda j=None: iter(files) directories._dirs.append("this is just so Scan() doesn't return 3") class TestCaseDupeGuru: def test_apply_filter_calls_results_apply_filter(self, monkeypatch): dgapp = TestApp().app monkeypatch.setattr(dgapp.results, "apply_filter", log_calls(dgapp.results.apply_filter)) dgapp.apply_filter("foo") eq_(2, len(dgapp.results.apply_filter.calls)) call = dgapp.results.apply_filter.calls[0] assert call["filter_str"] is None call = dgapp.results.apply_filter.calls[1] eq_("foo", call["filter_str"]) def test_apply_filter_escapes_regexp(self, monkeypatch): dgapp = TestApp().app monkeypatch.setattr(dgapp.results, "apply_filter", log_calls(dgapp.results.apply_filter)) dgapp.apply_filter("()[]\\.|+?^abc") call = dgapp.results.apply_filter.calls[1] eq_("\\(\\)\\[\\]\\\\\\.\\|\\+\\?\\^abc", call["filter_str"]) dgapp.apply_filter("(*)") # In "simple mode", we want the * to behave as a wildcard call = dgapp.results.apply_filter.calls[3] eq_(r"\(.*\)", call["filter_str"]) dgapp.options["escape_filter_regexp"] = False dgapp.apply_filter("(abc)") call = dgapp.results.apply_filter.calls[5] eq_("(abc)", call["filter_str"]) def test_copy_or_move(self, tmpdir, monkeypatch): # The goal here is just to have a test for a previous blowup I had. I know my test coverage # for this unit is pathetic. What's done is done. My approach now is to add tests for # every change I want to make. The blowup was caused by a missing import. p = Path(str(tmpdir)) p.joinpath("foo").touch() monkeypatch.setattr( hscommon.conflict, "smart_copy", log_calls(lambda source_path, dest_path: None), ) # XXX This monkeypatch is temporary. will be fixed in a better monkeypatcher. monkeypatch.setattr(app, "smart_copy", hscommon.conflict.smart_copy) monkeypatch.setattr(os, "makedirs", lambda path: None) # We don't want the test to create that fake directory dgapp = TestApp().app dgapp.directories.add_path(p) [f] = dgapp.directories.get_files() with tempfile.TemporaryDirectory() as tmp_dir: dgapp.copy_or_move(f, True, tmp_dir, 0) eq_(1, len(hscommon.conflict.smart_copy.calls)) call = hscommon.conflict.smart_copy.calls[0] eq_(call["dest_path"], Path(tmp_dir, "foo")) eq_(call["source_path"], f.path) def test_copy_or_move_clean_empty_dirs(self, tmpdir, monkeypatch): tmppath = Path(str(tmpdir)) sourcepath = tmppath.joinpath("source") sourcepath.mkdir() sourcepath.joinpath("myfile").touch() app = TestApp().app app.directories.add_path(tmppath) [myfile] = app.directories.get_files() monkeypatch.setattr(app, "clean_empty_dirs", log_calls(lambda path: None)) app.copy_or_move(myfile, False, tmppath.joinpath("dest"), 0) calls = app.clean_empty_dirs.calls eq_(1, len(calls)) eq_(sourcepath, calls[0]["path"]) def test_scan_with_objects_evaluating_to_false(self): class FakeFile(fs.File): def __bool__(self): return False # At some point, any() was used in a wrong way that made Scan() wrongly return 1 app = TestApp().app f1, f2 = (FakeFile("foo") for _ in range(2)) f1.is_ref, f2.is_ref = (False, False) assert not (bool(f1) and bool(f2)) add_fake_files_to_directories(app.directories, [f1, f2]) app.start_scanning() # no exception @pytest.mark.skipif("not hasattr(os, 'link')") def test_ignore_hardlink_matches(self, tmpdir): # If the ignore_hardlink_matches option is set, don't match files hardlinking to the same # inode. tmppath = Path(str(tmpdir)) tmppath.joinpath("myfile").open("wt").write("foo") os.link(str(tmppath.joinpath("myfile")), str(tmppath.joinpath("hardlink"))) app = TestApp().app app.directories.add_path(tmppath) app.options["scan_type"] = ScanType.CONTENTS app.options["ignore_hardlink_matches"] = True app.start_scanning() eq_(len(app.results.groups), 0) def test_rename_when_nothing_is_selected(self): # Issue #140 # It's possible that rename operation has its selected row swept off from under it, thus # making the selected row None. Don't crash when it happens. dgapp = TestApp().app # selected_row is None because there's no result. assert not dgapp.result_table.rename_selected("foo") # no crash class TestCaseDupeGuruCleanEmptyDirs: @pytest.fixture def do_setup(self, request): monkeypatch = request.getfixturevalue("monkeypatch") monkeypatch.setattr( hscommon.util, "delete_if_empty", log_calls(lambda path, files_to_delete=[]: None), ) # XXX This monkeypatch is temporary. will be fixed in a better monkeypatcher. monkeypatch.setattr(app, "delete_if_empty", hscommon.util.delete_if_empty) self.app = TestApp().app def test_option_off(self, do_setup): self.app.clean_empty_dirs(Path("/foo/bar")) eq_(0, len(hscommon.util.delete_if_empty.calls)) def test_option_on(self, do_setup): self.app.options["clean_empty_dirs"] = True self.app.clean_empty_dirs(Path("/foo/bar")) calls = hscommon.util.delete_if_empty.calls eq_(1, len(calls)) eq_(Path("/foo/bar"), calls[0]["path"]) eq_([".DS_Store"], calls[0]["files_to_delete"]) def test_recurse_up(self, do_setup, monkeypatch): # delete_if_empty must be recursively called up in the path until it returns False @log_calls def mock_delete_if_empty(path, files_to_delete=[]): return len(path.parts) > 1 monkeypatch.setattr(hscommon.util, "delete_if_empty", mock_delete_if_empty) # XXX This monkeypatch is temporary. will be fixed in a better monkeypatcher. monkeypatch.setattr(app, "delete_if_empty", mock_delete_if_empty) self.app.options["clean_empty_dirs"] = True self.app.clean_empty_dirs(Path("not-empty/empty/empty")) calls = hscommon.util.delete_if_empty.calls eq_(3, len(calls)) eq_(Path("not-empty/empty/empty"), calls[0]["path"]) eq_(Path("not-empty/empty"), calls[1]["path"]) eq_(Path("not-empty"), calls[2]["path"]) class TestCaseDupeGuruWithResults: @pytest.fixture def do_setup(self, request): app = TestApp() self.app = app.app self.objects, self.matches, self.groups = GetTestGroups() self.app.results.groups = self.groups self.dpanel = app.dpanel self.dtree = app.dtree self.rtable = app.rtable self.rtable.refresh() tmpdir = request.getfixturevalue("tmpdir") tmppath = Path(str(tmpdir)) tmppath.joinpath("foo").mkdir() tmppath.joinpath("bar").mkdir() self.app.directories.add_path(tmppath) def test_get_objects(self, do_setup): objects = self.objects groups = self.groups r = self.rtable[0] assert r._group is groups[0] assert r._dupe is objects[0] r = self.rtable[1] assert r._group is groups[0] assert r._dupe is objects[1] r = self.rtable[4] assert r._group is groups[1] assert r._dupe is objects[4] def test_get_objects_after_sort(self, do_setup): objects = self.objects groups = self.groups[:] # we need an un-sorted reference self.rtable.sort("name", False) r = self.rtable[1] assert r._group is groups[1] assert r._dupe is objects[4] def test_selected_result_node_paths_after_deletion(self, do_setup): # cases where the selected dupes aren't there are correctly handled self.rtable.select([1, 2, 3]) self.app.remove_selected() # The first 2 dupes have been removed. The 3rd one is a ref. it stays there, in first pos. eq_(self.rtable.selected_indexes, [1]) # no exception def test_select_result_node_paths(self, do_setup): app = self.app objects = self.objects self.rtable.select([1, 2]) eq_(len(app.selected_dupes), 2) assert app.selected_dupes[0] is objects[1] assert app.selected_dupes[1] is objects[2] def test_select_result_node_paths_with_ref(self, do_setup): app = self.app objects = self.objects self.rtable.select([1, 2, 3]) eq_(len(app.selected_dupes), 3) assert app.selected_dupes[0] is objects[1] assert app.selected_dupes[1] is objects[2] assert app.selected_dupes[2] is self.groups[1].ref def test_select_result_node_paths_after_sort(self, do_setup): app = self.app objects = self.objects groups = self.groups[:] # To keep the old order in memory self.rtable.sort("name", False) # 0 # Now, the group order is supposed to be reversed self.rtable.select([1, 2, 3]) eq_(len(app.selected_dupes), 3) assert app.selected_dupes[0] is objects[4] assert app.selected_dupes[1] is groups[0].ref assert app.selected_dupes[2] is objects[1] def test_selected_powermarker_node_paths(self, do_setup): # app.selected_dupes is correctly converted into paths self.rtable.power_marker = True self.rtable.select([0, 1, 2]) self.rtable.power_marker = False eq_(self.rtable.selected_indexes, [1, 2, 4]) def test_selected_powermarker_node_paths_after_deletion(self, do_setup): # cases where the selected dupes aren't there are correctly handled app = self.app self.rtable.power_marker = True self.rtable.select([0, 1, 2]) app.remove_selected() eq_(self.rtable.selected_indexes, []) # no exception def test_select_powermarker_rows_after_sort(self, do_setup): app = self.app objects = self.objects self.rtable.power_marker = True self.rtable.sort("name", False) self.rtable.select([0, 1, 2]) eq_(len(app.selected_dupes), 3) assert app.selected_dupes[0] is objects[4] assert app.selected_dupes[1] is objects[2] assert app.selected_dupes[2] is objects[1] def test_toggle_selected_mark_state(self, do_setup): app = self.app objects = self.objects app.toggle_selected_mark_state() eq_(app.results.mark_count, 0) self.rtable.select([1, 4]) app.toggle_selected_mark_state() eq_(app.results.mark_count, 2) assert not app.results.is_marked(objects[0]) assert app.results.is_marked(objects[1]) assert not app.results.is_marked(objects[2]) assert not app.results.is_marked(objects[3]) assert app.results.is_marked(objects[4]) def test_toggle_selected_mark_state_with_different_selected_state(self, do_setup): # When marking selected dupes with a heterogenous selection, mark all selected dupes. When # it's homogenous, simply toggle. app = self.app self.rtable.select([1]) app.toggle_selected_mark_state() # index 0 is unmarkable, but we throw it in the bunch to be sure that it doesn't make the # selection heterogenoug when it shouldn't. self.rtable.select([0, 1, 4]) app.toggle_selected_mark_state() eq_(app.results.mark_count, 2) app.toggle_selected_mark_state() eq_(app.results.mark_count, 0) def test_refresh_details_with_selected(self, do_setup): self.rtable.select([1, 4]) eq_(self.dpanel.row(0), ("Filename", "bar bleh", "foo bar")) self.dpanel.view.check_gui_calls(["refresh"]) self.rtable.select([]) eq_(self.dpanel.row(0), ("Filename", "---", "---")) self.dpanel.view.check_gui_calls(["refresh"]) def test_make_selected_reference(self, do_setup): app = self.app objects = self.objects groups = self.groups self.rtable.select([1, 4]) app.make_selected_reference() assert groups[0].ref is objects[1] assert groups[1].ref is objects[4] def test_make_selected_reference_by_selecting_two_dupes_in_the_same_group(self, do_setup): app = self.app objects = self.objects groups = self.groups self.rtable.select([1, 2, 4]) # Only [0, 0] and [1, 0] must go ref, not [0, 1] because it is a part of the same group app.make_selected_reference() assert groups[0].ref is objects[1] assert groups[1].ref is objects[4] def test_remove_selected(self, do_setup): app = self.app self.rtable.select([1, 4]) app.remove_selected() eq_(len(app.results.dupes), 1) # the first path is now selected app.remove_selected() eq_(len(app.results.dupes), 0) def test_add_directory_simple(self, do_setup): # There's already a directory in self.app, so adding another once makes 2 of em app = self.app # any other path that isn't a parent or child of the already added path otherpath = Path(op.dirname(__file__)) app.add_directory(otherpath) eq_(len(app.directories), 2) def test_add_directory_already_there(self, do_setup): app = self.app otherpath = Path(op.dirname(__file__)) app.add_directory(otherpath) app.add_directory(otherpath) eq_(len(app.view.messages), 1) assert "already" in app.view.messages[0] def test_add_directory_does_not_exist(self, do_setup): app = self.app app.add_directory("/does_not_exist") eq_(len(app.view.messages), 1) assert "exist" in app.view.messages[0] def test_ignore(self, do_setup): app = self.app self.rtable.select([4]) # The dupe of the second, 2 sized group app.add_selected_to_ignore_list() eq_(len(app.ignore_list), 1) self.rtable.select([1]) # first dupe of the 3 dupes group app.add_selected_to_ignore_list() # BOTH the ref and the other dupe should have been added eq_(len(app.ignore_list), 3) def test_purge_ignorelist(self, do_setup, tmpdir): app = self.app p1 = str(tmpdir.join("file1")) p2 = str(tmpdir.join("file2")) open(p1, "w").close() open(p2, "w").close() dne = "/does_not_exist" app.ignore_list.ignore(dne, p1) app.ignore_list.ignore(p2, dne) app.ignore_list.ignore(p1, p2) app.purge_ignore_list() eq_(1, len(app.ignore_list)) assert app.ignore_list.are_ignored(p1, p2) assert not app.ignore_list.are_ignored(dne, p1) def test_only_unicode_is_added_to_ignore_list(self, do_setup): def fake_ignore(first, second): if not isinstance(first, str): self.fail() if not isinstance(second, str): self.fail() app = self.app app.ignore_list.ignore = fake_ignore self.rtable.select([4]) app.add_selected_to_ignore_list() def test_cancel_scan_with_previous_results(self, do_setup): # When doing a scan with results being present prior to the scan, correctly invalidate the # results table. app = self.app app.JOB = Job(1, lambda *args, **kw: False) # Cancels the task add_fake_files_to_directories(app.directories, self.objects) # We want the scan to at least start app.start_scanning() # will be cancelled immediately eq_(len(app.result_table), 0) def test_selected_dupes_after_removal(self, do_setup): # Purge the app's `selected_dupes` attribute when removing dupes, or else it might cause a # crash later with None refs. app = self.app app.results.mark_all() self.rtable.select([0, 1, 2, 3, 4]) app.remove_marked() eq_(len(self.rtable), 0) eq_(app.selected_dupes, []) def test_dont_crash_on_delta_powermarker_dupecount_sort(self, do_setup): # Don't crash when sorting by dupe count or percentage while delta+powermarker are enabled. # Ref #238 self.rtable.delta_values = True self.rtable.power_marker = True self.rtable.sort("dupe_count", False) # don't crash self.rtable.sort("percentage", False) # don't crash class TestCaseDupeGuruRenameSelected: @pytest.fixture def do_setup(self, request): tmpdir = request.getfixturevalue("tmpdir") p = Path(str(tmpdir)) p.joinpath("foo bar 1").touch() p.joinpath("foo bar 2").touch() p.joinpath("foo bar 3").touch() files = fs.get_files(p) for f in files: f.is_ref = False matches = engine.getmatches(files) groups = engine.get_groups(matches) g = groups[0] g.prioritize(lambda x: x.name) app = TestApp() app.app.results.groups = groups self.app = app.app self.rtable = app.rtable self.rtable.refresh() self.groups = groups self.p = p self.files = files def test_simple(self, do_setup): app = self.app g = self.groups[0] self.rtable.select([1]) assert app.rename_selected("renamed") names = [p.name for p in self.p.glob("*")] assert "renamed" in names assert "foo bar 2" not in names eq_(g.dupes[0].name, "renamed") def test_none_selected(self, do_setup, monkeypatch): app = self.app g = self.groups[0] self.rtable.select([]) monkeypatch.setattr(logging, "warning", log_calls(lambda msg: None)) assert not app.rename_selected("renamed") msg = logging.warning.calls[0]["msg"] eq_("dupeGuru Warning: list index out of range", msg) names = [p.name for p in self.p.glob("*")] assert "renamed" not in names assert "foo bar 2" in names eq_(g.dupes[0].name, "foo bar 2") def test_name_already_exists(self, do_setup, monkeypatch): app = self.app g = self.groups[0] self.rtable.select([1]) monkeypatch.setattr(logging, "warning", log_calls(lambda msg: None)) assert not app.rename_selected("foo bar 1") msg = logging.warning.calls[0]["msg"] assert msg.startswith("dupeGuru Warning: 'foo bar 1' already exists in") names = [p.name for p in self.p.glob("*")] assert "foo bar 1" in names assert "foo bar 2" in names eq_(g.dupes[0].name, "foo bar 2") class TestAppWithDirectoriesInTree: @pytest.fixture def do_setup(self, request): tmpdir = request.getfixturevalue("tmpdir") p = Path(str(tmpdir)) p.joinpath("sub1").mkdir() p.joinpath("sub2").mkdir() p.joinpath("sub3").mkdir() app = TestApp() self.app = app.app self.dtree = app.dtree self.dtree.add_directory(p) self.dtree.view.clear_calls() def test_set_root_as_ref_makes_subfolders_ref_as_well(self, do_setup): # Setting a node state to something also affect subnodes. These subnodes must be correctly # refreshed. node = self.dtree[0] eq_(len(node), 3) # a len() call is required for subnodes to be loaded node.state = 1 # the state property is a state index node = self.dtree[0] eq_(len(node), 3) subnode = node[0] eq_(subnode.state, 1) self.dtree.view.check_gui_calls(["refresh_states"])
20,612
Python
.py
454
36.95815
118
0.630851
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,164
scanner_test.py
arsenetar_dupeguru/core/tests/scanner_test.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import pytest from hscommon.jobprogress import job from pathlib import Path from hscommon.testutil import eq_ from core import fs from core.engine import getwords, Match from core.ignore import IgnoreList from core.scanner import Scanner, ScanType from core.me.scanner import ScannerME # TODO update this to be able to inherit from fs.File class NamedObject: def __init__(self, name="foobar", size=1, path=None): if path is None: path = Path(name) else: path = Path(path, name) self.name = name self.size = size self.path = path self.words = getwords(name) def __repr__(self): return "<NamedObject {!r} {!r}>".format(self.name, self.path) def exists(self): return self.path.exists() no = NamedObject @pytest.fixture def fake_fileexists(request): # This is a hack to avoid invalidating all previous tests since the scanner started to test # for file existence before doing the match grouping. monkeypatch = request.getfixturevalue("monkeypatch") monkeypatch.setattr(Path, "exists", lambda _: True) def test_empty(fake_fileexists): s = Scanner() r = s.get_dupe_groups([]) eq_(r, []) def test_default_settings(fake_fileexists): s = Scanner() eq_(s.min_match_percentage, 80) eq_(s.scan_type, ScanType.FILENAME) eq_(s.mix_file_kind, True) eq_(s.word_weighting, False) eq_(s.match_similar_words, False) eq_(s.size_threshold, 0) eq_(s.large_size_threshold, 0) eq_(s.big_file_size_threshold, 0) def test_simple_with_default_settings(fake_fileexists): s = Scanner() f = [no("foo bar", path="p1"), no("foo bar", path="p2"), no("foo bleh")] r = s.get_dupe_groups(f) eq_(len(r), 1) g = r[0] # 'foo bleh' cannot be in the group because the default min match % is 80 eq_(len(g), 2) assert g.ref in f[:2] assert g.dupes[0] in f[:2] def test_simple_with_lower_min_match(fake_fileexists): s = Scanner() s.min_match_percentage = 50 f = [no("foo bar", path="p1"), no("foo bar", path="p2"), no("foo bleh")] r = s.get_dupe_groups(f) eq_(len(r), 1) g = r[0] eq_(len(g), 3) def test_trim_all_ref_groups(fake_fileexists): # When all files of a group are ref, don't include that group in the results, but also don't # count the files from that group as discarded. s = Scanner() f = [ no("foo", path="p1"), no("foo", path="p2"), no("bar", path="p1"), no("bar", path="p2"), ] f[2].is_ref = True f[3].is_ref = True r = s.get_dupe_groups(f) eq_(len(r), 1) eq_(s.discarded_file_count, 0) def test_prioritize(fake_fileexists): s = Scanner() f = [ no("foo", path="p1"), no("foo", path="p2"), no("bar", path="p1"), no("bar", path="p2"), ] f[1].size = 2 f[2].size = 3 f[3].is_ref = True r = s.get_dupe_groups(f) g1, g2 = r assert f[1] in (g1.ref, g2.ref) assert f[0] in (g1.dupes[0], g2.dupes[0]) assert f[3] in (g1.ref, g2.ref) assert f[2] in (g1.dupes[0], g2.dupes[0]) def test_content_scan(fake_fileexists): s = Scanner() s.scan_type = ScanType.CONTENTS f = [no("foo"), no("bar"), no("bleh")] f[0].digest = f[0].digest_partial = f[0].digest_samples = "foobar" f[1].digest = f[1].digest_partial = f[1].digest_samples = "foobar" f[2].digest = f[2].digest_partial = f[1].digest_samples = "bleh" r = s.get_dupe_groups(f) eq_(len(r), 1) eq_(len(r[0]), 2) eq_(s.discarded_file_count, 0) # don't count the different digest as discarded! def test_content_scan_compare_sizes_first(fake_fileexists): class MyFile(no): @property def digest(self): raise AssertionError() s = Scanner() s.scan_type = ScanType.CONTENTS f = [MyFile("foo", 1), MyFile("bar", 2)] eq_(len(s.get_dupe_groups(f)), 0) def test_ignore_file_size(fake_fileexists): s = Scanner() s.scan_type = ScanType.CONTENTS small_size = 10 # 10KB s.size_threshold = 0 large_size = 100 * 1024 * 1024 # 100MB s.large_size_threshold = 0 f = [ no("smallignore1", small_size - 1), no("smallignore2", small_size - 1), no("small1", small_size), no("small2", small_size), no("large1", large_size), no("large2", large_size), no("largeignore1", large_size + 1), no("largeignore2", large_size + 1), ] f[0].digest = f[0].digest_partial = f[0].digest_samples = "smallignore" f[1].digest = f[1].digest_partial = f[1].digest_samples = "smallignore" f[2].digest = f[2].digest_partial = f[2].digest_samples = "small" f[3].digest = f[3].digest_partial = f[3].digest_samples = "small" f[4].digest = f[4].digest_partial = f[4].digest_samples = "large" f[5].digest = f[5].digest_partial = f[5].digest_samples = "large" f[6].digest = f[6].digest_partial = f[6].digest_samples = "largeignore" f[7].digest = f[7].digest_partial = f[7].digest_samples = "largeignore" r = s.get_dupe_groups(f) # No ignores eq_(len(r), 4) # Ignore smaller s.size_threshold = small_size r = s.get_dupe_groups(f) eq_(len(r), 3) # Ignore larger s.size_threshold = 0 s.large_size_threshold = large_size r = s.get_dupe_groups(f) eq_(len(r), 3) # Ignore both s.size_threshold = small_size r = s.get_dupe_groups(f) eq_(len(r), 2) def test_big_file_partial_hashes(fake_fileexists): s = Scanner() s.scan_type = ScanType.CONTENTS smallsize = 1 bigsize = 100 * 1024 * 1024 # 100MB s.big_file_size_threshold = bigsize f = [no("bigfoo", bigsize), no("bigbar", bigsize), no("smallfoo", smallsize), no("smallbar", smallsize)] f[0].digest = f[0].digest_partial = f[0].digest_samples = "foobar" f[1].digest = f[1].digest_partial = f[1].digest_samples = "foobar" f[2].digest = f[2].digest_partial = "bleh" f[3].digest = f[3].digest_partial = "bleh" r = s.get_dupe_groups(f) eq_(len(r), 2) # digest_partial is still the same, but the file is actually different f[1].digest = f[1].digest_samples = "difffoobar" # here we compare the full digests, as the user disabled the optimization s.big_file_size_threshold = 0 r = s.get_dupe_groups(f) eq_(len(r), 1) # here we should compare the digest_samples, and see they are different s.big_file_size_threshold = bigsize r = s.get_dupe_groups(f) eq_(len(r), 1) def test_min_match_perc_doesnt_matter_for_content_scan(fake_fileexists): s = Scanner() s.scan_type = ScanType.CONTENTS f = [no("foo"), no("bar"), no("bleh")] f[0].digest = f[0].digest_partial = f[0].digest_samples = "foobar" f[1].digest = f[1].digest_partial = f[1].digest_samples = "foobar" f[2].digest = f[2].digest_partial = f[2].digest_samples = "bleh" s.min_match_percentage = 101 r = s.get_dupe_groups(f) eq_(len(r), 1) eq_(len(r[0]), 2) s.min_match_percentage = 0 r = s.get_dupe_groups(f) eq_(len(r), 1) eq_(len(r[0]), 2) def test_content_scan_doesnt_put_digest_in_words_at_the_end(fake_fileexists): s = Scanner() s.scan_type = ScanType.CONTENTS f = [no("foo"), no("bar")] f[0].digest = f[0].digest_partial = f[0].digest_samples = ( "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" ) f[1].digest = f[1].digest_partial = f[1].digest_samples = ( "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" ) r = s.get_dupe_groups(f) # FIXME looks like we are missing something here? r[0] def test_extension_is_not_counted_in_filename_scan(fake_fileexists): s = Scanner() s.min_match_percentage = 100 f = [no("foo.bar"), no("foo.bleh")] r = s.get_dupe_groups(f) eq_(len(r), 1) eq_(len(r[0]), 2) def test_job(fake_fileexists): def do_progress(progress, desc=""): log.append(progress) return True s = Scanner() log = [] f = [no("foo bar"), no("foo bar"), no("foo bleh")] s.get_dupe_groups(f, j=job.Job(1, do_progress)) eq_(log[0], 0) eq_(log[-1], 100) def test_mix_file_kind(fake_fileexists): s = Scanner() s.mix_file_kind = False f = [no("foo.1"), no("foo.2")] r = s.get_dupe_groups(f) eq_(len(r), 0) def test_word_weighting(fake_fileexists): s = Scanner() s.min_match_percentage = 75 s.word_weighting = True f = [no("foo bar"), no("foo bar bleh")] r = s.get_dupe_groups(f) eq_(len(r), 1) g = r[0] m = g.get_match_of(g.dupes[0]) eq_(m.percentage, 75) # 16 letters, 12 matching def test_similar_words(fake_fileexists): s = Scanner() s.match_similar_words = True f = [ no("The White Stripes"), no("The Whites Stripe"), no("Limp Bizkit"), no("Limp Bizkitt"), ] r = s.get_dupe_groups(f) eq_(len(r), 2) def test_fields(fake_fileexists): s = Scanner() s.scan_type = ScanType.FIELDS f = [no("The White Stripes - Little Ghost"), no("The White Stripes - Little Acorn")] r = s.get_dupe_groups(f) eq_(len(r), 0) def test_fields_no_order(fake_fileexists): s = Scanner() s.scan_type = ScanType.FIELDSNOORDER f = [no("The White Stripes - Little Ghost"), no("Little Ghost - The White Stripes")] r = s.get_dupe_groups(f) eq_(len(r), 1) def test_tag_scan(fake_fileexists): s = Scanner() s.scan_type = ScanType.TAG o1 = no("foo") o2 = no("bar") o1.artist = "The White Stripes" o1.title = "The Air Near My Fingers" o2.artist = "The White Stripes" o2.title = "The Air Near My Fingers" r = s.get_dupe_groups([o1, o2]) eq_(len(r), 1) def test_tag_with_album_scan(fake_fileexists): s = Scanner() s.scan_type = ScanType.TAG s.scanned_tags = {"artist", "album", "title"} o1 = no("foo") o2 = no("bar") o3 = no("bleh") o1.artist = "The White Stripes" o1.title = "The Air Near My Fingers" o1.album = "Elephant" o2.artist = "The White Stripes" o2.title = "The Air Near My Fingers" o2.album = "Elephant" o3.artist = "The White Stripes" o3.title = "The Air Near My Fingers" o3.album = "foobar" r = s.get_dupe_groups([o1, o2, o3]) eq_(len(r), 1) def test_that_dash_in_tags_dont_create_new_fields(fake_fileexists): s = Scanner() s.scan_type = ScanType.TAG s.scanned_tags = {"artist", "album", "title"} s.min_match_percentage = 50 o1 = no("foo") o2 = no("bar") o1.artist = "The White Stripes - a" o1.title = "The Air Near My Fingers - a" o1.album = "Elephant - a" o2.artist = "The White Stripes - b" o2.title = "The Air Near My Fingers - b" o2.album = "Elephant - b" r = s.get_dupe_groups([o1, o2]) eq_(len(r), 1) def test_tag_scan_with_different_scanned(fake_fileexists): s = Scanner() s.scan_type = ScanType.TAG s.scanned_tags = {"track", "year"} o1 = no("foo") o2 = no("bar") o1.artist = "The White Stripes" o1.title = "some title" o1.track = "foo" o1.year = "bar" o2.artist = "The White Stripes" o2.title = "another title" o2.track = "foo" o2.year = "bar" r = s.get_dupe_groups([o1, o2]) eq_(len(r), 1) def test_tag_scan_only_scans_existing_tags(fake_fileexists): s = Scanner() s.scan_type = ScanType.TAG s.scanned_tags = {"artist", "foo"} o1 = no("foo") o2 = no("bar") o1.artist = "The White Stripes" o1.foo = "foo" o2.artist = "The White Stripes" o2.foo = "bar" r = s.get_dupe_groups([o1, o2]) eq_(len(r), 1) # Because 'foo' is not scanned, they match def test_tag_scan_converts_to_str(fake_fileexists): s = Scanner() s.scan_type = ScanType.TAG s.scanned_tags = {"track"} o1 = no("foo") o2 = no("bar") o1.track = 42 o2.track = 42 try: r = s.get_dupe_groups([o1, o2]) except TypeError: raise AssertionError() eq_(len(r), 1) def test_tag_scan_non_ascii(fake_fileexists): s = Scanner() s.scan_type = ScanType.TAG s.scanned_tags = {"title"} o1 = no("foo") o2 = no("bar") o1.title = "foobar\u00e9" o2.title = "foobar\u00e9" try: r = s.get_dupe_groups([o1, o2]) except UnicodeEncodeError: raise AssertionError() eq_(len(r), 1) def test_ignore_list(fake_fileexists): s = Scanner() f1 = no("foobar") f2 = no("foobar") f3 = no("foobar") f1.path = Path("dir1/foobar") f2.path = Path("dir2/foobar") f3.path = Path("dir3/foobar") ignore_list = IgnoreList() ignore_list.ignore(str(f1.path), str(f2.path)) ignore_list.ignore(str(f1.path), str(f3.path)) r = s.get_dupe_groups([f1, f2, f3], ignore_list=ignore_list) eq_(len(r), 1) g = r[0] eq_(len(g.dupes), 1) assert f1 not in g assert f2 in g assert f3 in g # Ignored matches are not counted as discarded eq_(s.discarded_file_count, 0) def test_ignore_list_checks_for_unicode(fake_fileexists): # scanner was calling path_str for ignore list checks. Since the Path changes, it must # be unicode(path) s = Scanner() f1 = no("foobar") f2 = no("foobar") f3 = no("foobar") f1.path = Path("foo1\u00e9") f2.path = Path("foo2\u00e9") f3.path = Path("foo3\u00e9") ignore_list = IgnoreList() ignore_list.ignore(str(f1.path), str(f2.path)) ignore_list.ignore(str(f1.path), str(f3.path)) r = s.get_dupe_groups([f1, f2, f3], ignore_list=ignore_list) eq_(len(r), 1) g = r[0] eq_(len(g.dupes), 1) assert f1 not in g assert f2 in g assert f3 in g def test_file_evaluates_to_false(fake_fileexists): # A very wrong way to use any() was added at some point, causing resulting group list # to be empty. class FalseNamedObject(NamedObject): def __bool__(self): return False s = Scanner() f1 = FalseNamedObject("foobar", path="p1") f2 = FalseNamedObject("foobar", path="p2") r = s.get_dupe_groups([f1, f2]) eq_(len(r), 1) def test_size_threshold(fake_fileexists): # Only file equal or higher than the size_threshold in size are scanned s = Scanner() f1 = no("foo", 1, path="p1") f2 = no("foo", 2, path="p2") f3 = no("foo", 3, path="p3") s.size_threshold = 2 groups = s.get_dupe_groups([f1, f2, f3]) eq_(len(groups), 1) [group] = groups eq_(len(group), 2) assert f1 not in group assert f2 in group assert f3 in group def test_tie_breaker_path_deepness(fake_fileexists): # If there is a tie in prioritization, path deepness is used as a tie breaker s = Scanner() o1, o2 = no("foo"), no("foo") o1.path = Path("foo") o2.path = Path("foo/bar") [group] = s.get_dupe_groups([o1, o2]) assert group.ref is o2 def test_tie_breaker_copy(fake_fileexists): # if copy is in the words used (even if it has a deeper path), it becomes a dupe s = Scanner() o1, o2 = no("foo bar Copy"), no("foo bar") o1.path = Path("deeper/path") o2.path = Path("foo") [group] = s.get_dupe_groups([o1, o2]) assert group.ref is o2 def test_tie_breaker_same_name_plus_digit(fake_fileexists): # if ref has the same words as dupe, but has some just one extra word which is a digit, it # becomes a dupe s = Scanner() o1 = no("foo bar 42") o2 = no("foo bar [42]") o3 = no("foo bar (42)") o4 = no("foo bar {42}") o5 = no("foo bar") # all numbered names have deeper paths, so they'll end up ref if the digits aren't correctly # used as tie breakers o1.path = Path("deeper/path") o2.path = Path("deeper/path") o3.path = Path("deeper/path") o4.path = Path("deeper/path") o5.path = Path("foo") [group] = s.get_dupe_groups([o1, o2, o3, o4, o5]) assert group.ref is o5 def test_partial_group_match(fake_fileexists): # Count the number of discarded matches (when a file doesn't match all other dupes of the # group) in Scanner.discarded_file_count s = Scanner() o1, o2, o3 = no("a b"), no("a"), no("b") s.min_match_percentage = 50 [group] = s.get_dupe_groups([o1, o2, o3]) eq_(len(group), 2) assert o1 in group # The file that will actually be counted as a dupe is undefined. The only thing we want to test # is that we don't have both if o2 in group: assert o3 not in group else: assert o3 in group eq_(s.discarded_file_count, 1) def test_dont_group_files_that_dont_exist(tmpdir): # when creating groups, check that files exist first. It's possible that these files have # been moved during the scan by the user. # In this test, we have to delete one of the files between the get_matches() part and the # get_groups() part. s = Scanner() s.scan_type = ScanType.CONTENTS p = Path(str(tmpdir)) with p.joinpath("file1").open("w") as fp: fp.write("foo") with p.joinpath("file2").open("w") as fp: fp.write("foo") file1, file2 = fs.get_files(p) def getmatches(*args, **kw): file2.path.unlink() return [Match(file1, file2, 100)] s._getmatches = getmatches assert not s.get_dupe_groups([file1, file2]) def test_folder_scan_exclude_subfolder_matches(fake_fileexists): # when doing a Folders scan type, don't include matches for folders whose parent folder already # match. s = Scanner() s.scan_type = ScanType.FOLDERS topf1 = no("top folder 1", size=42) topf1.digest = topf1.digest_partial = topf1.digest_samples = b"some_digest__1" topf1.path = Path("/topf1") topf2 = no("top folder 2", size=42) topf2.digest = topf2.digest_partial = topf2.digest_samples = b"some_digest__1" topf2.path = Path("/topf2") subf1 = no("sub folder 1", size=41) subf1.digest = subf1.digest_partial = subf1.digest_samples = b"some_digest__2" subf1.path = Path("/topf1/sub") subf2 = no("sub folder 2", size=41) subf2.digest = subf2.digest_partial = subf2.digest_samples = b"some_digest__2" subf2.path = Path("/topf2/sub") eq_(len(s.get_dupe_groups([topf1, topf2, subf1, subf2])), 1) # only top folders # however, if another folder matches a subfolder, keep in in the matches otherf = no("other folder", size=41) otherf.digest = otherf.digest_partial = otherf.digest_samples = b"some_digest__2" otherf.path = Path("/otherfolder") eq_(len(s.get_dupe_groups([topf1, topf2, subf1, subf2, otherf])), 2) def test_ignore_files_with_same_path(fake_fileexists): # It's possible that the scanner is fed with two file instances pointing to the same path. One # of these files has to be ignored s = Scanner() f1 = no("foobar", path="path1/foobar") f2 = no("foobar", path="path1/foobar") eq_(s.get_dupe_groups([f1, f2]), []) def test_dont_count_ref_files_as_discarded(fake_fileexists): # To speed up the scan, we don't bother comparing contents of files that are both ref files. # However, this causes problems in "discarded" counting and we make sure here that we don't # report discarded matches in exact duplicate scans. s = Scanner() s.scan_type = ScanType.CONTENTS o1 = no("foo", path="p1") o2 = no("foo", path="p2") o3 = no("foo", path="p3") o1.digest = o1.digest_partial = o1.digest_samples = "foobar" o2.digest = o2.digest_partial = o2.digest_samples = "foobar" o3.digest = o3.digest_partial = o3.digest_samples = "foobar" o1.is_ref = True o2.is_ref = True eq_(len(s.get_dupe_groups([o1, o2, o3])), 1) eq_(s.discarded_file_count, 0) def test_prioritize_me(fake_fileexists): # in ScannerME, bitrate goes first (right after is_ref) in prioritization s = ScannerME() o1, o2 = no("foo", path="p1"), no("foo", path="p2") o1.bitrate = 1 o2.bitrate = 2 [group] = s.get_dupe_groups([o1, o2]) assert group.ref is o2
20,264
Python
.py
553
31.499096
108
0.626842
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,165
prioritize_test.py
arsenetar_dupeguru/core/tests/prioritize_test.py
# Created By: Virgil Dupras # Created On: 2011/09/07 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import os.path as op from itertools import combinations from core.tests.base import TestApp, NamedObject, with_app, eq_ from core.engine import Group, Match no = NamedObject def app_with_dupes(dupes): # Creates an app with specified dupes. dupes is a list of lists, each list in the list being # a dupe group. We cheat a little bit by creating dupe groups manually instead of running a # dupe scan, but it simplifies the test code quite a bit app = TestApp() groups = [] for dupelist in dupes: g = Group() for dupe1, dupe2 in combinations(dupelist, 2): g.add_match(Match(dupe1, dupe2, 100)) groups.append(g) app.app.results.groups = groups app.app._results_changed() return app # --- def app_normal_results(): # Just some results, with different extensions and size, for good measure. dupes = [ [ no("foo1.ext1", size=1, folder="folder1"), no("foo2.ext2", size=2, folder="folder2"), ], ] return app_with_dupes(dupes) @with_app(app_normal_results) def test_kind_subcrit(app): # The subcriteria of the "Kind" criteria is a list of extensions contained in the dupes. app.select_pri_criterion("Kind") eq_(app.pdialog.criteria_list[:], ["ext1", "ext2"]) @with_app(app_normal_results) def test_kind_reprioritization(app): # Just a simple test of the system as a whole. # select a criterion, and perform re-prioritization and see if it worked. app.select_pri_criterion("Kind") app.pdialog.criteria_list.select([1]) # ext2 app.pdialog.add_selected() app.pdialog.perform_reprioritization() eq_(app.rtable[0].data["name"], "foo2.ext2") @with_app(app_normal_results) def test_folder_subcrit(app): app.select_pri_criterion("Folder") eq_(app.pdialog.criteria_list[:], ["folder1", "folder2"]) @with_app(app_normal_results) def test_folder_reprioritization(app): app.select_pri_criterion("Folder") app.pdialog.criteria_list.select([1]) # folder2 app.pdialog.add_selected() app.pdialog.perform_reprioritization() eq_(app.rtable[0].data["name"], "foo2.ext2") @with_app(app_normal_results) def test_prilist_display(app): # The prioritization list displays selected criteria correctly. app.select_pri_criterion("Kind") app.pdialog.criteria_list.select([1]) # ext2 app.pdialog.add_selected() app.select_pri_criterion("Folder") app.pdialog.criteria_list.select([1]) # folder2 app.pdialog.add_selected() app.select_pri_criterion("Size") app.pdialog.criteria_list.select([1]) # Lowest app.pdialog.add_selected() expected = [ "Kind (ext2)", "Folder (folder2)", "Size (Lowest)", ] eq_(app.pdialog.prioritization_list[:], expected) @with_app(app_normal_results) def test_size_subcrit(app): app.select_pri_criterion("Size") eq_(app.pdialog.criteria_list[:], ["Highest", "Lowest"]) @with_app(app_normal_results) def test_size_reprioritization(app): app.select_pri_criterion("Size") app.pdialog.criteria_list.select([0]) # highest app.pdialog.add_selected() app.pdialog.perform_reprioritization() eq_(app.rtable[0].data["name"], "foo2.ext2") @with_app(app_normal_results) def test_reorder_prioritizations(app): app.add_pri_criterion("Kind", 0) # ext1 app.add_pri_criterion("Kind", 1) # ext2 app.pdialog.prioritization_list.move_indexes([1], 0) expected = [ "Kind (ext2)", "Kind (ext1)", ] eq_(app.pdialog.prioritization_list[:], expected) @with_app(app_normal_results) def test_remove_crit_from_list(app): app.add_pri_criterion("Kind", 0) app.add_pri_criterion("Kind", 1) app.pdialog.prioritization_list.select(0) app.pdialog.remove_selected() expected = [ "Kind (ext2)", ] eq_(app.pdialog.prioritization_list[:], expected) @with_app(app_normal_results) def test_add_crit_without_selection(app): # Adding a criterion without having made a selection doesn't cause a crash. app.pdialog.add_selected() # no crash # --- def app_one_name_ends_with_number(): dupes = [ [no("foo.ext"), no("foo1.ext")], ] return app_with_dupes(dupes) @with_app(app_one_name_ends_with_number) def test_filename_reprioritization(app): app.add_pri_criterion("Filename", 0) # Ends with a number app.pdialog.perform_reprioritization() eq_(app.rtable[0].data["name"], "foo1.ext") # --- def app_with_subfolders(): dupes = [ [no("foo1", folder="baz"), no("foo2", folder="foo/bar")], [no("foo3", folder="baz"), no("foo4", folder="foo")], ] return app_with_dupes(dupes) @with_app(app_with_subfolders) def test_folder_crit_is_sorted(app): # Folder subcriteria are sorted. app.select_pri_criterion("Folder") eq_(app.pdialog.criteria_list[:], ["baz", "foo", op.join("foo", "bar")]) @with_app(app_with_subfolders) def test_folder_crit_includes_subfolders(app): # When selecting a folder crit, dupes in a subfolder are also considered as affected by that # crit. app.add_pri_criterion("Folder", 1) # foo app.pdialog.perform_reprioritization() # Both foo and foo/bar dupes will be prioritized eq_(app.rtable[0].data["name"], "foo2") eq_(app.rtable[2].data["name"], "foo4") @with_app(app_with_subfolders) def test_display_something_on_empty_extensions(app): # When there's no extension, display "None" instead of nothing at all. app.select_pri_criterion("Kind") eq_(app.pdialog.criteria_list[:], ["None"]) # --- def app_one_name_longer_than_the_other(): dupes = [ [no("shortest.ext"), no("loooongest.ext")], ] return app_with_dupes(dupes) @with_app(app_one_name_longer_than_the_other) def test_longest_filename_prioritization(app): app.add_pri_criterion("Filename", 2) # Longest app.pdialog.perform_reprioritization() eq_(app.rtable[0].data["name"], "loooongest.ext")
6,310
Python
.py
162
34.425926
96
0.687961
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,166
ignore_test.py
arsenetar_dupeguru/core/tests/ignore_test.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import io from xml.etree import ElementTree as ET from pytest import raises from hscommon.testutil import eq_ from core.ignore import IgnoreList def test_empty(): il = IgnoreList() eq_(0, len(il)) assert not il.are_ignored("foo", "bar") def test_simple(): il = IgnoreList() il.ignore("foo", "bar") assert il.are_ignored("foo", "bar") assert il.are_ignored("bar", "foo") assert not il.are_ignored("foo", "bleh") assert not il.are_ignored("bleh", "bar") eq_(1, len(il)) def test_multiple(): il = IgnoreList() il.ignore("foo", "bar") il.ignore("foo", "bleh") il.ignore("bleh", "bar") il.ignore("aybabtu", "bleh") assert il.are_ignored("foo", "bar") assert il.are_ignored("bar", "foo") assert il.are_ignored("foo", "bleh") assert il.are_ignored("bleh", "bar") assert not il.are_ignored("aybabtu", "bar") eq_(4, len(il)) def test_clear(): il = IgnoreList() il.ignore("foo", "bar") il.clear() assert not il.are_ignored("foo", "bar") assert not il.are_ignored("bar", "foo") eq_(0, len(il)) def test_add_same_twice(): il = IgnoreList() il.ignore("foo", "bar") il.ignore("bar", "foo") eq_(1, len(il)) def test_save_to_xml(): il = IgnoreList() il.ignore("foo", "bar") il.ignore("foo", "bleh") il.ignore("bleh", "bar") f = io.BytesIO() il.save_to_xml(f) f.seek(0) doc = ET.parse(f) root = doc.getroot() eq_(root.tag, "ignore_list") eq_(len(root), 2) eq_(len([c for c in root if c.tag == "file"]), 2) f1, f2 = root[:] subchildren = [c for c in f1 if c.tag == "file"] + [c for c in f2 if c.tag == "file"] eq_(len(subchildren), 3) def test_save_then_load(): il = IgnoreList() il.ignore("foo", "bar") il.ignore("foo", "bleh") il.ignore("bleh", "bar") il.ignore("\u00e9", "bar") f = io.BytesIO() il.save_to_xml(f) f.seek(0) il = IgnoreList() il.load_from_xml(f) eq_(4, len(il)) assert il.are_ignored("\u00e9", "bar") def test_load_xml_with_empty_file_tags(): f = io.BytesIO() f.write(b'<?xml version="1.0" encoding="utf-8"?><ignore_list><file><file/></file></ignore_list>') f.seek(0) il = IgnoreList() il.load_from_xml(f) eq_(0, len(il)) def test_are_ignore_works_when_a_child_is_a_key_somewhere_else(): il = IgnoreList() il.ignore("foo", "bar") il.ignore("bar", "baz") assert il.are_ignored("bar", "foo") def test_no_dupes_when_a_child_is_a_key_somewhere_else(): il = IgnoreList() il.ignore("foo", "bar") il.ignore("bar", "baz") il.ignore("bar", "foo") eq_(2, len(il)) def test_iterate(): # It must be possible to iterate through ignore list il = IgnoreList() expected = [("foo", "bar"), ("bar", "baz"), ("foo", "baz")] for i in expected: il.ignore(i[0], i[1]) for i in il: expected.remove(i) # No exception should be raised assert not expected # expected should be empty def test_filter(): il = IgnoreList() il.ignore("foo", "bar") il.ignore("bar", "baz") il.ignore("foo", "baz") il.filter(lambda f, s: f == "bar") eq_(1, len(il)) assert not il.are_ignored("foo", "bar") assert il.are_ignored("bar", "baz") def test_save_with_non_ascii_items(): il = IgnoreList() il.ignore("\xac", "\xbf") f = io.BytesIO() try: il.save_to_xml(f) except Exception as e: raise AssertionError(str(e)) def test_len(): il = IgnoreList() eq_(0, len(il)) il.ignore("foo", "bar") eq_(1, len(il)) def test_nonzero(): il = IgnoreList() assert not il il.ignore("foo", "bar") assert il def test_remove(): il = IgnoreList() il.ignore("foo", "bar") il.ignore("foo", "baz") il.remove("bar", "foo") eq_(len(il), 1) assert not il.are_ignored("foo", "bar") def test_remove_non_existant(): il = IgnoreList() il.ignore("foo", "bar") il.ignore("foo", "baz") with raises(ValueError): il.remove("foo", "bleh")
4,351
Python
.py
142
26
101
0.604746
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,167
cache_test.py
arsenetar_dupeguru/core/tests/cache_test.py
# Copyright 2016 Virgil Dupras # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import logging from pytest import raises, skip from hscommon.testutil import eq_ try: from core.pe.cache import colors_to_bytes, bytes_to_colors from core.pe.cache_sqlite import SqliteCache except ImportError: skip("Can't import the cache module, probably hasn't been compiled.") class TestCaseColorsToString: def test_no_color(self): eq_(b"", colors_to_bytes([])) def test_single_color(self): eq_(b"\x00\x00\x00", colors_to_bytes([(0, 0, 0)])) eq_(b"\x01\x01\x01", colors_to_bytes([(1, 1, 1)])) eq_(b"\x0a\x14\x1e", colors_to_bytes([(10, 20, 30)])) def test_two_colors(self): eq_(b"\x00\x01\x02\x03\x04\x05", colors_to_bytes([(0, 1, 2), (3, 4, 5)])) class TestCaseStringToColors: def test_empty(self): eq_([], bytes_to_colors(b"")) def test_single_color(self): eq_([(0, 0, 0)], bytes_to_colors(b"\x00\x00\x00")) eq_([(2, 3, 4)], bytes_to_colors(b"\x02\x03\x04")) eq_([(10, 20, 30)], bytes_to_colors(b"\x0a\x14\x1e")) def test_two_colors(self): eq_([(10, 20, 30), (40, 50, 60)], bytes_to_colors(b"\x0a\x14\x1e\x28\x32\x3c")) def test_incomplete_color(self): # don't return anything if it's not a complete color eq_([], bytes_to_colors(b"\x01")) eq_([(1, 2, 3)], bytes_to_colors(b"\x01\x02\x03\x04")) class BaseTestCaseCache: def get_cache(self, dbname=None): raise NotImplementedError() def test_empty(self): c = self.get_cache() eq_(0, len(c)) with raises(KeyError): c["foo"] def test_set_then_retrieve_blocks(self): c = self.get_cache() b = [[(0, 0, 0), (1, 2, 3)]] * 8 c["foo"] = b eq_(b, c["foo"]) def test_delitem(self): c = self.get_cache() c["foo"] = [[]] * 8 del c["foo"] assert "foo" not in c with raises(KeyError): del c["foo"] def test_persistance(self, tmpdir): DBNAME = tmpdir.join("hstest.db") c = self.get_cache(str(DBNAME)) c["foo"] = [[(1, 2, 3)]] * 8 del c c = self.get_cache(str(DBNAME)) eq_([[(1, 2, 3)]] * 8, c["foo"]) def test_filter(self): c = self.get_cache() c["foo"] = [[]] * 8 c["bar"] = [[]] * 8 c["baz"] = [[]] * 8 c.filter(lambda p: p != "bar") # only 'bar' is removed eq_(2, len(c)) assert "foo" in c assert "baz" in c assert "bar" not in c def test_clear(self): c = self.get_cache() c["foo"] = [[]] * 8 c["bar"] = [[]] * 8 c["baz"] = [[]] * 8 c.clear() eq_(0, len(c)) assert "foo" not in c assert "baz" not in c assert "bar" not in c def test_by_id(self): # it's possible to use the cache by referring to the files by their row_id c = self.get_cache() b = [[(0, 0, 0), (1, 2, 3)]] * 8 c["foo"] = b foo_id = c.get_id("foo") eq_(c[foo_id], b) class TestCaseSqliteCache(BaseTestCaseCache): def get_cache(self, dbname=None): if dbname: return SqliteCache(dbname) else: return SqliteCache() def test_corrupted_db(self, tmpdir, monkeypatch): # If we don't do this monkeypatching, we get a weird exception about trying to flush a # closed file. I've tried setting logging level and stuff, but nothing worked. So, there we # go, a dirty monkeypatch. monkeypatch.setattr(logging, "warning", lambda *args, **kw: None) dbname = str(tmpdir.join("foo.db")) fp = open(dbname, "w") fp.write("invalid sqlite content") fp.close() c = self.get_cache(dbname) # should not raise a DatabaseError c["foo"] = [[(1, 2, 3)]] * 8 del c c = self.get_cache(dbname) eq_(c["foo"], [[(1, 2, 3)]] * 8) class TestCaseCacheSQLEscape: def get_cache(self): return SqliteCache() def test_contains(self): c = self.get_cache() assert "foo'bar" not in c def test_getitem(self): c = self.get_cache() with raises(KeyError): c["foo'bar"] def test_setitem(self): c = self.get_cache() c["foo'bar"] = [] def test_delitem(self): c = self.get_cache() c["foo'bar"] = [[]] * 8 try: del c["foo'bar"] except KeyError: assert False
4,727
Python
.py
129
28.899225
99
0.554729
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,168
results_test.py
arsenetar_dupeguru/core/tests/results_test.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import io import os.path as op from xml.etree import ElementTree as ET from pytest import raises from hscommon.testutil import eq_ from hscommon.util import first from core import engine from core.tests.base import NamedObject, GetTestGroups, DupeGuru from core.results import Results class TestCaseResultsEmpty: def setup_method(self, method): self.app = DupeGuru() self.results = self.app.results def test_apply_invalid_filter(self): # If the applied filter is an invalid regexp, just ignore the filter. self.results.apply_filter("[") # invalid self.test_stat_line() # make sure that the stats line isn't saying we applied a '[' filter def test_stat_line(self): eq_("0 / 0 (0.00 B / 0.00 B) duplicates marked.", self.results.stat_line) def test_groups(self): eq_(0, len(self.results.groups)) def test_get_group_of_duplicate(self): assert self.results.get_group_of_duplicate("foo") is None def test_save_to_xml(self): f = io.BytesIO() self.results.save_to_xml(f) f.seek(0) doc = ET.parse(f) root = doc.getroot() eq_("results", root.tag) def test_is_modified(self): assert not self.results.is_modified def test_is_modified_after_setting_empty_group(self): # Don't consider results as modified if they're empty self.results.groups = [] assert not self.results.is_modified def test_save_to_same_name_as_folder(self, tmpdir): # Issue #149 # When saving to a filename that already exists, the file is overwritten. However, when # the name exists but that it's a folder, then there used to be a crash. The proper fix # would have been some kind of feedback to the user, but the work involved for something # that simply never happens (I never received a report of this crash, I experienced it # while fooling around) is too much. Instead, use standard name conflict resolution. folderpath = tmpdir.join("foo") folderpath.mkdir() self.results.save_to_xml(str(folderpath)) # no crash assert tmpdir.join("[000] foo").check() class TestCaseResultsWithSomeGroups: def setup_method(self, method): self.app = DupeGuru() self.results = self.app.results self.objects, self.matches, self.groups = GetTestGroups() self.results.groups = self.groups def test_stat_line(self): eq_("0 / 3 (0.00 B / 1.01 KB) duplicates marked.", self.results.stat_line) def test_groups(self): eq_(2, len(self.results.groups)) def test_get_group_of_duplicate(self): for o in self.objects: g = self.results.get_group_of_duplicate(o) assert isinstance(g, engine.Group) assert o in g assert self.results.get_group_of_duplicate(self.groups[0]) is None def test_remove_duplicates(self): g1, g2 = self.results.groups self.results.remove_duplicates([g1.dupes[0]]) eq_(2, len(g1)) assert g1 in self.results.groups self.results.remove_duplicates([g1.ref]) eq_(2, len(g1)) assert g1 in self.results.groups self.results.remove_duplicates([g1.dupes[0]]) eq_(0, len(g1)) assert g1 not in self.results.groups self.results.remove_duplicates([g2.dupes[0]]) eq_(0, len(g2)) assert g2 not in self.results.groups eq_(0, len(self.results.groups)) def test_remove_duplicates_with_ref_files(self): g1, g2 = self.results.groups self.objects[0].is_ref = True self.objects[1].is_ref = True self.results.remove_duplicates([self.objects[2]]) eq_(0, len(g1)) assert g1 not in self.results.groups def test_make_ref(self): g = self.results.groups[0] d = g.dupes[0] self.results.make_ref(d) assert d is g.ref def test_sort_groups(self): self.results.make_ref(self.objects[1]) # We want to make the 1024 sized object to go ref. g1, g2 = self.groups self.results.sort_groups("size") assert self.results.groups[0] is g2 assert self.results.groups[1] is g1 self.results.sort_groups("size", False) assert self.results.groups[0] is g1 assert self.results.groups[1] is g2 def test_set_groups_when_sorted(self): self.results.make_ref(self.objects[1]) # We want to make the 1024 sized object to go ref. self.results.sort_groups("size") objects, matches, groups = GetTestGroups() g1, g2 = groups g1.switch_ref(objects[1]) self.results.groups = groups assert self.results.groups[0] is g2 assert self.results.groups[1] is g1 def test_get_dupe_list(self): eq_([self.objects[1], self.objects[2], self.objects[4]], self.results.dupes) def test_dupe_list_is_cached(self): assert self.results.dupes is self.results.dupes def test_dupe_list_cache_is_invalidated_when_needed(self): o1, o2, o3, o4, o5 = self.objects eq_([o2, o3, o5], self.results.dupes) self.results.make_ref(o2) eq_([o1, o3, o5], self.results.dupes) objects, matches, groups = GetTestGroups() o1, o2, o3, o4, o5 = objects self.results.groups = groups eq_([o2, o3, o5], self.results.dupes) def test_dupe_list_sort(self): o1, o2, o3, o4, o5 = self.objects o1.size = 5 o2.size = 4 o3.size = 3 o4.size = 2 o5.size = 1 self.results.sort_dupes("size") eq_([o5, o3, o2], self.results.dupes) self.results.sort_dupes("size", False) eq_([o2, o3, o5], self.results.dupes) def test_dupe_list_remember_sort(self): o1, o2, o3, o4, o5 = self.objects o1.size = 5 o2.size = 4 o3.size = 3 o4.size = 2 o5.size = 1 self.results.sort_dupes("size") self.results.make_ref(o2) eq_([o5, o3, o1], self.results.dupes) def test_dupe_list_sort_delta_values(self): o1, o2, o3, o4, o5 = self.objects o1.size = 10 o2.size = 2 # -8 o3.size = 3 # -7 o4.size = 20 o5.size = 1 # -19 self.results.sort_dupes("size", delta=True) eq_([o5, o2, o3], self.results.dupes) def test_sort_empty_list(self): # There was an infinite loop when sorting an empty list. app = DupeGuru() r = app.results r.sort_dupes("name") eq_([], r.dupes) def test_dupe_list_update_on_remove_duplicates(self): o1, o2, o3, o4, o5 = self.objects eq_(3, len(self.results.dupes)) self.results.remove_duplicates([o2]) eq_(2, len(self.results.dupes)) def test_is_modified(self): # Changing the groups sets the modified flag assert self.results.is_modified def test_is_modified_after_save_and_load(self): # Saving/Loading a file sets the modified flag back to False def get_file(path): return [f for f in self.objects if str(f.path) == path][0] f = io.BytesIO() self.results.save_to_xml(f) assert not self.results.is_modified self.results.groups = self.groups # sets the flag back f.seek(0) self.results.load_from_xml(f, get_file) assert not self.results.is_modified def test_is_modified_after_removing_all_results(self): # Removing all results sets the is_modified flag to false. self.results.mark_all() self.results.perform_on_marked(lambda x: None, True) assert not self.results.is_modified def test_group_of_duplicate_after_removal(self): # removing a duplicate also removes it from the dupe:group map. dupe = self.results.groups[1].dupes[0] ref = self.results.groups[1].ref self.results.remove_duplicates([dupe]) assert self.results.get_group_of_duplicate(dupe) is None # also remove group ref assert self.results.get_group_of_duplicate(ref) is None def test_dupe_list_sort_delta_values_nonnumeric(self): # When sorting dupes in delta mode on a non-numeric column, our first sort criteria is if # the string is the same as its ref. g1r, g1d1, g1d2, g2r, g2d1 = self.objects # "aaa" makes our dupe go first in alphabetical order, but since we have the same value as # ref, we're going last. g2r.name = g2d1.name = "aaa" self.results.sort_dupes("name", delta=True) eq_("aaa", self.results.dupes[2].name) def test_dupe_list_sort_delta_values_nonnumeric_case_insensitive(self): # Non-numeric delta sorting comparison is case insensitive g1r, g1d1, g1d2, g2r, g2d1 = self.objects g2r.name = "AaA" g2d1.name = "aAa" self.results.sort_dupes("name", delta=True) eq_("aAa", self.results.dupes[2].name) class TestCaseResultsWithSavedResults: def setup_method(self, method): self.app = DupeGuru() self.results = self.app.results self.objects, self.matches, self.groups = GetTestGroups() self.results.groups = self.groups self.f = io.BytesIO() self.results.save_to_xml(self.f) self.f.seek(0) def test_is_modified(self): # Saving a file sets the modified flag back to False assert not self.results.is_modified def test_is_modified_after_load(self): # Loading a file sets the modified flag back to False def get_file(path): return [f for f in self.objects if str(f.path) == path][0] self.results.groups = self.groups # sets the flag back self.results.load_from_xml(self.f, get_file) assert not self.results.is_modified def test_is_modified_after_remove(self): # Removing dupes sets the modified flag self.results.remove_duplicates([self.results.groups[0].dupes[0]]) assert self.results.is_modified def test_is_modified_after_make_ref(self): # Making a dupe ref sets the modified flag self.results.make_ref(self.results.groups[0].dupes[0]) assert self.results.is_modified class TestCaseResultsMarkings: def setup_method(self, method): self.app = DupeGuru() self.results = self.app.results self.objects, self.matches, self.groups = GetTestGroups() self.results.groups = self.groups def test_stat_line(self): eq_("0 / 3 (0.00 B / 1.01 KB) duplicates marked.", self.results.stat_line) self.results.mark(self.objects[1]) eq_("1 / 3 (1.00 KB / 1.01 KB) duplicates marked.", self.results.stat_line) self.results.mark_invert() eq_("2 / 3 (2.00 B / 1.01 KB) duplicates marked.", self.results.stat_line) self.results.mark_invert() self.results.unmark(self.objects[1]) self.results.mark(self.objects[2]) self.results.mark(self.objects[4]) eq_("2 / 3 (2.00 B / 1.01 KB) duplicates marked.", self.results.stat_line) self.results.mark(self.objects[0]) # this is a ref, it can't be counted eq_("2 / 3 (2.00 B / 1.01 KB) duplicates marked.", self.results.stat_line) self.results.groups = self.groups eq_("0 / 3 (0.00 B / 1.01 KB) duplicates marked.", self.results.stat_line) def test_with_ref_duplicate(self): self.objects[1].is_ref = True self.results.groups = self.groups assert not self.results.mark(self.objects[1]) self.results.mark(self.objects[2]) eq_("1 / 2 (1.00 B / 2.00 B) duplicates marked.", self.results.stat_line) def test_perform_on_marked(self): def log_object(o): log.append(o) return True log = [] self.results.mark_all() self.results.perform_on_marked(log_object, False) assert self.objects[1] in log assert self.objects[2] in log assert self.objects[4] in log eq_(3, len(log)) log = [] self.results.mark_none() self.results.mark(self.objects[4]) self.results.perform_on_marked(log_object, True) eq_(1, len(log)) assert self.objects[4] in log eq_(1, len(self.results.groups)) def test_perform_on_marked_with_problems(self): def log_object(o): log.append(o) if o is self.objects[1]: raise OSError("foobar") log = [] self.results.mark_all() assert self.results.is_marked(self.objects[1]) self.results.perform_on_marked(log_object, True) eq_(len(log), 3) eq_(len(self.results.groups), 1) eq_(len(self.results.groups[0]), 2) assert self.objects[1] in self.results.groups[0] assert not self.results.is_marked(self.objects[2]) assert self.results.is_marked(self.objects[1]) eq_(len(self.results.problems), 1) dupe, msg = self.results.problems[0] assert dupe is self.objects[1] eq_(msg, "foobar") def test_perform_on_marked_with_ref(self): def log_object(o): log.append(o) return True log = [] self.objects[0].is_ref = True self.objects[1].is_ref = True self.results.mark_all() self.results.perform_on_marked(log_object, True) assert self.objects[1] not in log assert self.objects[2] in log assert self.objects[4] in log eq_(2, len(log)) eq_(0, len(self.results.groups)) def test_perform_on_marked_remove_objects_only_at_the_end(self): def check_groups(o): eq_(3, len(g1)) eq_(2, len(g2)) return True g1, g2 = self.results.groups self.results.mark_all() self.results.perform_on_marked(check_groups, True) eq_(0, len(g1)) eq_(0, len(g2)) eq_(0, len(self.results.groups)) def test_remove_duplicates(self): g1 = self.results.groups[0] self.results.mark(g1.dupes[0]) eq_("1 / 3 (1.00 KB / 1.01 KB) duplicates marked.", self.results.stat_line) self.results.remove_duplicates([g1.dupes[1]]) eq_("1 / 2 (1.00 KB / 1.01 KB) duplicates marked.", self.results.stat_line) self.results.remove_duplicates([g1.dupes[0]]) eq_("0 / 1 (0.00 B / 1.00 B) duplicates marked.", self.results.stat_line) def test_make_ref(self): g = self.results.groups[0] d = g.dupes[0] self.results.mark(d) eq_("1 / 3 (1.00 KB / 1.01 KB) duplicates marked.", self.results.stat_line) self.results.make_ref(d) eq_("0 / 3 (0.00 B / 3.00 B) duplicates marked.", self.results.stat_line) self.results.make_ref(d) eq_("0 / 3 (0.00 B / 3.00 B) duplicates marked.", self.results.stat_line) def test_save_xml(self): self.results.mark(self.objects[1]) self.results.mark_invert() f = io.BytesIO() self.results.save_to_xml(f) f.seek(0) doc = ET.parse(f) root = doc.getroot() g1, g2 = root.iter("group") d1, d2, d3 = g1.iter("file") eq_("n", d1.get("marked")) eq_("n", d2.get("marked")) eq_("y", d3.get("marked")) d1, d2 = g2.iter("file") eq_("n", d1.get("marked")) eq_("y", d2.get("marked")) def test_load_xml(self): def get_file(path): return [f for f in self.objects if str(f.path) == path][0] self.objects[4].name = "ibabtu 2" # we can't have 2 files with the same path self.results.mark(self.objects[1]) self.results.mark_invert() f = io.BytesIO() self.results.save_to_xml(f) f.seek(0) app = DupeGuru() r = Results(app) r.load_from_xml(f, get_file) assert not r.is_marked(self.objects[0]) assert not r.is_marked(self.objects[1]) assert r.is_marked(self.objects[2]) assert not r.is_marked(self.objects[3]) assert r.is_marked(self.objects[4]) class TestCaseResultsXML: def setup_method(self, method): self.app = DupeGuru() self.results = self.app.results self.objects, self.matches, self.groups = GetTestGroups() self.results.groups = self.groups def get_file(self, path): # use this as a callback for load_from_xml return [o for o in self.objects if str(o.path) == path][0] def test_save_to_xml(self): self.objects[0].is_ref = True self.objects[0].words = [["foo", "bar"]] f = io.BytesIO() self.results.save_to_xml(f) f.seek(0) doc = ET.parse(f) root = doc.getroot() eq_("results", root.tag) eq_(2, len(root)) eq_(2, len([c for c in root if c.tag == "group"])) g1, g2 = root eq_(6, len(g1)) eq_(3, len([c for c in g1 if c.tag == "file"])) eq_(3, len([c for c in g1 if c.tag == "match"])) d1, d2, d3 = (c for c in g1 if c.tag == "file") eq_(op.join("basepath", "foo bar"), d1.get("path")) eq_(op.join("basepath", "bar bleh"), d2.get("path")) eq_(op.join("basepath", "foo bleh"), d3.get("path")) eq_("y", d1.get("is_ref")) eq_("n", d2.get("is_ref")) eq_("n", d3.get("is_ref")) eq_("foo,bar", d1.get("words")) eq_("bar,bleh", d2.get("words")) eq_("foo,bleh", d3.get("words")) eq_(3, len(g2)) eq_(2, len([c for c in g2 if c.tag == "file"])) eq_(1, len([c for c in g2 if c.tag == "match"])) d1, d2 = (c for c in g2 if c.tag == "file") eq_(op.join("basepath", "ibabtu"), d1.get("path")) eq_(op.join("basepath", "ibabtu"), d2.get("path")) eq_("n", d1.get("is_ref")) eq_("n", d2.get("is_ref")) eq_("ibabtu", d1.get("words")) eq_("ibabtu", d2.get("words")) def test_load_xml(self): def get_file(path): return [f for f in self.objects if str(f.path) == path][0] self.objects[0].is_ref = True self.objects[4].name = "ibabtu 2" # we can't have 2 files with the same path f = io.BytesIO() self.results.save_to_xml(f) f.seek(0) app = DupeGuru() r = Results(app) r.load_from_xml(f, get_file) eq_(2, len(r.groups)) g1, g2 = r.groups eq_(3, len(g1)) assert g1[0].is_ref assert not g1[1].is_ref assert not g1[2].is_ref assert g1[0] is self.objects[0] assert g1[1] is self.objects[1] assert g1[2] is self.objects[2] eq_(["foo", "bar"], g1[0].words) eq_(["bar", "bleh"], g1[1].words) eq_(["foo", "bleh"], g1[2].words) eq_(2, len(g2)) assert not g2[0].is_ref assert not g2[1].is_ref assert g2[0] is self.objects[3] assert g2[1] is self.objects[4] eq_(["ibabtu"], g2[0].words) eq_(["ibabtu"], g2[1].words) def test_load_xml_with_filename(self, tmpdir): def get_file(path): return [f for f in self.objects if str(f.path) == path][0] filename = str(tmpdir.join("dupeguru_results.xml")) self.objects[4].name = "ibabtu 2" # we can't have 2 files with the same path self.results.save_to_xml(filename) app = DupeGuru() r = Results(app) r.load_from_xml(filename, get_file) eq_(2, len(r.groups)) def test_load_xml_with_some_files_that_dont_exist_anymore(self): def get_file(path): if path.endswith("ibabtu 2"): return None return [f for f in self.objects if str(f.path) == path][0] self.objects[4].name = "ibabtu 2" # we can't have 2 files with the same path f = io.BytesIO() self.results.save_to_xml(f) f.seek(0) app = DupeGuru() r = Results(app) r.load_from_xml(f, get_file) eq_(1, len(r.groups)) eq_(3, len(r.groups[0])) def test_load_xml_missing_attributes_and_bogus_elements(self): def get_file(path): return [f for f in self.objects if str(f.path) == path][0] root = ET.Element("foobar") # The root element shouldn't matter, really. group_node = ET.SubElement(root, "group") dupe_node = ET.SubElement(group_node, "file") # Perfectly correct file dupe_node.set("path", op.join("basepath", "foo bar")) dupe_node.set("is_ref", "y") dupe_node.set("words", "foo, bar") dupe_node = ET.SubElement(group_node, "file") # is_ref missing, default to 'n' dupe_node.set("path", op.join("basepath", "foo bleh")) dupe_node.set("words", "foo, bleh") dupe_node = ET.SubElement(group_node, "file") # words are missing, valid. dupe_node.set("path", op.join("basepath", "bar bleh")) dupe_node = ET.SubElement(group_node, "file") # path is missing, invalid. dupe_node.set("words", "foo, bleh") dupe_node = ET.SubElement(group_node, "foobar") # Invalid element name dupe_node.set("path", op.join("basepath", "bar bleh")) dupe_node.set("is_ref", "y") dupe_node.set("words", "bar, bleh") match_node = ET.SubElement(group_node, "match") # match pointing to a bad index match_node.set("first", "42") match_node.set("second", "45") match_node = ET.SubElement(group_node, "match") # match with missing attrs match_node = ET.SubElement(group_node, "match") # match with non-int values match_node.set("first", "foo") match_node.set("second", "bar") match_node.set("percentage", "baz") group_node = ET.SubElement(root, "foobar") # invalid group group_node = ET.SubElement(root, "group") # empty group f = io.BytesIO() tree = ET.ElementTree(root) tree.write(f, encoding="utf-8") f.seek(0) app = DupeGuru() r = Results(app) r.load_from_xml(f, get_file) eq_(1, len(r.groups)) eq_(3, len(r.groups[0])) def test_xml_non_ascii(self): def get_file(path): if path == op.join("basepath", "\xe9foo bar"): return objects[0] if path == op.join("basepath", "bar bleh"): return objects[1] objects = [NamedObject("\xe9foo bar", True), NamedObject("bar bleh", True)] matches = engine.getmatches(objects) # we should have 5 matches groups = engine.get_groups(matches) # We should have 2 groups for g in groups: g.prioritize(lambda x: objects.index(x)) # We want the dupes to be in the same order as the list is app = DupeGuru() results = Results(app) results.groups = groups f = io.BytesIO() results.save_to_xml(f) f.seek(0) app = DupeGuru() r = Results(app) r.load_from_xml(f, get_file) g = r.groups[0] eq_("\xe9foo bar", g[0].name) eq_(["efoo", "bar"], g[0].words) def test_load_invalid_xml(self): f = io.BytesIO() f.write(b"<this is invalid") f.seek(0) app = DupeGuru() r = Results(app) with raises(ET.ParseError): r.load_from_xml(f, None) eq_(0, len(r.groups)) def test_load_non_existant_xml(self): app = DupeGuru() r = Results(app) with raises(IOError): r.load_from_xml("does_not_exist.xml", None) eq_(0, len(r.groups)) def test_remember_match_percentage(self): group = self.groups[0] d1, d2, d3 = group fake_matches = set() fake_matches.add(engine.Match(d1, d2, 42)) fake_matches.add(engine.Match(d1, d3, 43)) fake_matches.add(engine.Match(d2, d3, 46)) group.matches = fake_matches f = io.BytesIO() results = self.results results.save_to_xml(f) f.seek(0) app = DupeGuru() results = Results(app) results.load_from_xml(f, self.get_file) group = results.groups[0] d1, d2, d3 = group match = group.get_match_of(d2) # d1 - d2 eq_(42, match[2]) match = group.get_match_of(d3) # d1 - d3 eq_(43, match[2]) group.switch_ref(d2) match = group.get_match_of(d3) # d2 - d3 eq_(46, match[2]) def test_save_and_load(self): # previously, when reloading matches, they wouldn't be reloaded as namedtuples f = io.BytesIO() self.results.save_to_xml(f) f.seek(0) self.results.load_from_xml(f, self.get_file) first(self.results.groups[0].matches).percentage def test_apply_filter_works_on_paths(self): # apply_filter() searches on the whole path, not just on the filename. self.results.apply_filter("basepath") eq_(len(self.results.groups), 2) def test_save_xml_with_invalid_characters(self): # Don't crash when saving files that have invalid xml characters in their path self.objects[0].name = "foo\x19" self.results.save_to_xml(io.BytesIO()) # don't crash class TestCaseResultsFilter: def setup_method(self, method): self.app = DupeGuru() self.results = self.app.results self.objects, self.matches, self.groups = GetTestGroups() self.results.groups = self.groups self.results.apply_filter(r"foo") def test_groups(self): eq_(1, len(self.results.groups)) assert self.results.groups[0] is self.groups[0] def test_dupes(self): # There are 2 objects matching. The first one is ref. Only the 3rd one is supposed to be in dupes. eq_(1, len(self.results.dupes)) assert self.results.dupes[0] is self.objects[2] def test_cancel_filter(self): self.results.apply_filter(None) eq_(3, len(self.results.dupes)) eq_(2, len(self.results.groups)) def test_dupes_reconstructed_filtered(self): # make_ref resets self.__dupes to None. When it's reconstructed, we want it filtered dupe = self.results.dupes[0] # 3rd object self.results.make_ref(dupe) eq_(1, len(self.results.dupes)) assert self.results.dupes[0] is self.objects[0] def test_include_ref_dupes_in_filter(self): # When only the ref of a group match the filter, include it in the group self.results.apply_filter(None) self.results.apply_filter(r"foo bar") eq_(1, len(self.results.groups)) eq_(0, len(self.results.dupes)) def test_filters_build_on_one_another(self): self.results.apply_filter(r"bar") eq_(1, len(self.results.groups)) eq_(0, len(self.results.dupes)) def test_stat_line(self): expected = "0 / 1 (0.00 B / 1.00 B) duplicates marked. filter: foo" eq_(expected, self.results.stat_line) self.results.apply_filter(r"bar") expected = "0 / 0 (0.00 B / 0.00 B) duplicates marked. filter: foo --> bar" eq_(expected, self.results.stat_line) self.results.apply_filter(None) expected = "0 / 3 (0.00 B / 1.01 KB) duplicates marked." eq_(expected, self.results.stat_line) def test_mark_count_is_filtered_as_well(self): self.results.apply_filter(None) # We don't want to perform mark_all() because we want the mark list to contain objects for dupe in self.results.dupes: self.results.mark(dupe) self.results.apply_filter(r"foo") expected = "1 / 1 (1.00 B / 1.00 B) duplicates marked. filter: foo" eq_(expected, self.results.stat_line) def test_mark_all_only_affects_filtered_items(self): # When performing actions like mark_all() and mark_none in a filtered environment, only mark # items that are actually in the filter. self.results.mark_all() self.results.apply_filter(None) eq_(self.results.mark_count, 1) def test_sort_groups(self): self.results.apply_filter(None) self.results.make_ref(self.objects[1]) # to have the 1024 b obkect as ref g1, g2 = self.groups self.results.apply_filter("a") # Matches both group self.results.sort_groups("size") assert self.results.groups[0] is g2 assert self.results.groups[1] is g1 self.results.apply_filter(None) assert self.results.groups[0] is g2 assert self.results.groups[1] is g1 self.results.sort_groups("size", False) self.results.apply_filter("a") assert self.results.groups[1] is g2 assert self.results.groups[0] is g1 def test_set_group(self): # We want the new group to be filtered self.objects, self.matches, self.groups = GetTestGroups() self.results.groups = self.groups eq_(1, len(self.results.groups)) assert self.results.groups[0] is self.groups[0] def test_load_cancels_filter(self, tmpdir): def get_file(path): return [f for f in self.objects if str(f.path) == path][0] filename = str(tmpdir.join("dupeguru_results.xml")) self.objects[4].name = "ibabtu 2" # we can't have 2 files with the same path self.results.save_to_xml(filename) app = DupeGuru() r = Results(app) r.apply_filter("foo") r.load_from_xml(filename, get_file) eq_(2, len(r.groups)) def test_remove_dupe(self): self.results.remove_duplicates([self.results.dupes[0]]) self.results.apply_filter(None) eq_(2, len(self.results.groups)) eq_(2, len(self.results.dupes)) self.results.apply_filter("ibabtu") self.results.remove_duplicates([self.results.dupes[0]]) self.results.apply_filter(None) eq_(1, len(self.results.groups)) eq_(1, len(self.results.dupes)) def test_filter_is_case_insensitive(self): self.results.apply_filter(None) self.results.apply_filter("FOO") eq_(1, len(self.results.dupes)) def test_make_ref_on_filtered_out_doesnt_mess_stats(self): # When filtered, a group containing filtered out dupes will display them as being reference. # When calling make_ref on such a dupe, the total size and dupecount stats gets messed up # because they are *not* counted in the stats in the first place. g1, g2 = self.groups bar_bleh = g1[1] # The "bar bleh" dupe is filtered out self.results.make_ref(bar_bleh) # Now the stats should display *2* markable dupes (instead of 1) expected = "0 / 2 (0.00 B / 2.00 B) duplicates marked. filter: foo" eq_(expected, self.results.stat_line) self.results.apply_filter(None) # Now let's make sure our unfiltered results aren't fucked up expected = "0 / 3 (0.00 B / 3.00 B) duplicates marked." eq_(expected, self.results.stat_line) class TestCaseResultsRefFile: def setup_method(self, method): self.app = DupeGuru() self.results = self.app.results self.objects, self.matches, self.groups = GetTestGroups() self.objects[0].is_ref = True self.objects[1].is_ref = True self.results.groups = self.groups def test_stat_line(self): expected = "0 / 2 (0.00 B / 2.00 B) duplicates marked." eq_(expected, self.results.stat_line)
31,679
Python
.py
716
35.586592
112
0.609008
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,169
base.py
arsenetar_dupeguru/core/tests/base.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.testutil import TestApp as TestAppBase, CallLogger, eq_, with_app # noqa from pathlib import Path from hscommon.util import get_file_ext, format_size from hscommon.gui.column import Column from hscommon.jobprogress.job import nulljob, JobCancelled from core import engine, prioritize from core.engine import getwords from core.app import DupeGuru as DupeGuruBase from core.gui.result_table import ResultTable as ResultTableBase from core.gui.prioritize_dialog import PrioritizeDialog class DupeGuruView: JOB = nulljob def __init__(self): self.messages = [] def start_job(self, jobid, func, args=()): try: func(self.JOB, *args) except JobCancelled: return def get_default(self, key_name): return None def set_default(self, key_name, value): pass def show_message(self, msg): self.messages.append(msg) def ask_yes_no(self, prompt): return True # always answer yes def create_results_window(self): pass class ResultTable(ResultTableBase): COLUMNS = [ Column("marked", ""), Column("name", "Filename"), Column("folder_path", "Directory"), Column("size", "Size (KB)"), Column("extension", "Kind"), ] DELTA_COLUMNS = { "size", } class DupeGuru(DupeGuruBase): NAME = "dupeGuru" METADATA_TO_READ = ["size"] def __init__(self): DupeGuruBase.__init__(self, DupeGuruView()) self.appdata = "/tmp" self._recreate_result_table() def _prioritization_categories(self): return prioritize.all_categories() def _recreate_result_table(self): if self.result_table is not None: self.result_table.disconnect() self.result_table = ResultTable(self) self.result_table.view = CallLogger() self.result_table.connect() class NamedObject: def __init__(self, name="foobar", with_words=False, size=1, folder=None): self.name = name if folder is None: folder = "basepath" self._folder = Path(folder) self.size = size self.digest_partial = name self.digest = name self.digest_samples = name if with_words: self.words = getwords(name) self.is_ref = False def __bool__(self): return False # Make sure that operations are made correctly when the bool value of files is false. def get_display_info(self, group, delta): size = self.size m = group.get_match_of(self) if m and delta: r = group.ref size -= r.size return { "name": self.name, "folder_path": str(self.folder_path), "size": format_size(size, 0, 1, False), "extension": self.extension if hasattr(self, "extension") else "---", } @property def path(self): return self._folder.joinpath(self.name) @property def folder_path(self): return self.path.parent @property def extension(self): return get_file_ext(self.name) # Returns a group set that looks like that: # "foo bar" (1) # "bar bleh" (1024) # "foo bleh" (1) # "ibabtu" (1) # "ibabtu" (1) def GetTestGroups(): objects = [ NamedObject("foo bar"), NamedObject("bar bleh"), NamedObject("foo bleh"), NamedObject("ibabtu"), NamedObject("ibabtu"), ] objects[1].size = 1024 matches = engine.getmatches(objects) # we should have 5 matches groups = engine.get_groups(matches) # We should have 2 groups for g in groups: g.prioritize(lambda x: objects.index(x)) # We want the dupes to be in the same order as the list is groups.sort(key=len, reverse=True) # We want the group with 3 members to be first. return (objects, matches, groups) class TestApp(TestAppBase): __test__ = False def __init__(self): def link_gui(gui): gui.view = self.make_logger() if hasattr(gui, "_columns"): # tables gui._columns.view = self.make_logger() return gui TestAppBase.__init__(self) self.app = DupeGuru() self.default_parent = self.app self.dtree = link_gui(self.app.directory_tree) self.dpanel = link_gui(self.app.details_panel) self.slabel = link_gui(self.app.stats_label) self.pdialog = PrioritizeDialog(self.app) link_gui(self.pdialog.category_list) link_gui(self.pdialog.criteria_list) link_gui(self.pdialog.prioritization_list) link_gui(self.app.ignore_list_dialog) link_gui(self.app.ignore_list_dialog.ignore_list_table) link_gui(self.app.progress_window) link_gui(self.app.progress_window.jobdesc_textfield) link_gui(self.app.progress_window.progressdesc_textfield) @property def rtable(self): # rtable is a property because its instance can be replaced during execution return self.app.result_table # --- Helpers def select_pri_criterion(self, name): # Select a main prioritize criterion by name instead of by index. Makes tests more # maintainable. index = self.pdialog.category_list.index(name) self.pdialog.category_list.select(index) def add_pri_criterion(self, name, index): self.select_pri_criterion(name) self.pdialog.criteria_list.select([index]) self.pdialog.add_selected()
5,792
Python
.py
154
30.441558
108
0.645789
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,170
block_test.py
arsenetar_dupeguru/core/tests/block_test.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html # The commented out tests are tests for function that have been converted to pure C for speed from pytest import raises, skip from hscommon.testutil import eq_ try: from core.pe.block import avgdiff, getblocks2, NoBlocksError, DifferentBlockCountError except ImportError: skip("Can't import the block module, probably hasn't been compiled.") def my_avgdiff(first, second, limit=768, min_iter=3): # this is so I don't have to re-write every call return avgdiff(first, second, limit, min_iter) BLACK = (0, 0, 0) RED = (0xFF, 0, 0) GREEN = (0, 0xFF, 0) BLUE = (0, 0, 0xFF) class FakeImage: def __init__(self, size, data): self.size = size self.data = data def getdata(self): return self.data def crop(self, box): pixels = [] for i in range(box[1], box[3]): for j in range(box[0], box[2]): pixel = self.data[i * self.size[0] + j] pixels.append(pixel) return FakeImage((box[2] - box[0], box[3] - box[1]), pixels) def empty(): return FakeImage((0, 0), []) def single_pixel(): # one red pixel return FakeImage((1, 1), [(0xFF, 0, 0)]) def four_pixels(): pixels = [RED, (0, 0x80, 0xFF), (0x80, 0, 0), (0, 0x40, 0x80)] return FakeImage((2, 2), pixels) class TestCasegetblock: def test_single_pixel(self): im = single_pixel() [b] = getblocks2(im, 1) eq_(RED, b) def test_no_pixel(self): im = empty() eq_([], getblocks2(im, 1)) def test_four_pixels(self): im = four_pixels() [b] = getblocks2(im, 1) meanred = (0xFF + 0x80) // 4 meangreen = (0x80 + 0x40) // 4 meanblue = (0xFF + 0x80) // 4 eq_((meanred, meangreen, meanblue), b) class TestCasegetblocks2: def test_empty_image(self): im = empty() blocks = getblocks2(im, 1) eq_(0, len(blocks)) def test_one_block_image(self): im = four_pixels() blocks = getblocks2(im, 1) eq_(1, len(blocks)) block = blocks[0] meanred = (0xFF + 0x80) // 4 meangreen = (0x80 + 0x40) // 4 meanblue = (0xFF + 0x80) // 4 eq_((meanred, meangreen, meanblue), block) def test_four_blocks_all_black(self): im = FakeImage((2, 2), [BLACK, BLACK, BLACK, BLACK]) blocks = getblocks2(im, 2) eq_(4, len(blocks)) for block in blocks: eq_(BLACK, block) def test_two_pixels_image_horizontal(self): pixels = [RED, BLUE] im = FakeImage((2, 1), pixels) blocks = getblocks2(im, 2) eq_(4, len(blocks)) eq_(RED, blocks[0]) eq_(BLUE, blocks[1]) eq_(RED, blocks[2]) eq_(BLUE, blocks[3]) def test_two_pixels_image_vertical(self): pixels = [RED, BLUE] im = FakeImage((1, 2), pixels) blocks = getblocks2(im, 2) eq_(4, len(blocks)) eq_(RED, blocks[0]) eq_(RED, blocks[1]) eq_(BLUE, blocks[2]) eq_(BLUE, blocks[3]) class TestCaseavgdiff: def test_empty(self): with raises(NoBlocksError): my_avgdiff([], []) def test_two_blocks(self): b1 = (5, 10, 15) b2 = (255, 250, 245) b3 = (0, 0, 0) b4 = (255, 0, 255) blocks1 = [b1, b2] blocks2 = [b3, b4] expected1 = 5 + 10 + 15 expected2 = 0 + 250 + 10 expected = (expected1 + expected2) // 2 eq_(expected, my_avgdiff(blocks1, blocks2)) def test_blocks_not_the_same_size(self): b = (0, 0, 0) with raises(DifferentBlockCountError): my_avgdiff([b, b], [b]) def test_first_arg_is_empty_but_not_second(self): # Don't return 0 (as when the 2 lists are empty), raise! b = (0, 0, 0) with raises(DifferentBlockCountError): my_avgdiff([], [b]) def test_limit(self): ref = (0, 0, 0) b1 = (10, 10, 10) # avg 30 b2 = (20, 20, 20) # avg 45 b3 = (30, 30, 30) # avg 60 blocks1 = [ref, ref, ref] blocks2 = [b1, b2, b3] eq_(45, my_avgdiff(blocks1, blocks2, 44)) def test_min_iterations(self): ref = (0, 0, 0) b1 = (10, 10, 10) # avg 30 b2 = (20, 20, 20) # avg 45 b3 = (10, 10, 10) # avg 40 blocks1 = [ref, ref, ref] blocks2 = [b1, b2, b3] eq_(40, my_avgdiff(blocks1, blocks2, 45 - 1, 3)) # Bah, I don't know why this test fails, but I don't think it matters very much # def test_just_over_the_limit(self): # #A score just over the limit might return exactly the limit due to truncating. We should # #ceil() the result in this case. # ref = (0, 0, 0) # b1 = (10, 0, 0) # b2 = (11, 0, 0) # blocks1 = [ref, ref] # blocks2 = [b1, b2] # eq_(11, my_avgdiff(blocks1, blocks2, 10)) # def test_return_at_least_1_at_the_slightest_difference(self): ref = (0, 0, 0) b1 = (1, 0, 0) blocks1 = [ref for _ in range(250)] blocks2 = [ref for _ in range(250)] blocks2[0] = b1 eq_(1, my_avgdiff(blocks1, blocks2)) def test_return_0_if_there_is_no_difference(self): ref = (0, 0, 0) blocks1 = [ref, ref] blocks2 = [ref, ref] eq_(0, my_avgdiff(blocks1, blocks2))
5,647
Python
.py
154
29.311688
103
0.56266
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,171
exclude_test.py
arsenetar_dupeguru/core/tests/exclude_test.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import io from xml.etree import ElementTree as ET from hscommon.testutil import eq_ from hscommon.plat import ISWINDOWS from core.tests.base import DupeGuru from core.exclude import ExcludeList, ExcludeDict, default_regexes, AlreadyThereException from re import error # Two slightly different implementations here, one around a list of lists, # and another around a dictionary. class TestCaseListXMLLoading: def setup_method(self, method): self.exclude_list = ExcludeList() def test_load_non_existant_file(self): # Loads the pre-defined regexes self.exclude_list.load_from_xml("non_existant.xml") eq_(len(default_regexes), len(self.exclude_list)) # they should also be marked by default eq_(len(default_regexes), self.exclude_list.marked_count) def test_save_to_xml(self): f = io.BytesIO() self.exclude_list.save_to_xml(f) f.seek(0) doc = ET.parse(f) root = doc.getroot() eq_("exclude_list", root.tag) def test_save_and_load(self, tmpdir): e1 = ExcludeList() e2 = ExcludeList() eq_(len(e1), 0) e1.add(r"one") e1.mark(r"one") e1.add(r"two") tmpxml = str(tmpdir.join("exclude_testunit.xml")) e1.save_to_xml(tmpxml) e2.load_from_xml(tmpxml) # We should have the default regexes assert r"one" in e2 assert r"two" in e2 eq_(len(e2), 2) eq_(e2.marked_count, 1) def test_load_xml_with_garbage_and_missing_elements(self): root = ET.Element("foobar") # The root element shouldn't matter exclude_node = ET.SubElement(root, "bogus") exclude_node.set("regex", "None") exclude_node.set("marked", "y") exclude_node = ET.SubElement(root, "exclude") exclude_node.set("regex", "one") # marked field invalid exclude_node.set("markedddd", "y") exclude_node = ET.SubElement(root, "exclude") exclude_node.set("regex", "two") # missing marked field exclude_node = ET.SubElement(root, "exclude") exclude_node.set("regex", "three") exclude_node.set("markedddd", "pazjbjepo") f = io.BytesIO() tree = ET.ElementTree(root) tree.write(f, encoding="utf-8") f.seek(0) self.exclude_list.load_from_xml(f) print(f"{[x for x in self.exclude_list]}") # only the two "exclude" nodes should be added, eq_(3, len(self.exclude_list)) # None should be marked eq_(0, self.exclude_list.marked_count) class TestCaseDictXMLLoading(TestCaseListXMLLoading): def setup_method(self, method): self.exclude_list = ExcludeDict() class TestCaseListEmpty: def setup_method(self, method): self.app = DupeGuru() self.app.exclude_list = ExcludeList(union_regex=False) self.exclude_list = self.app.exclude_list def test_add_mark_and_remove_regex(self): regex1 = r"one" regex2 = r"two" self.exclude_list.add(regex1) assert regex1 in self.exclude_list self.exclude_list.add(regex2) self.exclude_list.mark(regex1) self.exclude_list.mark(regex2) eq_(len(self.exclude_list), 2) eq_(len(self.exclude_list.compiled), 2) compiled_files = [x for x in self.exclude_list.compiled_files] eq_(len(compiled_files), 2) self.exclude_list.remove(regex2) assert regex2 not in self.exclude_list eq_(len(self.exclude_list), 1) def test_add_duplicate(self): self.exclude_list.add(r"one") eq_(1, len(self.exclude_list)) try: self.exclude_list.add(r"one") except Exception: pass eq_(1, len(self.exclude_list)) def test_add_not_compilable(self): # Trying to add a non-valid regex should not work and raise exception regex = r"one))" try: self.exclude_list.add(regex) except Exception as e: # Make sure we raise a re.error so that the interface can process it eq_(type(e), error) added = self.exclude_list.mark(regex) eq_(added, False) eq_(len(self.exclude_list), 0) eq_(len(self.exclude_list.compiled), 0) compiled_files = [x for x in self.exclude_list.compiled_files] eq_(len(compiled_files), 0) def test_force_add_not_compilable(self): """Used when loading from XML for example""" regex = r"one))" self.exclude_list.add(regex, forced=True) marked = self.exclude_list.mark(regex) eq_(marked, False) # can't be marked since not compilable eq_(len(self.exclude_list), 1) eq_(len(self.exclude_list.compiled), 0) compiled_files = [x for x in self.exclude_list.compiled_files] eq_(len(compiled_files), 0) # adding a duplicate regex = r"one))" try: self.exclude_list.add(regex, forced=True) except Exception as e: # we should have this exception, and it shouldn't be added assert type(e) is AlreadyThereException eq_(len(self.exclude_list), 1) eq_(len(self.exclude_list.compiled), 0) def test_rename_regex(self): regex = r"one" self.exclude_list.add(regex) self.exclude_list.mark(regex) regex_renamed = r"one))" # Not compilable, can't be marked self.exclude_list.rename(regex, regex_renamed) assert regex not in self.exclude_list assert regex_renamed in self.exclude_list eq_(self.exclude_list.is_marked(regex_renamed), False) self.exclude_list.mark(regex_renamed) eq_(self.exclude_list.is_marked(regex_renamed), False) regex_renamed_compilable = r"two" self.exclude_list.rename(regex_renamed, regex_renamed_compilable) assert regex_renamed_compilable in self.exclude_list eq_(self.exclude_list.is_marked(regex_renamed), False) self.exclude_list.mark(regex_renamed_compilable) eq_(self.exclude_list.is_marked(regex_renamed_compilable), True) eq_(len(self.exclude_list), 1) # Should still be marked after rename regex_compilable = r"three" self.exclude_list.rename(regex_renamed_compilable, regex_compilable) eq_(self.exclude_list.is_marked(regex_compilable), True) def test_rename_regex_file_to_path(self): regex = r".*/one.*" if ISWINDOWS: regex = r".*\\one.*" regex2 = r".*one.*" self.exclude_list.add(regex) self.exclude_list.mark(regex) compiled_re = [x.pattern for x in self.exclude_list._excluded_compiled] files_re = [x.pattern for x in self.exclude_list.compiled_files] paths_re = [x.pattern for x in self.exclude_list.compiled_paths] assert regex in compiled_re assert regex not in files_re assert regex in paths_re self.exclude_list.rename(regex, regex2) compiled_re = [x.pattern for x in self.exclude_list._excluded_compiled] files_re = [x.pattern for x in self.exclude_list.compiled_files] paths_re = [x.pattern for x in self.exclude_list.compiled_paths] assert regex not in compiled_re assert regex2 in compiled_re assert regex2 in files_re assert regex2 not in paths_re def test_restore_default(self): """Only unmark previously added regexes and mark the pre-defined ones""" regex = r"one" self.exclude_list.add(regex) self.exclude_list.mark(regex) self.exclude_list.restore_defaults() eq_(len(default_regexes), self.exclude_list.marked_count) # added regex shouldn't be marked eq_(self.exclude_list.is_marked(regex), False) # added regex shouldn't be in compiled list either compiled = [x for x in self.exclude_list.compiled] assert regex not in compiled # Only default regexes marked and in compiled list for re in default_regexes: assert self.exclude_list.is_marked(re) found = False for compiled_re in compiled: if compiled_re.pattern == re: found = True if not found: raise (Exception(f"Default RE {re} not found in compiled list.")) eq_(len(default_regexes), len(self.exclude_list.compiled)) class TestCaseListEmptyUnion(TestCaseListEmpty): """Same but with union regex""" def setup_method(self, method): self.app = DupeGuru() self.app.exclude_list = ExcludeList(union_regex=True) self.exclude_list = self.app.exclude_list def test_add_mark_and_remove_regex(self): regex1 = r"one" regex2 = r"two" self.exclude_list.add(regex1) assert regex1 in self.exclude_list self.exclude_list.add(regex2) self.exclude_list.mark(regex1) self.exclude_list.mark(regex2) eq_(len(self.exclude_list), 2) eq_(len(self.exclude_list.compiled), 1) compiled_files = [x for x in self.exclude_list.compiled_files] eq_(len(compiled_files), 1) # Two patterns joined together into one assert "|" in compiled_files[0].pattern self.exclude_list.remove(regex2) assert regex2 not in self.exclude_list eq_(len(self.exclude_list), 1) def test_rename_regex_file_to_path(self): regex = r".*/one.*" if ISWINDOWS: regex = r".*\\one.*" regex2 = r".*one.*" self.exclude_list.add(regex) self.exclude_list.mark(regex) eq_(len([x for x in self.exclude_list]), 1) compiled_re = [x.pattern for x in self.exclude_list.compiled] files_re = [x.pattern for x in self.exclude_list.compiled_files] paths_re = [x.pattern for x in self.exclude_list.compiled_paths] assert regex in compiled_re assert regex not in files_re assert regex in paths_re self.exclude_list.rename(regex, regex2) eq_(len([x for x in self.exclude_list]), 1) compiled_re = [x.pattern for x in self.exclude_list.compiled] files_re = [x.pattern for x in self.exclude_list.compiled_files] paths_re = [x.pattern for x in self.exclude_list.compiled_paths] assert regex not in compiled_re assert regex2 in compiled_re assert regex2 in files_re assert regex2 not in paths_re def test_restore_default(self): """Only unmark previously added regexes and mark the pre-defined ones""" regex = r"one" self.exclude_list.add(regex) self.exclude_list.mark(regex) self.exclude_list.restore_defaults() eq_(len(default_regexes), self.exclude_list.marked_count) # added regex shouldn't be marked eq_(self.exclude_list.is_marked(regex), False) # added regex shouldn't be in compiled list either compiled = [x for x in self.exclude_list.compiled] assert regex not in compiled # Need to escape both to get the same strings after compilation compiled_escaped = {x.encode("unicode-escape").decode() for x in compiled[0].pattern.split("|")} default_escaped = {x.encode("unicode-escape").decode() for x in default_regexes} assert compiled_escaped == default_escaped eq_(len(default_regexes), len(compiled[0].pattern.split("|"))) class TestCaseDictEmpty(TestCaseListEmpty): """Same, but with dictionary implementation""" def setup_method(self, method): self.app = DupeGuru() self.app.exclude_list = ExcludeDict(union_regex=False) self.exclude_list = self.app.exclude_list class TestCaseDictEmptyUnion(TestCaseDictEmpty): """Same, but with union regex""" def setup_method(self, method): self.app = DupeGuru() self.app.exclude_list = ExcludeDict(union_regex=True) self.exclude_list = self.app.exclude_list def test_add_mark_and_remove_regex(self): regex1 = r"one" regex2 = r"two" self.exclude_list.add(regex1) assert regex1 in self.exclude_list self.exclude_list.add(regex2) self.exclude_list.mark(regex1) self.exclude_list.mark(regex2) eq_(len(self.exclude_list), 2) eq_(len(self.exclude_list.compiled), 1) compiled_files = [x for x in self.exclude_list.compiled_files] # two patterns joined into one eq_(len(compiled_files), 1) self.exclude_list.remove(regex2) assert regex2 not in self.exclude_list eq_(len(self.exclude_list), 1) def test_rename_regex_file_to_path(self): regex = r".*/one.*" if ISWINDOWS: regex = r".*\\one.*" regex2 = r".*one.*" self.exclude_list.add(regex) self.exclude_list.mark(regex) marked_re = [x for marked, x in self.exclude_list if marked] eq_(len(marked_re), 1) compiled_re = [x.pattern for x in self.exclude_list.compiled] files_re = [x.pattern for x in self.exclude_list.compiled_files] paths_re = [x.pattern for x in self.exclude_list.compiled_paths] assert regex in compiled_re assert regex not in files_re assert regex in paths_re self.exclude_list.rename(regex, regex2) compiled_re = [x.pattern for x in self.exclude_list.compiled] files_re = [x.pattern for x in self.exclude_list.compiled_files] paths_re = [x.pattern for x in self.exclude_list.compiled_paths] assert regex not in compiled_re assert regex2 in compiled_re assert regex2 in files_re assert regex2 not in paths_re def test_restore_default(self): """Only unmark previously added regexes and mark the pre-defined ones""" regex = r"one" self.exclude_list.add(regex) self.exclude_list.mark(regex) self.exclude_list.restore_defaults() eq_(len(default_regexes), self.exclude_list.marked_count) # added regex shouldn't be marked eq_(self.exclude_list.is_marked(regex), False) # added regex shouldn't be in compiled list either compiled = [x for x in self.exclude_list.compiled] assert regex not in compiled # Need to escape both to get the same strings after compilation compiled_escaped = {x.encode("unicode-escape").decode() for x in compiled[0].pattern.split("|")} default_escaped = {x.encode("unicode-escape").decode() for x in default_regexes} assert compiled_escaped == default_escaped eq_(len(default_regexes), len(compiled[0].pattern.split("|"))) def split_union(pattern_object): """Returns list of strings for each union pattern""" return [x for x in pattern_object.pattern.split("|")] class TestCaseCompiledList: """Test consistency between union or and separate versions.""" def setup_method(self, method): self.e_separate = ExcludeList(union_regex=False) self.e_separate.restore_defaults() self.e_union = ExcludeList(union_regex=True) self.e_union.restore_defaults() def test_same_number_of_expressions(self): # We only get one union Pattern item in a tuple, which is made of however many parts eq_(len(split_union(self.e_union.compiled[0])), len(default_regexes)) # We get as many as there are marked items eq_(len(self.e_separate.compiled), len(default_regexes)) exprs = split_union(self.e_union.compiled[0]) # We should have the same number and the same expressions eq_(len(exprs), len(self.e_separate.compiled)) for expr in self.e_separate.compiled: assert expr.pattern in exprs def test_compiled_files(self): # is path separator checked properly to yield the output if ISWINDOWS: regex1 = r"test\\one\\sub" else: regex1 = r"test/one/sub" self.e_separate.add(regex1) self.e_separate.mark(regex1) self.e_union.add(regex1) self.e_union.mark(regex1) separate_compiled_dirs = self.e_separate.compiled separate_compiled_files = [x for x in self.e_separate.compiled_files] # HACK we need to call compiled property FIRST to generate the cache union_compiled_dirs = self.e_union.compiled # print(f"type: {type(self.e_union.compiled_files[0])}") # A generator returning only one item... ugh union_compiled_files = [x for x in self.e_union.compiled_files][0] print(f"compiled files: {union_compiled_files}") # Separate should give several plus the one added eq_(len(separate_compiled_dirs), len(default_regexes) + 1) # regex1 shouldn't be in the "files" version eq_(len(separate_compiled_files), len(default_regexes)) # Only one Pattern returned, which when split should be however many + 1 eq_(len(split_union(union_compiled_dirs[0])), len(default_regexes) + 1) # regex1 shouldn't be here either eq_(len(split_union(union_compiled_files)), len(default_regexes)) class TestCaseCompiledDict(TestCaseCompiledList): """Test the dictionary version""" def setup_method(self, method): self.e_separate = ExcludeDict(union_regex=False) self.e_separate.restore_defaults() self.e_union = ExcludeDict(union_regex=True) self.e_union.restore_defaults()
17,739
Python
.py
383
37.754569
104
0.648983
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,172
directories_test.py
arsenetar_dupeguru/core/tests/directories_test.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import os import time import tempfile import shutil from pytest import raises from pathlib import Path from hscommon.testutil import eq_ from hscommon.plat import ISWINDOWS from core.fs import File from core.directories import ( Directories, DirectoryState, AlreadyThereError, InvalidPathError, ) from core.exclude import ExcludeList, ExcludeDict def create_fake_fs(rootpath): # We have it as a separate function because other units are using it. rootpath = rootpath.joinpath("fs") rootpath.mkdir() rootpath.joinpath("dir1").mkdir() rootpath.joinpath("dir2").mkdir() rootpath.joinpath("dir3").mkdir() with rootpath.joinpath("file1.test").open("wt") as fp: fp.write("1") with rootpath.joinpath("file2.test").open("wt") as fp: fp.write("12") with rootpath.joinpath("file3.test").open("wt") as fp: fp.write("123") with rootpath.joinpath("dir1", "file1.test").open("wt") as fp: fp.write("1") with rootpath.joinpath("dir2", "file2.test").open("wt") as fp: fp.write("12") with rootpath.joinpath("dir3", "file3.test").open("wt") as fp: fp.write("123") return rootpath testpath = None def setup_module(module): # In this unit, we have tests depending on two directory structure. One with only one file in it # and another with a more complex structure. testpath = Path(tempfile.mkdtemp()) module.testpath = testpath rootpath = testpath.joinpath("onefile") rootpath.mkdir() with rootpath.joinpath("test.txt").open("wt") as fp: fp.write("test_data") create_fake_fs(testpath) def teardown_module(module): shutil.rmtree(str(module.testpath)) def test_empty(): d = Directories() eq_(len(d), 0) assert "foobar" not in d def test_add_path(): d = Directories() p = testpath.joinpath("onefile") d.add_path(p) eq_(1, len(d)) assert p in d assert (p.joinpath("foobar")) in d assert p.parent not in d p = testpath.joinpath("fs") d.add_path(p) eq_(2, len(d)) assert p in d def test_add_path_when_path_is_already_there(): d = Directories() p = testpath.joinpath("onefile") d.add_path(p) with raises(AlreadyThereError): d.add_path(p) with raises(AlreadyThereError): d.add_path(p.joinpath("foobar")) eq_(1, len(d)) def test_add_path_containing_paths_already_there(): d = Directories() d.add_path(testpath.joinpath("onefile")) eq_(1, len(d)) d.add_path(testpath) eq_(len(d), 1) eq_(d[0], testpath) def test_add_path_non_latin(tmpdir): p = Path(str(tmpdir)) to_add = p.joinpath("unicode\u201a") os.mkdir(str(to_add)) d = Directories() try: d.add_path(to_add) except UnicodeDecodeError: assert False def test_del(): d = Directories() d.add_path(testpath.joinpath("onefile")) try: del d[1] assert False except IndexError: pass d.add_path(testpath.joinpath("fs")) del d[1] eq_(1, len(d)) def test_states(): d = Directories() p = testpath.joinpath("onefile") d.add_path(p) eq_(DirectoryState.NORMAL, d.get_state(p)) d.set_state(p, DirectoryState.REFERENCE) eq_(DirectoryState.REFERENCE, d.get_state(p)) eq_(DirectoryState.REFERENCE, d.get_state(p.joinpath("dir1"))) eq_(1, len(d.states)) eq_(p, list(d.states.keys())[0]) eq_(DirectoryState.REFERENCE, d.states[p]) def test_get_state_with_path_not_there(): # When the path's not there, just return DirectoryState.Normal d = Directories() d.add_path(testpath.joinpath("onefile")) eq_(d.get_state(testpath), DirectoryState.NORMAL) def test_states_overwritten_when_larger_directory_eat_smaller_ones(): # ref #248 # When setting the state of a folder, we overwrite previously set states for subfolders. d = Directories() p = testpath.joinpath("onefile") d.add_path(p) d.set_state(p, DirectoryState.EXCLUDED) d.add_path(testpath) d.set_state(testpath, DirectoryState.REFERENCE) eq_(d.get_state(p), DirectoryState.REFERENCE) eq_(d.get_state(p.joinpath("dir1")), DirectoryState.REFERENCE) eq_(d.get_state(testpath), DirectoryState.REFERENCE) def test_get_files(): d = Directories() p = testpath.joinpath("fs") d.add_path(p) d.set_state(p.joinpath("dir1"), DirectoryState.REFERENCE) d.set_state(p.joinpath("dir2"), DirectoryState.EXCLUDED) files = list(d.get_files()) eq_(5, len(files)) for f in files: if f.path.parent == p.joinpath("dir1"): assert f.is_ref else: assert not f.is_ref def test_get_files_with_folders(): # When fileclasses handle folders, return them and stop recursing! class FakeFile(File): @classmethod def can_handle(cls, path): return True d = Directories() p = testpath.joinpath("fs") d.add_path(p) files = list(d.get_files(fileclasses=[FakeFile])) # We have the 3 root files and the 3 root dirs eq_(6, len(files)) def test_get_folders(): d = Directories() p = testpath.joinpath("fs") d.add_path(p) d.set_state(p.joinpath("dir1"), DirectoryState.REFERENCE) d.set_state(p.joinpath("dir2"), DirectoryState.EXCLUDED) folders = list(d.get_folders()) eq_(len(folders), 3) ref = [f for f in folders if f.is_ref] not_ref = [f for f in folders if not f.is_ref] eq_(len(ref), 1) eq_(ref[0].path, p.joinpath("dir1")) eq_(len(not_ref), 2) eq_(ref[0].size, 1) def test_get_files_with_inherited_exclusion(): d = Directories() p = testpath.joinpath("onefile") d.add_path(p) d.set_state(p, DirectoryState.EXCLUDED) eq_([], list(d.get_files())) def test_save_and_load(tmpdir): d1 = Directories() d2 = Directories() p1 = Path(str(tmpdir.join("p1"))) p1.mkdir() p2 = Path(str(tmpdir.join("p2"))) p2.mkdir() d1.add_path(p1) d1.add_path(p2) d1.set_state(p1, DirectoryState.REFERENCE) d1.set_state(p1.joinpath("dir1"), DirectoryState.EXCLUDED) tmpxml = str(tmpdir.join("directories_testunit.xml")) d1.save_to_file(tmpxml) d2.load_from_file(tmpxml) eq_(2, len(d2)) eq_(DirectoryState.REFERENCE, d2.get_state(p1)) eq_(DirectoryState.EXCLUDED, d2.get_state(p1.joinpath("dir1"))) def test_invalid_path(): d = Directories() p = Path("does_not_exist") with raises(InvalidPathError): d.add_path(p) eq_(0, len(d)) def test_set_state_on_invalid_path(): d = Directories() try: d.set_state( Path( "foobar", ), DirectoryState.NORMAL, ) except LookupError: assert False def test_load_from_file_with_invalid_path(tmpdir): # This test simulates a load from file resulting in a # InvalidPath raise. Other directories must be loaded. d1 = Directories() d1.add_path(testpath.joinpath("onefile")) # Will raise InvalidPath upon loading p = Path(str(tmpdir.join("toremove"))) p.mkdir() d1.add_path(p) p.rmdir() tmpxml = str(tmpdir.join("directories_testunit.xml")) d1.save_to_file(tmpxml) d2 = Directories() d2.load_from_file(tmpxml) eq_(1, len(d2)) def test_unicode_save(tmpdir): d = Directories() p1 = Path(str(tmpdir), "hello\xe9") p1.mkdir() p1.joinpath("foo\xe9").mkdir() d.add_path(p1) d.set_state(p1.joinpath("foo\xe9"), DirectoryState.EXCLUDED) tmpxml = str(tmpdir.join("directories_testunit.xml")) try: d.save_to_file(tmpxml) except UnicodeDecodeError: assert False def test_get_files_refreshes_its_directories(): d = Directories() p = testpath.joinpath("fs") d.add_path(p) files = d.get_files() eq_(6, len(list(files))) time.sleep(1) os.remove(str(p.joinpath("dir1", "file1.test"))) files = d.get_files() eq_(5, len(list(files))) def test_get_files_does_not_choke_on_non_existing_directories(tmpdir): d = Directories() p = Path(str(tmpdir)) d.add_path(p) shutil.rmtree(str(p)) eq_([], list(d.get_files())) def test_get_state_returns_excluded_by_default_for_hidden_directories(tmpdir): d = Directories() p = Path(str(tmpdir)) hidden_dir_path = p.joinpath(".foo") p.joinpath(".foo").mkdir() d.add_path(p) eq_(d.get_state(hidden_dir_path), DirectoryState.EXCLUDED) # But it can be overriden d.set_state(hidden_dir_path, DirectoryState.NORMAL) eq_(d.get_state(hidden_dir_path), DirectoryState.NORMAL) def test_default_path_state_override(tmpdir): # It's possible for a subclass to override the default state of a path class MyDirectories(Directories): def _default_state_for_path(self, path): if "foobar" in path.parts: return DirectoryState.EXCLUDED return DirectoryState.NORMAL d = MyDirectories() p1 = Path(str(tmpdir)) p1.joinpath("foobar").mkdir() p1.joinpath("foobar/somefile").touch() p1.joinpath("foobaz").mkdir() p1.joinpath("foobaz/somefile").touch() d.add_path(p1) eq_(d.get_state(p1.joinpath("foobaz")), DirectoryState.NORMAL) eq_(d.get_state(p1.joinpath("foobar")), DirectoryState.EXCLUDED) eq_(len(list(d.get_files())), 1) # only the 'foobaz' file is there # However, the default state can be changed d.set_state(p1.joinpath("foobar"), DirectoryState.NORMAL) eq_(d.get_state(p1.joinpath("foobar")), DirectoryState.NORMAL) eq_(len(list(d.get_files())), 2) class TestExcludeList: def setup_method(self, method): self.d = Directories(exclude_list=ExcludeList(union_regex=False)) def get_files_and_expect_num_result(self, num_result): """Calls get_files(), get the filenames only, print for debugging. num_result is how many files are expected as a result.""" print( f"EXCLUDED REGEX: paths {self.d._exclude_list.compiled_paths} \ files: {self.d._exclude_list.compiled_files} all: {self.d._exclude_list.compiled}" ) files = list(self.d.get_files()) files = [file.name for file in files] print(f"FINAL FILES {files}") eq_(len(files), num_result) return files def test_exclude_recycle_bin_by_default(self, tmpdir): regex = r"^.*Recycle\.Bin$" self.d._exclude_list.add(regex) self.d._exclude_list.mark(regex) p1 = Path(str(tmpdir)) p1.joinpath("$Recycle.Bin").mkdir() p1.joinpath("$Recycle.Bin", "subdir").mkdir() self.d.add_path(p1) eq_(self.d.get_state(p1.joinpath("$Recycle.Bin")), DirectoryState.EXCLUDED) # By default, subdirs should be excluded too, but this can be overridden separately eq_(self.d.get_state(p1.joinpath("$Recycle.Bin", "subdir")), DirectoryState.EXCLUDED) self.d.set_state(p1.joinpath("$Recycle.Bin", "subdir"), DirectoryState.NORMAL) eq_(self.d.get_state(p1.joinpath("$Recycle.Bin", "subdir")), DirectoryState.NORMAL) def test_exclude_refined(self, tmpdir): regex1 = r"^\$Recycle\.Bin$" self.d._exclude_list.add(regex1) self.d._exclude_list.mark(regex1) p1 = Path(str(tmpdir)) p1.joinpath("$Recycle.Bin").mkdir() p1.joinpath("$Recycle.Bin", "somefile.png").touch() p1.joinpath("$Recycle.Bin", "some_unwanted_file.jpg").touch() p1.joinpath("$Recycle.Bin", "subdir").mkdir() p1.joinpath("$Recycle.Bin", "subdir", "somesubdirfile.png").touch() p1.joinpath("$Recycle.Bin", "subdir", "unwanted_subdirfile.gif").touch() p1.joinpath("$Recycle.Bin", "subdar").mkdir() p1.joinpath("$Recycle.Bin", "subdar", "somesubdarfile.jpeg").touch() p1.joinpath("$Recycle.Bin", "subdar", "unwanted_subdarfile.png").touch() self.d.add_path(p1.joinpath("$Recycle.Bin")) # Filter should set the default state to Excluded eq_(self.d.get_state(p1.joinpath("$Recycle.Bin")), DirectoryState.EXCLUDED) # The subdir should inherit its parent state eq_(self.d.get_state(p1.joinpath("$Recycle.Bin", "subdir")), DirectoryState.EXCLUDED) eq_(self.d.get_state(p1.joinpath("$Recycle.Bin", "subdar")), DirectoryState.EXCLUDED) # Override a child path's state self.d.set_state(p1.joinpath("$Recycle.Bin", "subdir"), DirectoryState.NORMAL) eq_(self.d.get_state(p1.joinpath("$Recycle.Bin", "subdir")), DirectoryState.NORMAL) # Parent should keep its default state, and the other child too eq_(self.d.get_state(p1.joinpath("$Recycle.Bin")), DirectoryState.EXCLUDED) eq_(self.d.get_state(p1.joinpath("$Recycle.Bin", "subdar")), DirectoryState.EXCLUDED) # print(f"get_folders(): {[x for x in self.d.get_folders()]}") # only the 2 files directly under the Normal directory files = self.get_files_and_expect_num_result(2) assert "somefile.png" not in files assert "some_unwanted_file.jpg" not in files assert "somesubdarfile.jpeg" not in files assert "unwanted_subdarfile.png" not in files assert "somesubdirfile.png" in files assert "unwanted_subdirfile.gif" in files # Overriding the parent should enable all children self.d.set_state(p1.joinpath("$Recycle.Bin"), DirectoryState.NORMAL) eq_(self.d.get_state(p1.joinpath("$Recycle.Bin", "subdar")), DirectoryState.NORMAL) # all files there files = self.get_files_and_expect_num_result(6) assert "somefile.png" in files assert "some_unwanted_file.jpg" in files # This should still filter out files under directory, despite the Normal state regex2 = r".*unwanted.*" self.d._exclude_list.add(regex2) self.d._exclude_list.mark(regex2) files = self.get_files_and_expect_num_result(3) assert "somefile.png" in files assert "some_unwanted_file.jpg" not in files assert "unwanted_subdirfile.gif" not in files assert "unwanted_subdarfile.png" not in files if ISWINDOWS: regex3 = r".*Recycle\.Bin\\.*unwanted.*subdirfile.*" else: regex3 = r".*Recycle\.Bin\/.*unwanted.*subdirfile.*" self.d._exclude_list.rename(regex2, regex3) assert self.d._exclude_list.error(regex3) is None # print(f"get_folders(): {[x for x in self.d.get_folders()]}") # Directory shouldn't change its state here, unless explicitely done by user eq_(self.d.get_state(p1.joinpath("$Recycle.Bin", "subdir")), DirectoryState.NORMAL) files = self.get_files_and_expect_num_result(5) assert "unwanted_subdirfile.gif" not in files assert "unwanted_subdarfile.png" in files # using end of line character should only filter the directory, or file ending with subdir regex4 = r".*subdir$" self.d._exclude_list.rename(regex3, regex4) assert self.d._exclude_list.error(regex4) is None p1.joinpath("$Recycle.Bin", "subdar", "file_ending_with_subdir").touch() eq_(self.d.get_state(p1.joinpath("$Recycle.Bin", "subdir")), DirectoryState.EXCLUDED) files = self.get_files_and_expect_num_result(4) assert "file_ending_with_subdir" not in files assert "somesubdarfile.jpeg" in files assert "somesubdirfile.png" not in files assert "unwanted_subdirfile.gif" not in files self.d.set_state(p1.joinpath("$Recycle.Bin", "subdir"), DirectoryState.NORMAL) eq_(self.d.get_state(p1.joinpath("$Recycle.Bin", "subdir")), DirectoryState.NORMAL) # print(f"get_folders(): {[x for x in self.d.get_folders()]}") files = self.get_files_and_expect_num_result(6) assert "file_ending_with_subdir" not in files assert "somesubdirfile.png" in files assert "unwanted_subdirfile.gif" in files regex5 = r".*subdir.*" self.d._exclude_list.rename(regex4, regex5) # Files containing substring should be filtered eq_(self.d.get_state(p1.joinpath("$Recycle.Bin", "subdir")), DirectoryState.NORMAL) # The path should not match, only the filename, the "subdir" in the directory name shouldn't matter p1.joinpath("$Recycle.Bin", "subdir", "file_which_shouldnt_match").touch() files = self.get_files_and_expect_num_result(5) assert "somesubdirfile.png" not in files assert "unwanted_subdirfile.gif" not in files assert "file_ending_with_subdir" not in files assert "file_which_shouldnt_match" in files # This should match the directory only regex6 = r".*/.*subdir.*/.*" if ISWINDOWS: regex6 = r".*\\.*subdir.*\\.*" assert os.sep in regex6 self.d._exclude_list.rename(regex5, regex6) self.d._exclude_list.remove(regex1) eq_(len(self.d._exclude_list.compiled), 1) assert regex1 not in self.d._exclude_list assert regex5 not in self.d._exclude_list assert self.d._exclude_list.error(regex6) is None assert regex6 in self.d._exclude_list # This still should not be affected eq_(self.d.get_state(p1.joinpath("$Recycle.Bin", "subdir")), DirectoryState.NORMAL) files = self.get_files_and_expect_num_result(5) # These files are under the "/subdir" directory assert "somesubdirfile.png" not in files assert "unwanted_subdirfile.gif" not in files # This file under "subdar" directory should not be filtered out assert "file_ending_with_subdir" in files # This file is in a directory that should be filtered out assert "file_which_shouldnt_match" not in files def test_japanese_unicode(self, tmpdir): p1 = Path(str(tmpdir)) p1.joinpath("$Recycle.Bin").mkdir() p1.joinpath("$Recycle.Bin", "somerecycledfile.png").touch() p1.joinpath("$Recycle.Bin", "some_unwanted_file.jpg").touch() p1.joinpath("$Recycle.Bin", "subdir").mkdir() p1.joinpath("$Recycle.Bin", "subdir", "過去白濁物語~]_カラー.jpg").touch() p1.joinpath("$Recycle.Bin", "思叫物語").mkdir() p1.joinpath("$Recycle.Bin", "思叫物語", "なししろ会う前").touch() p1.joinpath("$Recycle.Bin", "思叫物語", "堂~ロ").touch() self.d.add_path(p1.joinpath("$Recycle.Bin")) regex3 = r".*物語.*" self.d._exclude_list.add(regex3) self.d._exclude_list.mark(regex3) # print(f"get_folders(): {[x for x in self.d.get_folders()]}") eq_(self.d.get_state(p1.joinpath("$Recycle.Bin", "思叫物語")), DirectoryState.EXCLUDED) files = self.get_files_and_expect_num_result(2) assert "過去白濁物語~]_カラー.jpg" not in files assert "なししろ会う前" not in files assert "堂~ロ" not in files # using end of line character should only filter that directory, not affecting its files regex4 = r".*物語$" self.d._exclude_list.rename(regex3, regex4) assert self.d._exclude_list.error(regex4) is None self.d.set_state(p1.joinpath("$Recycle.Bin", "思叫物語"), DirectoryState.NORMAL) files = self.get_files_and_expect_num_result(5) assert "過去白濁物語~]_カラー.jpg" in files assert "なししろ会う前" in files assert "堂~ロ" in files def test_get_state_returns_excluded_for_hidden_directories_and_files(self, tmpdir): # This regex only work for files, not paths regex = r"^\..*$" self.d._exclude_list.add(regex) self.d._exclude_list.mark(regex) p1 = Path(str(tmpdir)) p1.joinpath("foobar").mkdir() p1.joinpath("foobar", ".hidden_file.txt").touch() p1.joinpath("foobar", ".hidden_dir").mkdir() p1.joinpath("foobar", ".hidden_dir", "foobar.jpg").touch() p1.joinpath("foobar", ".hidden_dir", ".hidden_subfile.png").touch() self.d.add_path(p1.joinpath("foobar")) # It should not inherit its parent's state originally eq_(self.d.get_state(p1.joinpath("foobar", ".hidden_dir")), DirectoryState.EXCLUDED) self.d.set_state(p1.joinpath("foobar", ".hidden_dir"), DirectoryState.NORMAL) # The files should still be filtered files = self.get_files_and_expect_num_result(1) eq_(len(self.d._exclude_list.compiled_paths), 0) eq_(len(self.d._exclude_list.compiled_files), 1) assert ".hidden_file.txt" not in files assert ".hidden_subfile.png" not in files assert "foobar.jpg" in files class TestExcludeDict(TestExcludeList): def setup_method(self, method): self.d = Directories(exclude_list=ExcludeDict(union_regex=False)) class TestExcludeListunion(TestExcludeList): def setup_method(self, method): self.d = Directories(exclude_list=ExcludeList(union_regex=True)) class TestExcludeDictunion(TestExcludeList): def setup_method(self, method): self.d = Directories(exclude_list=ExcludeDict(union_regex=True))
21,405
Python
.py
489
36.709611
107
0.656862
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,173
result_table_test.py
arsenetar_dupeguru/core/tests/result_table_test.py
# Created By: Virgil Dupras # Created On: 2013-07-28 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from core.tests.base import TestApp, GetTestGroups def app_with_results(): app = TestApp() objects, matches, groups = GetTestGroups() app.app.results.groups = groups app.rtable.refresh() return app def test_delta_flags_delta_mode_off(): app = app_with_results() # When the delta mode is off, we never have delta values flags app.rtable.delta_values = False # Ref file, always false anyway assert not app.rtable[0].is_cell_delta("size") # False because delta mode is off assert not app.rtable[1].is_cell_delta("size") def test_delta_flags_delta_mode_on_delta_columns(): # When the delta mode is on, delta columns always have a delta flag, except for ref rows app = app_with_results() app.rtable.delta_values = True # Ref file, always false anyway assert not app.rtable[0].is_cell_delta("size") # But for a dupe, the flag is on assert app.rtable[1].is_cell_delta("size") def test_delta_flags_delta_mode_on_non_delta_columns(): # When the delta mode is on, non-delta columns have a delta flag if their value differs from # their ref. app = app_with_results() app.rtable.delta_values = True # "bar bleh" != "foo bar", flag on assert app.rtable[1].is_cell_delta("name") # "ibabtu" row, but it's a ref, flag off assert not app.rtable[3].is_cell_delta("name") # "ibabtu" == "ibabtu", flag off assert not app.rtable[4].is_cell_delta("name") def test_delta_flags_delta_mode_on_non_delta_columns_case_insensitive(): # Comparison that occurs for non-numeric columns to check whether they're delta is case # insensitive app = app_with_results() app.app.results.groups[1].ref.name = "ibAbtu" app.app.results.groups[1].dupes[0].name = "IBaBTU" app.rtable.delta_values = True # "ibAbtu" == "IBaBTU", flag off assert not app.rtable[4].is_cell_delta("name")
2,229
Python
.py
50
40.4
96
0.704797
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,174
markable_test.py
arsenetar_dupeguru/core/tests/markable_test.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.testutil import eq_ from core.markable import MarkableList, Markable def gen(): ml = MarkableList() ml.extend(list(range(10))) return ml def test_unmarked(): ml = gen() for i in ml: assert not ml.is_marked(i) def test_mark(): ml = gen() assert ml.mark(3) assert ml.is_marked(3) assert not ml.is_marked(2) def test_unmark(): ml = gen() ml.mark(4) assert ml.unmark(4) assert not ml.is_marked(4) def test_unmark_unmarked(): ml = gen() assert not ml.unmark(4) assert not ml.is_marked(4) def test_mark_twice_and_unmark(): ml = gen() assert ml.mark(5) assert not ml.mark(5) ml.unmark(5) assert not ml.is_marked(5) def test_mark_toggle(): ml = gen() ml.mark_toggle(6) assert ml.is_marked(6) ml.mark_toggle(6) assert not ml.is_marked(6) ml.mark_toggle(6) assert ml.is_marked(6) def test_is_markable(): class Foobar(Markable): def _is_markable(self, o): return o == "foobar" f = Foobar() assert not f.is_marked("foobar") assert not f.mark("foo") assert not f.is_marked("foo") f.mark_toggle("foo") assert not f.is_marked("foo") f.mark("foobar") assert f.is_marked("foobar") ml = gen() ml.mark(11) assert not ml.is_marked(11) def test_change_notifications(): class Foobar(Markable): def _did_mark(self, o): self.log.append((True, o)) def _did_unmark(self, o): self.log.append((False, o)) f = Foobar() f.log = [] f.mark("foo") f.mark("foo") f.mark_toggle("bar") f.unmark("foo") f.unmark("foo") f.mark_toggle("bar") eq_([(True, "foo"), (True, "bar"), (False, "foo"), (False, "bar")], f.log) def test_mark_count(): ml = gen() eq_(0, ml.mark_count) ml.mark(7) eq_(1, ml.mark_count) ml.mark(11) eq_(1, ml.mark_count) def test_mark_none(): log = [] ml = gen() ml._did_unmark = lambda o: log.append(o) ml.mark(1) ml.mark(2) eq_(2, ml.mark_count) ml.mark_none() eq_(0, ml.mark_count) eq_([1, 2], log) def test_mark_all(): ml = gen() eq_(0, ml.mark_count) ml.mark_all() eq_(10, ml.mark_count) assert ml.is_marked(1) def test_mark_invert(): ml = gen() ml.mark(1) ml.mark_invert() assert not ml.is_marked(1) assert ml.is_marked(2) def test_mark_while_inverted(): log = [] ml = gen() ml._did_unmark = lambda o: log.append((False, o)) ml._did_mark = lambda o: log.append((True, o)) ml.mark(1) ml.mark_invert() assert ml.mark_inverted assert ml.mark(1) assert ml.unmark(2) assert ml.unmark(1) ml.mark_toggle(3) assert not ml.is_marked(3) eq_(7, ml.mark_count) eq_([(True, 1), (False, 1), (True, 2), (True, 1), (True, 3)], log) def test_remove_mark_flag(): ml = gen() ml.mark(1) ml._remove_mark_flag(1) assert not ml.is_marked(1) ml.mark(1) ml.mark_invert() assert not ml.is_marked(1) ml._remove_mark_flag(1) assert ml.is_marked(1) def test_is_marked_returns_false_if_object_not_markable(): class MyMarkableList(MarkableList): def _is_markable(self, o): return o != 4 ml = MyMarkableList() ml.extend(list(range(10))) ml.mark_invert() assert ml.is_marked(1) assert not ml.is_marked(4)
3,689
Python
.py
135
22.303704
89
0.613087
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,175
fs_test.py
arsenetar_dupeguru/core/tests/fs_test.py
# Created By: Virgil Dupras # Created On: 2009-10-23 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import typing from os import urandom from pathlib import Path from hscommon.testutil import eq_ from core.tests.directories_test import create_fake_fs from core import fs hasher: typing.Callable try: import xxhash hasher = xxhash.xxh128 except ImportError: import hashlib hasher = hashlib.md5 def create_fake_fs_with_random_data(rootpath): rootpath = rootpath.joinpath("fs") rootpath.mkdir() rootpath.joinpath("dir1").mkdir() rootpath.joinpath("dir2").mkdir() rootpath.joinpath("dir3").mkdir() data1 = urandom(200 * 1024) # 200KiB data2 = urandom(1024 * 1024) # 1MiB data3 = urandom(10 * 1024 * 1024) # 10MiB with rootpath.joinpath("file1.test").open("wb") as fp: fp.write(data1) with rootpath.joinpath("file2.test").open("wb") as fp: fp.write(data2) with rootpath.joinpath("file3.test").open("wb") as fp: fp.write(data3) with rootpath.joinpath("dir1", "file1.test").open("wb") as fp: fp.write(data1) with rootpath.joinpath("dir2", "file2.test").open("wb") as fp: fp.write(data2) with rootpath.joinpath("dir3", "file3.test").open("wb") as fp: fp.write(data3) return rootpath def test_size_aggregates_subfiles(tmpdir): p = create_fake_fs(Path(str(tmpdir))) b = fs.Folder(p) eq_(b.size, 12) def test_digest_aggregate_subfiles_sorted(tmpdir): # dir.allfiles can return child in any order. Thus, bundle.digest must aggregate # all files' digests it contains, but it must make sure that it does so in the # same order everytime. p = create_fake_fs_with_random_data(Path(str(tmpdir))) b = fs.Folder(p) digest1 = fs.File(p.joinpath("dir1", "file1.test")).digest digest2 = fs.File(p.joinpath("dir2", "file2.test")).digest digest3 = fs.File(p.joinpath("dir3", "file3.test")).digest digest4 = fs.File(p.joinpath("file1.test")).digest digest5 = fs.File(p.joinpath("file2.test")).digest digest6 = fs.File(p.joinpath("file3.test")).digest # The expected digest is the hash of digests for folders and the direct digest for files folder_digest1 = hasher(digest1).digest() folder_digest2 = hasher(digest2).digest() folder_digest3 = hasher(digest3).digest() digest = hasher(folder_digest1 + folder_digest2 + folder_digest3 + digest4 + digest5 + digest6).digest() eq_(b.digest, digest) def test_partial_digest_aggregate_subfile_sorted(tmpdir): p = create_fake_fs_with_random_data(Path(str(tmpdir))) b = fs.Folder(p) digest1 = fs.File(p.joinpath("dir1", "file1.test")).digest_partial digest2 = fs.File(p.joinpath("dir2", "file2.test")).digest_partial digest3 = fs.File(p.joinpath("dir3", "file3.test")).digest_partial digest4 = fs.File(p.joinpath("file1.test")).digest_partial digest5 = fs.File(p.joinpath("file2.test")).digest_partial digest6 = fs.File(p.joinpath("file3.test")).digest_partial # The expected digest is the hash of digests for folders and the direct digest for files folder_digest1 = hasher(digest1).digest() folder_digest2 = hasher(digest2).digest() folder_digest3 = hasher(digest3).digest() digest = hasher(folder_digest1 + folder_digest2 + folder_digest3 + digest4 + digest5 + digest6).digest() eq_(b.digest_partial, digest) digest1 = fs.File(p.joinpath("dir1", "file1.test")).digest_samples digest2 = fs.File(p.joinpath("dir2", "file2.test")).digest_samples digest3 = fs.File(p.joinpath("dir3", "file3.test")).digest_samples digest4 = fs.File(p.joinpath("file1.test")).digest_samples digest5 = fs.File(p.joinpath("file2.test")).digest_samples digest6 = fs.File(p.joinpath("file3.test")).digest_samples # The expected digest is the digest of digests for folders and the direct digest for files folder_digest1 = hasher(digest1).digest() folder_digest2 = hasher(digest2).digest() folder_digest3 = hasher(digest3).digest() digest = hasher(folder_digest1 + folder_digest2 + folder_digest3 + digest4 + digest5 + digest6).digest() eq_(b.digest_samples, digest) def test_has_file_attrs(tmpdir): # a Folder must behave like a file, so it must have mtime attributes b = fs.Folder(Path(str(tmpdir))) assert b.mtime > 0 eq_(b.extension, "")
4,604
Python
.py
96
43.40625
108
0.704965
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,176
fs.py
arsenetar_dupeguru/core/se/fs.py
# Created By: Virgil Dupras # Created On: 2013-07-14 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.util import format_size from core import fs from core.util import format_timestamp, format_perc, format_words, format_dupe_count def get_display_info(dupe, group, delta): size = dupe.size mtime = dupe.mtime m = group.get_match_of(dupe) if m: percentage = m.percentage dupe_count = 0 if delta: r = group.ref size -= r.size mtime -= r.mtime else: percentage = group.percentage dupe_count = len(group.dupes) return { "name": dupe.name, "folder_path": str(dupe.folder_path), "size": format_size(size, 0, 1, False), "extension": dupe.extension, "mtime": format_timestamp(mtime, delta and m), "percentage": format_perc(percentage), "words": format_words(dupe.words) if hasattr(dupe, "words") else "", "dupe_count": format_dupe_count(dupe_count), } class File(fs.File): def get_display_info(self, group, delta): return get_display_info(self, group, delta) class Folder(fs.Folder): def get_display_info(self, group, delta): return get_display_info(self, group, delta)
1,503
Python
.py
40
31.575
89
0.661856
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,177
scanner.py
arsenetar_dupeguru/core/se/scanner.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.trans import tr from core.scanner import Scanner as ScannerBase, ScanOption, ScanType class ScannerSE(ScannerBase): @staticmethod def get_scan_options(): return [ ScanOption(ScanType.FILENAME, tr("Filename")), ScanOption(ScanType.CONTENTS, tr("Contents")), ScanOption(ScanType.FOLDERS, tr("Folders")), ]
658
Python
.py
15
38.6
89
0.719875
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,178
result_table.py
arsenetar_dupeguru/core/se/result_table.py
# Created On: 2011-11-27 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.gui.column import Column from hscommon.trans import trget from core.gui.result_table import ResultTable as ResultTableBase coltr = trget("columns") class ResultTable(ResultTableBase): COLUMNS = [ Column("marked", ""), Column("name", coltr("Filename")), Column("folder_path", coltr("Folder"), optional=True), Column("size", coltr("Size (KB)"), optional=True), Column("extension", coltr("Kind"), visible=False, optional=True), Column("mtime", coltr("Modification"), visible=False, optional=True), Column("percentage", coltr("Match %"), optional=True), Column("words", coltr("Words Used"), visible=False, optional=True), Column("dupe_count", coltr("Dupe Count"), visible=False, optional=True), ] DELTA_COLUMNS = {"size", "mtime"}
1,131
Python
.py
23
44.304348
89
0.695376
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,179
setup.py
DamnWidget_anaconda/setup.py
try: # don't execute this in sublime text import sublime except ImportError: from setuptools import setup, find_packages setup( name='anaconda_tests', packages=find_packages() )
215
Python
.py
9
18.777778
47
0.682927
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,180
anaconda.py
DamnWidget_anaconda/anaconda.py
# -*- coding: utf8 -*- # Copyright (C) 2013 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details """ Anaconda is a python autocompletion and linting plugin for Sublime Text 3 """ import os import sys import logging from string import Template import sublime import sublime_plugin from .anaconda_lib import ioloop from .anaconda_lib.helpers import get_settings from .commands import * # noqa from .listeners import * # noqa if sys.version_info < (3, 3): raise RuntimeError('Anaconda works with Sublime Text 3 only') DISABLED_PLUGINS = [] LOOP_RUNNING = False logger = logging.getLogger(__name__) logger.addHandler(logging.StreamHandler(sys.stdout)) logger.setLevel(logging.DEBUG) def plugin_loaded() -> None: """Called directly from sublime on plugin load """ package_folder = os.path.dirname(__file__) if not os.path.exists(os.path.join(package_folder, 'Main.sublime-menu')): template_file = os.path.join( package_folder, 'templates', 'Main.sublime-menu.tpl' ) with open(template_file, 'r', encoding='utf8') as tplfile: template = Template(tplfile.read()) menu_file = os.path.join(package_folder, 'Main.sublime-menu') with open(menu_file, 'w', encoding='utf8') as menu: menu.write(template.safe_substitute({ 'package_folder': os.path.basename(package_folder) })) # unload any conflictive package while anaconda is running sublime.set_timeout_async(monitor_plugins, 0) if not LOOP_RUNNING: ioloop.loop() def plugin_unloaded() -> None: """Called directly from sublime on plugin unload """ # reenable any conflictive package enable_plugins() if LOOP_RUNNING: ioloop.terminate() def monitor_plugins(): """Monitor for any plugin that conflicts with anaconda """ view = sublime.active_window().active_view() if not get_settings(view, 'auto_unload_conflictive_plugins', True): return plist = [ 'Jedi - Python autocompletion', # breaks auto completion 'SublimePythonIDE', # interfere with autocompletion 'SublimeCodeIntel' # breaks everything, SCI is a mess ] for plugin in plist: if plugin in sys.modules: [ sublime_plugin.unload_module(m) for k, m in sys.modules.items() if plugin in k ] if plugin not in DISABLED_PLUGINS: DISABLED_PLUGINS.append(plugin) sublime.set_timeout_async(monitor_plugins, 5 * 60 * 1000) def enable_plugins(): """Reenable disabled plugins by anaconda """ for plugin in DISABLED_PLUGINS: sublime_plugin.reload_plugin(plugin)
2,778
Python
.py
74
31.459459
79
0.677504
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,181
version.py
DamnWidget_anaconda/version.py
# Copyright (C) 2013 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details import os messages_json = os.path.join(os.path.dirname(__file__), 'messages.json') with open(messages_json, 'r') as message_file: message_data = message_file.read() ver = message_data.splitlines()[-2].split(':')[0].strip().replace('"', '') version = tuple([int(i) for i in ver.split('.')])
425
Python
.py
8
51.125
74
0.699758
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,182
test_lint.py
DamnWidget_anaconda/test/test_lint.py
# Copyright (C) 2012-2016 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details import sys import tempfile import os from nose.plugins.skip import SkipTest from handlers.python_lint_handler import PythonLintHandler PYTHON38 = sys.version_info >= (3, 8) PYTHON3 = sys.version_info >= (3, 0) PYTHON26 = sys.version_info < (2, 7) class real_temp_file(object): def __init__(self, contents): self.contents = contents self.filename = None def __enter__(self): with tempfile.NamedTemporaryFile(delete=False) as f: f.write(self.contents.encode()) self.filename = f.name f.close() return self.filename def __exit__(self, exc_type, exc_value, traceback): os.remove(self.filename) class TestLint(object): """Linting test suite """ _lintable_code = ''' def f(): a = 1 [1 for a, b in [(1, 2)]] ''' _lintable_assignmentoperator = ''' def f(): if a := 1: return a ''' _lintable_docstring = ''' def f(): """This is a docst ring"""''' _import_validator_code = ''' import idontexists def main(): idontexists('Hello World!') ''' _type_checkable_code = ''' def f(a: int) -> str: return a ''' _type_checkable_async_code = ''' import asyncio async def f(a: int) -> int: await asyncio.sleep(2) return a ''' def setUp(self): self._settings = { 'use_pyflakes': False, 'use_pylint': False, 'use_pep257': False, 'pep8': False, 'vapidate_imports': False, 'use_mypy': False, 'mypypath': '', 'mypy_settings': [''] } def test_pyflakes_lint(self): handler = PythonLintHandler('lint', None, 0, 0, self._settings, self._check_pyflakes) self._settings['use_pyflakes'] = True handler.lint(self._lintable_code) def test_pyflakes_ignore(self): handler = PythonLintHandler('lint', None, 0, 0, self._settings, self._check_pyflakes_ignore) # noqa self._settings['use_pyflakes'] = True self._settings['pyflakes_ignore'] = 'F841' def test_pep8_lint(self): self._settings['pep8'] = True handler = PythonLintHandler('lint', None, 0, 0, self._settings, self._check_pep8) handler.lint(self._lintable_code) def test_pep8_ignores(self): self._settings['pep8'] = True self._settings['pep8_ignore'] = ['W293'] handler = PythonLintHandler('lint', None, 0, 0, self._settings, self._check_pep8_ignores) # noqa handler.lint(self._lintable_code) def test_pep8_max_line_length(self): self._settings['pep8'] = True self._settings['pep8_max_line_length'] = 120 handler = PythonLintHandler('lint', None, 0, 0, self._settings, self._check_pep8_max_line_length) # noqa handler.lint('a = \'this is a very long string: {0}\'\n'.format('a' * 80)) # noqa def test_pep8_assignment_operator(self): if not PYTHON38: raise SkipTest() self._settings['pep8'] = True handler = PythonLintHandler('lint', None, 0, 0, self._settings, self._check_pep8) handler.lint(self._lintable_assignmentoperator) def test_pep257_lint(self): if PYTHON26: raise SkipTest('PyDocStyle dropped support to Python2.6') self._settings['use_pep257'] = True handler = PythonLintHandler('lint', None, 0, 0, self._settings, self._check_pep257) handler.lint(self._lintable_docstring, '') def test_pep257_ignores(self): if PYTHON26: raise SkipTest('PyDocStyle dropped support to Python2.6') self._settings['use_pep257'] = True self._settings['pep257_ignore'] = ['D100', 'D400', 'D209', 'D205', 'D401', 'D404', 'D213'] # noqa handler = PythonLintHandler('lint', None, 0, 0, self._settings, self._check_pep257_ignores) # noqa handler.lint(self._lintable_docstring, '') def test_import_validator(self): self._settings['validate_imports'] = True handler = PythonLintHandler('lint', None, 0, 0, self._settings, self._check_validate_imports) # noqa handler.lint(self._import_validator_code, '') def test_mypy(self): if not PYTHON3: raise SkipTest() try: import mypy # noqa except ImportError: raise SkipTest('MyPy not installed') with real_temp_file(self._type_checkable_code) as temp_file_name: self._settings['use_mypy'] = True handler = PythonLintHandler('lint', None, 0, 0, self._settings, self._check_mypy) handler.lint(self._type_checkable_code, temp_file_name) # noqa def test_mypy_fast_parser(self): if not PYTHON3: raise SkipTest() try: import mypy # noqa except ImportError: raise SkipTest('MyPy not installed') with real_temp_file(self._type_checkable_async_code) as temp_file_name: self._settings['use_mypy'] = True self._settings['mypy_settings'] = ['--fast-parser', ''] handler = PythonLintHandler('lint', None, 0, 0, self._settings, self._check_mypy_async) # noqa handler.lint(self._type_checkable_code, temp_file_name) # noqa def _check_pyflakes(self, result): assert result['success'] is True assert len(result['errors']) == 1 assert result['errors'][0]['level'] == 'W' err = 'list comprehension redefines \'a\' from line 3' \ if not PYTHON3 else 'local variable \'a\' is assigned to but never used' # noqa assert result['errors'][0]['raw_error'] == err assert result['errors'][0]['underline_range'] is False assert result['uid'] == 0 assert result['vid'] == 0 def _check_pep8(self, result): assert result['success'] is True assert len(result['errors']) == 2 error1 = result['errors'][0] assert error1['raw_error'] == '[V] PEP 8 (W391): blank line at end of file' # noqa assert error1['level'] == 'V' assert error1['underline_range'] is True error2 = result['errors'][1] assert error2['raw_error'] == '[V] PEP 8 (W293): blank line contains whitespace' # noqa assert error2['level'] == 'V' assert error2['underline_range'] is True assert result['uid'] == 0 assert result['vid'] == 0 def _check_pep8_ignores(self, result): assert result['success'] is True assert len(result['errors']) == 1 error1 = result['errors'][0] assert error1['raw_error'] == '[V] PEP 8 (W391): blank line at end of file' # noqa assert error1['level'] == 'V' assert error1['underline_range'] is True assert result['uid'] == 0 assert result['vid'] == 0 def _check_pep8_max_line_length(self, result): print(result) assert result['success'] is True assert len(result['errors']) == 0 assert result['uid'] == 0 assert result['vid'] == 0 def _check_pyflakes_ignore(self, result): assert result['success'] is True assert len(result['errors']) == 0 assert result['uid'] == 0 assert result['vid'] == 0 def _check_pep257(self, result): assert result['success'] is True assert len(result['errors']) == 7 raw_errors = [r['raw_error'] for r in result['errors']] assert '[V] PEP 257 (D100): Missing docstring in public module' in raw_errors # noqa assert '[V] PEP 257 (D209): Multi-line docstring closing quotes should be on a separate line' in raw_errors # noqa assert '[V] PEP 257 (D205): 1 blank line required between summary line and description (found 0)' in raw_errors # noqa assert '[V] PEP 257 (D400): First line should end with a period (not \'t\')' in raw_errors # noqa assert "[V] PEP 257 (D401): First line should be in imperative mood; try rephrasing (found 'This')" in raw_errors # noqa error1, error2, error3, error4, error5, _, _ = result['errors'] assert (error1['level'], error2['level'], error3['level'], error4['level'], error5['level']) == ('V', 'V', 'V', 'V', 'V') # noqa assert result['uid'] == 0 assert result['vid'] == 0 def _check_pep257_ignores(self, result): assert result['success'] is True assert len(result['errors']) == 0 assert result['uid'] == 0 assert result['vid'] == 0 def _check_validate_imports(self, result): assert result['success'] is True assert len(result['errors']) == 1 assert result['errors'][0]['raw_error'] == "[E] ImportValidator (801): can't import idontexists" # noqa assert result['errors'][0]['code'] == 801 assert result['errors'][0]['level'] == 'E' assert result['errors'][0]['underline_range'] is True assert result['uid'] == 0 assert result['vid'] == 0 def _check_mypy(self, result): assert result['success'] is True assert len(result['errors']) == 1 assert result['errors'][0]['raw_error'] == '[W] MyPy error: Incompatible return value type (got "int", expected "str")' # noqa assert result['errors'][0]['level'] == 'W' assert result['uid'] == 0 assert result['vid'] == 0 def _check_mypy_async(self, result): assert result['success'] is True assert len(result['errors']) == 0 assert result['uid'] == 0 assert result['vid'] == 0
9,591
Python
.py
210
37.704762
137
0.60634
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,183
test_qa.py
DamnWidget_anaconda/test/test_qa.py
# Copyright (C) 2012-2016 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details from commands.mccabe import McCabe from handlers.qa_handler import QAHandler from linting.anaconda_mccabe import AnacondaMcCabe class TestQa(object): """QA test suite """ _code = ''' def f(n): if n > 3: return "bigger than three" elif n > 4: return "is never executed" else: return "smaller than or equal to three" ''' def test_mccabe_command(self): McCabe( self._check_mccabe, 0, 0, AnacondaMcCabe, self._code, 0, '') def test_mccabe_high_threshold(self): def _check_threshold_4(result): assert result['success'] is True assert len(result['errors']) == 1 def _check_threshold_7(result): assert result['success'] is True assert len(result['errors']) == 0 McCabe(_check_threshold_4, 0, 0, AnacondaMcCabe, self._code, 4, '') McCabe(_check_threshold_7, 0, 0, AnacondaMcCabe, self._code, 7, '') def test_mccabe_handler(self): data = {'code': self._code, 'threshold': 4, 'filename': ''} handler = QAHandler('mccabe', data, 0, 0, {}, self._check_mccabe) handler.run() def _check_mccabe(self, result): assert result['success'] is True assert result['uid'] == 0 assert result['vid'] == 0 assert len(result['errors']) == 1 assert result['errors'][0]['message'] == "'f' is too complex (4)" assert result['errors'][0]['line'] == 2 assert result['errors'][0]['code'] == 'C901' assert result['errors'][0]['offset'] == 1
1,707
Python
.py
42
33.261905
75
0.605566
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,184
test_completion.py
DamnWidget_anaconda/test/test_completion.py
# Copyright (C) 2012-2016 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details import sys import jedi from commands.autocomplete import AutoComplete from handlers.jedi_handler import JediHandler PYTHON36 = sys.version_info >= (3, 6) class TestAutoCompletion(object): """Auto completion test suite """ def setUp(self): self.settings = {} def test_autocomplete_command(self): AutoComplete(self._check, 0, jedi.Script('import os; os.')) def test_autocomplete_handler(self): data = {'source': 'import os; os.', 'line': 1, 'offset': 14} handler = JediHandler('autocomplete', data, 0, 0, self.settings, self._check) handler.run() def test_autocomplete_not_in_string(self): data = {'source': 'import os; "{os.', 'line': 1, 'offset': 16} handler = JediHandler('autocomplete', data, 0, 0, self.settings, self._check_false) handler.run() def test_autocomplete_in_fstring(self): data = {'source': 'import os; f"{os.', 'line': 1, 'offset': 17} handler = JediHandler( 'autocomplete', data, 0, 0, self.settings, self._check if PYTHON36 else self._check_false ) handler.run() def _check(self, kwrgs): assert kwrgs['success'] is True assert len(kwrgs['completions']) > 0 if sys.version_info < (3, 6): assert kwrgs['completions'][0] == ('abort\tfunction', 'abort') else: assert kwrgs['completions'][0] == ('abc\tmodule', 'abc') assert kwrgs['uid'] == 0 def _check_false(self, kwrgs): assert kwrgs['success'] is False
1,695
Python
.py
39
36.25641
91
0.629111
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,185
test_find_usages.py
DamnWidget_anaconda/test/test_find_usages.py
# Copyright (C) 2012-2016 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details import jedi from commands.find_usages import FindUsages from handlers.jedi_handler import JediHandler _code = 'from _usages_helper import usages_helper' class TestFindUsages(object): """FindUsages tests suite """ def test_find_usages_command(self): FindUsages(self._check_find_usages, 0, jedi.Script(_code)) def test_find_usages_handler(self): data = {'source': _code, 'line': 1, 'offset': 40, 'filename': None} handler = JediHandler('usages', data, 0, 0, {}, self._check_find_usages) handler.run() def _check_find_usages(self, result): assert result['success'] is True assert len(result['result']) == 1 assert result['result'][0] == ('_usages_helper.usages_helper', None, 1, 27) assert result['uid'] == 0
931
Python
.py
20
40.9
83
0.677384
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,186
test_doc.py
DamnWidget_anaconda/test/test_doc.py
# -*- encoding: utf8 -*- # Copyright (C) 2012-2016 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details import sys import jedi from commands.doc import Doc from handlers.jedi_handler import JediHandler src = 'def test_src():\n\t"""Test String\n\t"""\n\ntest_src' src_escape = 'def test_src():\n\t"""<strong>Espa&nacute;a currency €</strong>"""\n\ntest_src' # noqa class TestDoc(object): """Doc test suite """ def test_doc_command(self): Doc(self._check_html, 0, jedi.Script(src), True) def test_doc_plain(self): Doc(self._check_plain, 0, jedi.Script(src), False) def test_doc_html_escape(self): Doc(self._check_html_escape, 0, jedi.Script(src_escape), True) def test_doc_no_definiion(self): Doc(self._check_no_definition, 0, jedi.Script('nothing'), False) def test_doc_handler(self): data = {'source': src, 'line': 5, 'offset': 8, 'html': True} handler = JediHandler('doc', data, 0, 0, {}, self._check_handler) handler.run() def _check_html(self, kwrgs): self._common_assertions(kwrgs) assert kwrgs['doc'].strip() == ( '__main__.test_src\ntest_src()<br><br>Test String<br>' ) def _check_plain(self, kwrgs): self._common_assertions(kwrgs) assert kwrgs['doc'].strip() == "Docstring for {0}\n{1}\n{2}".format( '__main__.test_src', '=' * 40, 'test_src()\n\nTest String' ) def _check_html_escape(self, kwrgs): self._common_assertions(kwrgs) if sys.version_info >= (3, 4): print(kwrgs['doc']) assert kwrgs['doc'].strip() == '__main__.test_src\ntest_src()<br><br>&lt;strong&gt;Espańa currency €&lt;/strong&gt;' # noqa if sys.version_info < (3, 0): print(repr(kwrgs['doc'])) assert kwrgs['doc'].strip() == '__main__.test_src\ntest_src()<br><br>&lt;strong&gt;Espa&amp;nacute;a currency \xe2\x82\xac&lt;/strong&gt;' # noqa def _check_no_definition(self, kwrgs): assert kwrgs['success'] is False assert kwrgs['uid'] == 0 assert kwrgs['doc'] == '' def _check_handler(self, kwrgs): self._check_html(kwrgs) def _common_assertions(self, kwrgs): assert kwrgs['success'] is True assert kwrgs['uid'] == 0
2,391
Python
.py
53
37.54717
158
0.60242
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,187
test_goto.py
DamnWidget_anaconda/test/test_goto.py
# Copyright (C) 2012-2016 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details import re import sys import jedi from commands.goto import Goto, GotoAssignment from handlers.jedi_handler import JediHandler src = 'import re; re.compile' PYTHON3 = sys.version_info >= (3, 0) class TestGoto(object): """Goto test suite """ def test_goto_command(self): Goto(self._check_goto, 0, jedi.Script(src)) def test_goto_handler(self): data = {'source': src, 'line': 1, 'offset': 21} handler = JediHandler('goto', data, 0, 0, {}, self._check_goto) handler.run() def _check_goto(self, result): assert result['success'] is True assert len(result['result']) == 1 if PYTHON3: assert result['result'][0][1] == re.__file__ else: file_name = re.__file__ if '.pyc' in file_name: assert result['result'][0][1] == file_name[:-1] else: assert result['result'][0][1] == file_name class TestGotoAssignment(object): """Goto test suite """ def test_goto_assignment_command(self): GotoAssignment(self._check_goto_assignment, 0, jedi.Script(src, line=1, column=13)) def test_goto_assignment_handler(self): data = {'source': src, 'line': 1, 'offset': 13} handler = JediHandler('goto_assignment', data, 0, 0, {}, self._check_goto_assignment) handler.run() def _check_goto_assignment(self, result): assert result['success'] is True assert len(result['result']) == 1 result = result['result'][0] assert result[1] is None assert result[2] == 1 assert result[3] == 8
1,761
Python
.py
45
31.933333
93
0.614345
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,188
test_complete_parameters.py
DamnWidget_anaconda/test/test_complete_parameters.py
# Copyright (C) 2012-2016 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details import sys import jedi from handlers.jedi_handler import JediHandler from commands.complete_parameters import CompleteParameters PYTHON3 = sys.version_info >= (3, 0) class TestCompleteParameters(object): """CompleteParameters tests suite """ def setUp(self): self.settings = {'complete_all_parameters': False} self.script = jedi.Script('open(') def test_complete_parameters_command(self): CompleteParameters( self._check_parameters, 0, self.script, self.settings) def test_complete_all_parameters(self): self.settings['complete_all_parameters'] = True CompleteParameters( self._check_all_parameters, 0, self.script, self.settings) def test_complete_parameters_handler(self): data = { 'source': 'open(', 'line': 1, 'offset': 5, 'filname': None, 'settings': self.settings } handler = JediHandler( 'parameters', data, 0, 0, self.settings, self._check_parameters) handler.run() def test_complete_all_parameters_handler(self): self.settings['complete_all_parameters'] = True data = { 'source': 'open(', 'line': 1, 'offset': 5, 'filname': None, 'settings': self.settings } handler = JediHandler( 'parameters', data, 0, 0, self.settings, self._check_all_parameters) handler.run() def _check_parameters(self, result): assert result['success'] is True assert result['template'] == '${1:file: Union[str, bytes, int]}' if PYTHON3 else u'${1:file}' assert result['uid'] == 0 def _check_all_parameters(self, result): assert result['success'] is True assert result['template'] == "${1:file: Union[str, bytes, int]}, mode: str=${2:...}, buffering: int=${3:...}, encoding: Optional[str]=${4:...}, errors: Optional[str]=${5:...}, newline: Optional[str]=${6:...}, closefd: bool=${7:...}, opener: Optional[Callable[[str, int], int]]=${8:...}" if PYTHON3 else u"${1:file}, mode=${2:'r'}, buffering=${3:-1}, encoding=${4:None}, errors=${5:None}, newline=${6:None}, closefd=${7:True}" # noqa assert result['uid'] == 0
2,335
Python
.py
45
44.088889
441
0.628735
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,189
phantoms.py
DamnWidget_anaconda/anaconda_lib/phantoms.py
# Copyright (C) 2015 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details import os import glob import logging from string import Template import sublime from .helpers import get_settings class Phantom(object): """Just a wrapper around Sublime Text 3 phantoms """ themes = {} # type: Dict[str, bytes] templates = {} # type: Dict[str, str] loaded = False phantomsets = {} def __init__(self) -> None: if int(sublime.version()) < 3124: return if Phantom.loaded is False: self._load_css_themes() self._load_phantom_templates() Phantom.loaded = True def clear_phantoms(self, view): if not self.loaded: return vid = view.id() if vid in self.phantomsets: self.phantomsets[vid].update([]) def update_phantoms(self, view, phantoms): if not self.loaded: return thmname = get_settings(view, 'anaconda_linter_phantoms_theme', 'phantom') tplname = get_settings(view, 'anaconda_linter_phantoms_template', 'default') thm = self.themes.get(thmname, self.themes['phantom']) tpl = self.templates.get(tplname, self.templates['default']) vid = view.id() if vid not in self.phantomsets: self.phantomsets[vid] = sublime.PhantomSet(view, 'Anaconda') sublime_phantoms = [] for item in phantoms: region = view.full_line(view.text_point(item['line'], 0)) context = {'css': thm} context.update(item) content = tpl.safe_substitute(context) sublime_phantoms.append(sublime.Phantom(region, content, sublime.LAYOUT_BLOCK)) self.phantomsets[vid].update(sublime_phantoms) def _load_phantom_templates(self) -> None: """Load phantoms templates from anaconda phantoms templates """ template_files_pattern = os.path.join( os.path.dirname(__file__), os.pardir, 'templates', 'phantoms', '*.tpl') for template_file in glob.glob(template_files_pattern): with open(template_file, 'r', encoding='utf8') as tplfile: tplname = os.path.basename(template_file).split('.tpl')[0] tpldata = '<style>${{css}}</style>{}'.format(tplfile.read()) self.templates[tplname] = Template(tpldata) def _load_css_themes(self) -> None: """ Load any css theme found in the anaconda CSS themes directory or in the User/Anaconda.themes directory """ css_files_pattern = os.path.join( os.path.dirname(__file__), os.pardir, 'css', '*.css') for css_file in glob.glob(css_files_pattern): logging.info('anaconda: {} css theme loaded'.format( self._load_css(css_file)) ) packages = sublime.active_window().extract_variables()['packages'] user_css_path = os.path.join(packages, 'User', 'Anaconda.themes') if os.path.exists(user_css_path): css_files_pattern = os.path.join(user_css_path, '*.css') for css_file in glob.glob(css_files_pattern): logging.info( 'anaconda: {} user css theme loaded', self._load_css(css_file) ) def _load_css(self, css_file: str) -> str: """Load a css file """ theme_name = os.path.basename(css_file).split('.css')[0] with open(css_file, 'r') as resource: self.themes[theme_name] = resource.read() return theme_name
3,660
Python
.py
84
33.797619
91
0.599831
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,190
tooltips.py
DamnWidget_anaconda/anaconda_lib/tooltips.py
# Copyright (C) 2015 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details import os import glob import logging from string import Template import sublime from .helpers import get_settings from ._typing import Callable, Union, Dict class Tooltip(object): """Just a wrapper around Sublime Text 3 tooltips """ themes = {} # type: Dict[str, bytes] tooltips = {} # type: Dict[str, str] loaded = False basesize = 75 def __init__(self, theme: str) -> None: self.theme = theme if int(sublime.version()) < 3070: return if Tooltip.loaded is False: self._load_css_themes() self._load_tooltips() Tooltip.loaded = True def show_tooltip(self, view: sublime.View, tooltip: str, content: Dict[str, str], fallback: Callable) -> None: # noqa """Generates and display a tooltip or pass execution to fallback """ st_ver = int(sublime.version()) if st_ver < 3070: return fallback() width = get_settings(view, 'font_size', 8) * 75 kwargs = {'location': -1, 'max_width': width if width < 900 else 900} if st_ver >= 3071: kwargs['flags'] = sublime.COOPERATE_WITH_AUTO_COMPLETE text = self._generate(tooltip, content) if text is None: return fallback() return view.show_popup(text, **kwargs) def _generate(self, tooltip: str, content: Dict[str, str]) -> Union[Dict[str, str], None]: # noqa """Generate a tooltip with the given text """ try: t = self.theme theme = self.themes[t] if t in self.themes else self.themes['popup'] # noqa context = {'css': theme} context.update(content) data = self.tooltips[tooltip].safe_substitute(context) return data except KeyError as err: logging.error( 'while generating tooltip: tooltip {} don\'t exists'.format( str(err)) ) return None def _load_tooltips(self) -> None: """Load tooltips templates from anaconda tooltips templates """ template_files_pattern = os.path.join( os.path.dirname(__file__), os.pardir, 'templates', 'tooltips', '*.tpl') for template_file in glob.glob(template_files_pattern): with open(template_file, 'r', encoding='utf8') as tplfile: tplname = os.path.basename(template_file).split('.tpl')[0] tpldata = '<style>${{css}}</style>{}'.format(tplfile.read()) self.tooltips[tplname] = Template(tpldata) def _load_css_themes(self) -> None: """ Load any css theme found in the anaconda CSS themes directory or in the User/Anaconda.themes directory """ css_files_pattern = os.path.join( os.path.dirname(__file__), os.pardir, 'css', '*.css') for css_file in glob.glob(css_files_pattern): logging.info('anaconda: {} css theme loaded'.format( self._load_css(css_file)) ) packages = sublime.active_window().extract_variables()['packages'] user_css_path = os.path.join(packages, 'User', 'Anaconda.themes') if os.path.exists(user_css_path): css_files_pattern = os.path.join(user_css_path, '*.css') for css_file in glob.glob(css_files_pattern): logging.info( 'anaconda: {} user css theme loaded', self._load_css(css_file) ) def _load_css(self, css_file: str) -> str: """Load a css file """ theme_name = os.path.basename(css_file).split('.css')[0] with open(css_file, 'r') as resource: self.themes[theme_name] = resource.read() return theme_name
3,948
Python
.py
92
32.956522
122
0.583246
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,191
_typing.py
DamnWidget_anaconda/anaconda_lib/_typing.py
# TODO nits: # Get rid of asserts that are the caller's fault. # Docstrings (e.g. ABCs). import abc from abc import abstractmethod, abstractproperty import collections import functools import re as stdlib_re # Avoid confusion with the re we export. import sys import types try: import collections.abc as collections_abc except ImportError: import collections as collections_abc # Fallback for PY3.2. # Please keep __all__ alphabetized within each category. __all__ = [ # Super-special typing primitives. 'Any', 'Callable', 'Generic', 'Optional', 'TypeVar', 'Union', 'Tuple', # ABCs (from collections.abc). 'AbstractSet', # collections.abc.Set. 'ByteString', 'Container', 'Hashable', 'ItemsView', 'Iterable', 'Iterator', 'KeysView', 'Mapping', 'MappingView', 'MutableMapping', 'MutableSequence', 'MutableSet', 'Sequence', 'Sized', 'ValuesView', # Structural checks, a.k.a. protocols. 'Reversible', 'SupportsAbs', 'SupportsFloat', 'SupportsInt', 'SupportsRound', # Concrete collection types. 'Dict', 'List', 'Set', 'NamedTuple', # Not really a type. 'Generator', # One-off things. 'AnyStr', 'cast', 'get_type_hints', 'no_type_check', 'no_type_check_decorator', 'overload', # Submodules. 'io', 're', ] def _qualname(x): if sys.version_info[:2] >= (3, 3): return x.__qualname__ else: # Fall back to just name. return x.__name__ class TypingMeta(type): """Metaclass for every type defined below. This overrides __new__() to require an extra keyword parameter '_root', which serves as a guard against naive subclassing of the typing classes. Any legitimate class defined using a metaclass derived from TypingMeta (including internal subclasses created by e.g. Union[X, Y]) must pass _root=True. This also defines a dummy constructor (all the work is done in __new__) and a nicer repr(). """ _is_protocol = False def __new__(cls, name, bases, namespace, *, _root=False): if not _root: raise TypeError("Cannot subclass %s" % (', '.join(map(_type_repr, bases)) or '()')) return super().__new__(cls, name, bases, namespace) def __init__(self, *args, **kwds): pass def _eval_type(self, globalns, localns): """Override this in subclasses to interpret forward references. For example, Union['C'] is internally stored as Union[_ForwardRef('C')], which should evaluate to _Union[C], where C is an object found in globalns or localns (searching localns first, of course). """ return self def _has_type_var(self): return False def __repr__(self): return '%s.%s' % (self.__module__, _qualname(self)) class Final: """Mix-in class to prevent instantiation.""" __slots__ = () def __new__(self, *args, **kwds): raise TypeError("Cannot instantiate %r" % self.__class__) class _ForwardRef(TypingMeta): """Wrapper to hold a forward reference.""" def __new__(cls, arg): if not isinstance(arg, str): raise TypeError('ForwardRef must be a string -- got %r' % (arg,)) try: code = compile(arg, '<string>', 'eval') except SyntaxError: raise SyntaxError('ForwardRef must be an expression -- got %r' % (arg,)) self = super().__new__(cls, arg, (), {}, _root=True) self.__forward_arg__ = arg self.__forward_code__ = code self.__forward_evaluated__ = False self.__forward_value__ = None typing_globals = globals() frame = sys._getframe(1) while frame is not None and frame.f_globals is typing_globals: frame = frame.f_back assert frame is not None self.__forward_frame__ = frame return self def _eval_type(self, globalns, localns): if not isinstance(localns, dict): raise TypeError('ForwardRef localns must be a dict -- got %r' % (localns,)) if not isinstance(globalns, dict): raise TypeError('ForwardRef globalns must be a dict -- got %r' % (globalns,)) if not self.__forward_evaluated__: if globalns is None and localns is None: globalns = localns = {} elif globalns is None: globalns = localns elif localns is None: localns = globalns self.__forward_value__ = _type_check( eval(self.__forward_code__, globalns, localns), "Forward references must evaluate to types.") self.__forward_evaluated__ = True return self.__forward_value__ def __instancecheck__(self, obj): raise TypeError("Forward references cannot be used with isinstance().") def __subclasscheck__(self, cls): if not self.__forward_evaluated__: globalns = self.__forward_frame__.f_globals localns = self.__forward_frame__.f_locals try: self._eval_type(globalns, localns) except NameError: return False # Too early. return issubclass(cls, self.__forward_value__) def __repr__(self): return '_ForwardRef(%r)' % (self.__forward_arg__,) class _TypeAlias: """Internal helper class for defining generic variants of concrete types. Note that this is not a type; let's call it a pseudo-type. It can be used in instance and subclass checks, e.g. isinstance(m, Match) or issubclass(type(m), Match). However, it cannot be itself the target of an issubclass() call; e.g. issubclass(Match, C) (for some arbitrary class C) raises TypeError rather than returning False. """ __slots__ = ('name', 'type_var', 'impl_type', 'type_checker') def __new__(cls, *args, **kwds): """Constructor. This only exists to give a better error message in case someone tries to subclass a type alias (not a good idea). """ if (len(args) == 3 and isinstance(args[0], str) and isinstance(args[1], tuple)): # Close enough. raise TypeError("A type alias cannot be subclassed") return object.__new__(cls) def __init__(self, name, type_var, impl_type, type_checker): """Initializer. Args: name: The name, e.g. 'Pattern'. type_var: The type parameter, e.g. AnyStr, or the specific type, e.g. str. impl_type: The implementation type. type_checker: Function that takes an impl_type instance. and returns a value that should be a type_var instance. """ assert isinstance(name, str), repr(name) assert isinstance(type_var, type), repr(type_var) assert isinstance(impl_type, type), repr(impl_type) assert not isinstance(impl_type, TypingMeta), repr(impl_type) self.name = name self.type_var = type_var self.impl_type = impl_type self.type_checker = type_checker def __repr__(self): return "%s[%s]" % (self.name, _type_repr(self.type_var)) def __getitem__(self, parameter): assert isinstance(parameter, type), repr(parameter) if not isinstance(self.type_var, TypeVar): raise TypeError("%s cannot be further parameterized." % self) if self.type_var.__constraints__: if not issubclass(parameter, Union[self.type_var.__constraints__]): raise TypeError("%s is not a valid substitution for %s." % (parameter, self.type_var)) return self.__class__(self.name, parameter, self.impl_type, self.type_checker) def __instancecheck__(self, obj): raise TypeError("Type aliases cannot be used with isinstance().") def __subclasscheck__(self, cls): if cls is Any: return True if isinstance(cls, _TypeAlias): # Covariance. For now, we compare by name. return (cls.name == self.name and issubclass(cls.type_var, self.type_var)) else: # Note that this is too lenient, because the # implementation type doesn't carry information about # whether it is about bytes or str (for example). return issubclass(cls, self.impl_type) def _has_type_var(t): return t is not None and isinstance(t, TypingMeta) and t._has_type_var() def _eval_type(t, globalns, localns): if isinstance(t, TypingMeta): return t._eval_type(globalns, localns) else: return t def _type_check(arg, msg): """Check that the argument is a type, and return it. As a special case, accept None and return type(None) instead. Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable. The msg argument is a human-readable error message, e.g. "Union[arg, ...]: arg should be a type." We append the repr() of the actual value (truncated to 100 chars). """ if arg is None: return type(None) if isinstance(arg, str): arg = _ForwardRef(arg) if not isinstance(arg, (type, _TypeAlias)): raise TypeError(msg + " Got %.100r." % (arg,)) return arg def _type_repr(obj): """Return the repr() of an object, special-casing types. If obj is a type, we return a shorter version than the default type.__repr__, based on the module and qualified name, which is typically enough to uniquely identify a type. For everything else, we fall back on repr(obj). """ if isinstance(obj, type) and not isinstance(obj, TypingMeta): if obj.__module__ == 'builtins': return _qualname(obj) else: return '%s.%s' % (obj.__module__, _qualname(obj)) else: return repr(obj) class AnyMeta(TypingMeta): """Metaclass for Any.""" def __new__(cls, name, bases, namespace, _root=False): self = super().__new__(cls, name, bases, namespace, _root=_root) return self def __instancecheck__(self, obj): raise TypeError("Any cannot be used with isinstance().") def __subclasscheck__(self, cls): if not isinstance(cls, type): return super().__subclasscheck__(cls) # To TypeError. return True class Any(Final, metaclass=AnyMeta, _root=True): """Special type indicating an unconstrained type. - Any object is an instance of Any. - Any class is a subclass of Any. - As a special case, Any and object are subclasses of each other. """ __slots__ = () class TypeVar(TypingMeta, metaclass=TypingMeta, _root=True): """Type variable. Usage:: T = TypeVar('T') # Can be anything A = TypeVar('A', str, bytes) # Must be str or bytes Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function definitions. See class Generic for more information on generic types. Generic functions work as follows: def repeat(x: T, n: int) -> Sequence[T]: '''Return a list containing n references to x.''' return [x]*n def longest(x: A, y: A) -> A: '''Return the longest of two strings.''' return x if len(x) >= len(y) else y The latter example's signature is essentially the overloading of (str, str) -> str and (bytes, bytes) -> bytes. Also note that if the arguments are instances of some subclass of str, the return type is still plain str. At runtime, isinstance(x, T) will raise TypeError. However, issubclass(C, T) is true for any class C, and issubclass(str, A) and issubclass(bytes, A) are true, and issubclass(int, A) is false. Type variables may be marked covariant or contravariant by passing covariant=True or contravariant=True. See PEP 484 for more details. By default type variables are invariant. Type variables can be introspected. e.g.: T.__name__ == 'T' T.__constraints__ == () T.__covariant__ == False T.__contravariant__ = False A.__constraints__ == (str, bytes) """ def __new__(cls, name, *constraints, bound=None, covariant=False, contravariant=False): self = super().__new__(cls, name, (Final,), {}, _root=True) if covariant and contravariant: raise ValueError("Bivariant type variables are not supported.") self.__covariant__ = bool(covariant) self.__contravariant__ = bool(contravariant) if constraints and bound is not None: raise TypeError("Constraints cannot be combined with bound=...") if constraints and len(constraints) == 1: raise TypeError("A single constraint is not allowed") msg = "TypeVar(name, constraint, ...): constraints must be types." self.__constraints__ = tuple(_type_check(t, msg) for t in constraints) if bound: self.__bound__ = _type_check(bound, "Bound must be a type.") else: self.__bound__ = None return self def _has_type_var(self): return True def __repr__(self): if self.__covariant__: prefix = '+' elif self.__contravariant__: prefix = '-' else: prefix = '~' return prefix + self.__name__ def __instancecheck__(self, instance): raise TypeError("Type variables cannot be used with isinstance().") def __subclasscheck__(self, cls): # TODO: Make this raise TypeError too? if cls is self: return True if cls is Any: return True if self.__bound__ is not None: return issubclass(cls, self.__bound__) if self.__constraints__: return any(issubclass(cls, c) for c in self.__constraints__) return True # Some unconstrained type variables. These are used by the container types. T = TypeVar('T') # Any type. KT = TypeVar('KT') # Key type. VT = TypeVar('VT') # Value type. T_co = TypeVar('T_co', covariant=True) # Any type covariant containers. V_co = TypeVar('V_co', covariant=True) # Any type covariant containers. VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers. T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant. # A useful type variable with constraints. This represents string types. # TODO: What about bytearray, memoryview? AnyStr = TypeVar('AnyStr', bytes, str) class UnionMeta(TypingMeta): """Metaclass for Union.""" def __new__(cls, name, bases, namespace, parameters=None, _root=False): if parameters is None: return super().__new__(cls, name, bases, namespace, _root=_root) if not isinstance(parameters, tuple): raise TypeError("Expected parameters=<tuple>") # Flatten out Union[Union[...], ...] and type-check non-Union args. params = [] msg = "Union[arg, ...]: each arg must be a type." for p in parameters: if isinstance(p, UnionMeta): params.extend(p.__union_params__) else: params.append(_type_check(p, msg)) # Weed out strict duplicates, preserving the first of each occurrence. all_params = set(params) if len(all_params) < len(params): new_params = [] for t in params: if t in all_params: new_params.append(t) all_params.remove(t) params = new_params assert not all_params, all_params # Weed out subclasses. # E.g. Union[int, Employee, Manager] == Union[int, Employee]. # If Any or object is present it will be the sole survivor. # If both Any and object are present, Any wins. # Never discard type variables, except against Any. # (In particular, Union[str, AnyStr] != AnyStr.) all_params = set(params) for t1 in params: if t1 is Any: return Any if isinstance(t1, TypeVar): continue if isinstance(t1, _TypeAlias): # _TypeAlias is not a real class. continue if any(issubclass(t1, t2) for t2 in all_params - {t1} if not isinstance(t2, TypeVar)): all_params.remove(t1) # It's not a union if there's only one type left. if len(all_params) == 1: return all_params.pop() # Create a new class with these params. self = super().__new__(cls, name, bases, {}, _root=True) self.__union_params__ = tuple(t for t in params if t in all_params) self.__union_set_params__ = frozenset(self.__union_params__) return self def _eval_type(self, globalns, localns): p = tuple(_eval_type(t, globalns, localns) for t in self.__union_params__) if p == self.__union_params__: return self else: return self.__class__(self.__name__, self.__bases__, {}, p, _root=True) def _has_type_var(self): if self.__union_params__: for t in self.__union_params__: if _has_type_var(t): return True return False def __repr__(self): r = super().__repr__() if self.__union_params__: r += '[%s]' % (', '.join(_type_repr(t) for t in self.__union_params__)) return r def __getitem__(self, parameters): if self.__union_params__ is not None: raise TypeError( "Cannot subscript an existing Union. Use Union[u, t] instead.") if parameters == (): raise TypeError("Cannot take a Union of no types.") if not isinstance(parameters, tuple): parameters = (parameters,) return self.__class__(self.__name__, self.__bases__, dict(self.__dict__), parameters, _root=True) def __eq__(self, other): if not isinstance(other, UnionMeta): return NotImplemented return self.__union_set_params__ == other.__union_set_params__ def __hash__(self): return hash(self.__union_set_params__) def __instancecheck__(self, obj): raise TypeError("Unions cannot be used with isinstance().") def __subclasscheck__(self, cls): if cls is Any: return True if self.__union_params__ is None: return isinstance(cls, UnionMeta) elif isinstance(cls, UnionMeta): if cls.__union_params__ is None: return False return all(issubclass(c, self) for c in (cls.__union_params__)) elif isinstance(cls, TypeVar): if cls in self.__union_params__: return True if cls.__constraints__: return issubclass(Union[cls.__constraints__], self) return False else: return any(issubclass(cls, t) for t in self.__union_params__) class Union(Final, metaclass=UnionMeta, _root=True): """Union type; Union[X, Y] means either X or Y. To define a union, use e.g. Union[int, str]. Details: - The arguments must be types and there must be at least one. - None as an argument is a special case and is replaced by type(None). - Unions of unions are flattened, e.g.:: Union[Union[int, str], float] == Union[int, str, float] - Unions of a single argument vanish, e.g.:: Union[int] == int # The constructor actually returns int - Redundant arguments are skipped, e.g.:: Union[int, str, int] == Union[int, str] - When comparing unions, the argument order is ignored, e.g.:: Union[int, str] == Union[str, int] - When two arguments have a subclass relationship, the least derived argument is kept, e.g.:: class Employee: pass class Manager(Employee): pass Union[int, Employee, Manager] == Union[int, Employee] Union[Manager, int, Employee] == Union[int, Employee] Union[Employee, Manager] == Employee - Corollary: if Any is present it is the sole survivor, e.g.:: Union[int, Any] == Any - Similar for object:: Union[int, object] == object - To cut a tie: Union[object, Any] == Union[Any, object] == Any. - You cannot subclass or instantiate a union. - You cannot write Union[X][Y] (what would it mean?). - You can use Optional[X] as a shorthand for Union[X, None]. """ # Unsubscripted Union type has params set to None. __union_params__ = None __union_set_params__ = None class OptionalMeta(TypingMeta): """Metaclass for Optional.""" def __new__(cls, name, bases, namespace, _root=False): return super().__new__(cls, name, bases, namespace, _root=_root) def __getitem__(self, arg): arg = _type_check(arg, "Optional[t] requires a single type.") return Union[arg, type(None)] class Optional(Final, metaclass=OptionalMeta, _root=True): """Optional type. Optional[X] is equivalent to Union[X, type(None)]. """ __slots__ = () class TupleMeta(TypingMeta): """Metaclass for Tuple.""" def __new__(cls, name, bases, namespace, parameters=None, use_ellipsis=False, _root=False): self = super().__new__(cls, name, bases, namespace, _root=_root) self.__tuple_params__ = parameters self.__tuple_use_ellipsis__ = use_ellipsis return self def _has_type_var(self): if self.__tuple_params__: for t in self.__tuple_params__: if _has_type_var(t): return True return False def _eval_type(self, globalns, localns): tp = self.__tuple_params__ if tp is None: return self p = tuple(_eval_type(t, globalns, localns) for t in tp) if p == self.__tuple_params__: return self else: return self.__class__(self.__name__, self.__bases__, {}, p, _root=True) def __repr__(self): r = super().__repr__() if self.__tuple_params__ is not None: params = [_type_repr(p) for p in self.__tuple_params__] if self.__tuple_use_ellipsis__: params.append('...') r += '[%s]' % ( ', '.join(params)) return r def __getitem__(self, parameters): if self.__tuple_params__ is not None: raise TypeError("Cannot re-parameterize %r" % (self,)) if not isinstance(parameters, tuple): parameters = (parameters,) if len(parameters) == 2 and parameters[1] == Ellipsis: parameters = parameters[:1] use_ellipsis = True msg = "Tuple[t, ...]: t must be a type." else: use_ellipsis = False msg = "Tuple[t0, t1, ...]: each t must be a type." parameters = tuple(_type_check(p, msg) for p in parameters) return self.__class__(self.__name__, self.__bases__, dict(self.__dict__), parameters, use_ellipsis=use_ellipsis, _root=True) def __eq__(self, other): if not isinstance(other, TupleMeta): return NotImplemented return self.__tuple_params__ == other.__tuple_params__ def __hash__(self): return hash(self.__tuple_params__) def __instancecheck__(self, obj): raise TypeError("Tuples cannot be used with isinstance().") def __subclasscheck__(self, cls): if cls is Any: return True if not isinstance(cls, type): return super().__subclasscheck__(cls) # To TypeError. if issubclass(cls, tuple): return True # Special case. if not isinstance(cls, TupleMeta): return super().__subclasscheck__(cls) # False. if self.__tuple_params__ is None: return True if cls.__tuple_params__ is None: return False # ??? if cls.__tuple_use_ellipsis__ != self.__tuple_use_ellipsis__: return False # Covariance. return (len(self.__tuple_params__) == len(cls.__tuple_params__) and all(issubclass(x, p) for x, p in zip(cls.__tuple_params__, self.__tuple_params__))) class Tuple(Final, metaclass=TupleMeta, _root=True): """Tuple type; Tuple[X, Y] is the cross-product type of X and Y. Example: Tuple[T1, T2] is a tuple of two elements corresponding to type variables T1 and T2. Tuple[int, float, str] is a tuple of an int, a float and a string. To specify a variable-length tuple of homogeneous type, use Sequence[T]. """ __slots__ = () class CallableMeta(TypingMeta): """Metaclass for Callable.""" def __new__(cls, name, bases, namespace, _root=False, args=None, result=None): if args is None and result is None: pass # Must be 'class Callable'. else: if args is not Ellipsis: if not isinstance(args, list): raise TypeError("Callable[args, result]: " "args must be a list." " Got %.100r." % (args,)) msg = "Callable[[arg, ...], result]: each arg must be a type." args = tuple(_type_check(arg, msg) for arg in args) msg = "Callable[args, result]: result must be a type." result = _type_check(result, msg) self = super().__new__(cls, name, bases, namespace, _root=_root) self.__args__ = args self.__result__ = result return self def _has_type_var(self): if self.__args__: for t in self.__args__: if _has_type_var(t): return True return _has_type_var(self.__result__) def _eval_type(self, globalns, localns): if self.__args__ is None and self.__result__ is None: return self if self.__args__ is Ellipsis: args = self.__args__ else: args = [_eval_type(t, globalns, localns) for t in self.__args__] result = _eval_type(self.__result__, globalns, localns) if args == self.__args__ and result == self.__result__: return self else: return self.__class__(self.__name__, self.__bases__, {}, args=args, result=result, _root=True) def __repr__(self): r = super().__repr__() if self.__args__ is not None or self.__result__ is not None: if self.__args__ is Ellipsis: args_r = '...' else: args_r = '[%s]' % ', '.join(_type_repr(t) for t in self.__args__) r += '[%s, %s]' % (args_r, _type_repr(self.__result__)) return r def __getitem__(self, parameters): if self.__args__ is not None or self.__result__ is not None: raise TypeError("This Callable type is already parameterized.") if not isinstance(parameters, tuple) or len(parameters) != 2: raise TypeError( "Callable must be used as Callable[[arg, ...], result].") args, result = parameters return self.__class__(self.__name__, self.__bases__, dict(self.__dict__), _root=True, args=args, result=result) def __eq__(self, other): if not isinstance(other, CallableMeta): return NotImplemented return (self.__args__ == other.__args__ and self.__result__ == other.__result__) def __hash__(self): return hash(self.__args__) ^ hash(self.__result__) def __instancecheck__(self, obj): # For unparametrized Callable we allow this, because # typing.Callable should be equivalent to # collections.abc.Callable. if self.__args__ is None and self.__result__ is None: return isinstance(obj, collections_abc.Callable) else: raise TypeError("Callable[] cannot be used with isinstance().") def __subclasscheck__(self, cls): if cls is Any: return True if not isinstance(cls, CallableMeta): return super().__subclasscheck__(cls) if self.__args__ is None and self.__result__ is None: return True # We're not doing covariance or contravariance -- this is *invariance*. return self == cls class Callable(Final, metaclass=CallableMeta, _root=True): """Callable type; Callable[[int], str] is a function of (int) -> str. The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list must be a list of types; the return type must be a single type. There is no syntax to indicate optional or keyword arguments, such function types are rarely used as callback types. """ __slots__ = () def _gorg(a): """Return the farthest origin of a generic class.""" assert isinstance(a, GenericMeta) while a.__origin__ is not None: a = a.__origin__ return a def _geqv(a, b): """Return whether two generic classes are equivalent. The intention is to consider generic class X and any of its parameterized forms (X[T], X[int], etc.) as equivalent. However, X is not equivalent to a subclass of X. The relation is reflexive, symmetric and transitive. """ assert isinstance(a, GenericMeta) and isinstance(b, GenericMeta) # Reduce each to its origin. return _gorg(a) is _gorg(b) class GenericMeta(TypingMeta, abc.ABCMeta): """Metaclass for generic types.""" # TODO: Constrain more how Generic is used; only a few # standard patterns should be allowed. # TODO: Use a more precise rule than matching __name__ to decide # whether two classes are the same. Also, save the formal # parameters. (These things are related! A solution lies in # using origin.) __extra__ = None def __new__(cls, name, bases, namespace, parameters=None, origin=None, extra=None): if parameters is None: # Extract parameters from direct base classes. Only # direct bases are considered and only those that are # themselves generic, and parameterized with type # variables. Don't use bases like Any, Union, Tuple, # Callable or type variables. params = None for base in bases: if isinstance(base, TypingMeta): if not isinstance(base, GenericMeta): raise TypeError( "You cannot inherit from magic class %s" % repr(base)) if base.__parameters__ is None: continue # The base is unparameterized. for bp in base.__parameters__: if _has_type_var(bp) and not isinstance(bp, TypeVar): raise TypeError( "Cannot inherit from a generic class " "parameterized with " "non-type-variable %s" % bp) if params is None: params = [] if bp not in params: params.append(bp) if params is not None: parameters = tuple(params) self = super().__new__(cls, name, bases, namespace, _root=True) self.__parameters__ = parameters if extra is not None: self.__extra__ = extra # Else __extra__ is inherited, eventually from the # (meta-)class default above. self.__origin__ = origin return self def _has_type_var(self): if self.__parameters__: for t in self.__parameters__: if _has_type_var(t): return True return False def __repr__(self): r = super().__repr__() if self.__parameters__ is not None: r += '[%s]' % ( ', '.join(_type_repr(p) for p in self.__parameters__)) return r def __eq__(self, other): if not isinstance(other, GenericMeta): return NotImplemented return (_geqv(self, other) and self.__parameters__ == other.__parameters__) def __hash__(self): return hash((self.__name__, self.__parameters__)) def __getitem__(self, params): if not isinstance(params, tuple): params = (params,) if not params: raise TypeError("Cannot have empty parameter list") msg = "Parameters to generic types must be types." params = tuple(_type_check(p, msg) for p in params) if self.__parameters__ is None: for p in params: if not isinstance(p, TypeVar): raise TypeError("Initial parameters must be " "type variables; got %s" % p) if len(set(params)) != len(params): raise TypeError( "All type variables in Generic[...] must be distinct.") else: if len(params) != len(self.__parameters__): raise TypeError("Cannot change parameter count from %d to %d" % (len(self.__parameters__), len(params))) for new, old in zip(params, self.__parameters__): if isinstance(old, TypeVar): if not old.__constraints__: # Substituting for an unconstrained TypeVar is OK. continue if issubclass(new, Union[old.__constraints__]): # Specializing a constrained type variable is OK. continue if not issubclass(new, old): raise TypeError( "Cannot substitute %s for %s in %s" % (_type_repr(new), _type_repr(old), self)) return self.__class__(self.__name__, (self,) + self.__bases__, dict(self.__dict__), parameters=params, origin=self, extra=self.__extra__) def __instancecheck__(self, instance): # Since we extend ABC.__subclasscheck__ and # ABC.__instancecheck__ inlines the cache checking done by the # latter, we must extend __instancecheck__ too. For simplicity # we just skip the cache check -- instance checks for generic # classes are supposed to be rare anyways. return self.__subclasscheck__(instance.__class__) def __subclasscheck__(self, cls): if cls is Any: return True if isinstance(cls, GenericMeta): # For a class C(Generic[T]) where T is co-variant, # C[X] is a subclass of C[Y] iff X is a subclass of Y. origin = self.__origin__ if origin is not None and origin is cls.__origin__: assert len(self.__parameters__) == len(origin.__parameters__) assert len(cls.__parameters__) == len(origin.__parameters__) for p_self, p_cls, p_origin in zip(self.__parameters__, cls.__parameters__, origin.__parameters__): if isinstance(p_origin, TypeVar): if p_origin.__covariant__: # Covariant -- p_cls must be a subclass of p_self. if not issubclass(p_cls, p_self): break elif p_origin.__contravariant__: # Contravariant. I think it's the opposite. :-) if not issubclass(p_self, p_cls): break else: # Invariant -- p_cls and p_self must equal. if p_self != p_cls: break else: # If the origin's parameter is not a typevar, # insist on invariance. if p_self != p_cls: break else: return True # If we break out of the loop, the superclass gets a chance. if super().__subclasscheck__(cls): return True if self.__extra__ is None or isinstance(cls, GenericMeta): return False return issubclass(cls, self.__extra__) class Generic(metaclass=GenericMeta): """Abstract base class for generic types. A generic type is typically declared by inheriting from an instantiation of this class with one or more type variables. For example, a generic mapping type might be defined as:: class Mapping(Generic[KT, VT]): def __getitem__(self, key: KT) -> VT: ... # Etc. This class can then be used as follows:: def lookup_name(mapping: Mapping, key: KT, default: VT) -> VT: try: return mapping[key] except KeyError: return default For clarity the type variables may be redefined, e.g.:: X = TypeVar('X') Y = TypeVar('Y') def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y: # Same body as above. """ __slots__ = () def __new__(cls, *args, **kwds): next_in_mro = object # Look for the last occurrence of Generic or Generic[...]. for i, c in enumerate(cls.__mro__[:-1]): if isinstance(c, GenericMeta) and _gorg(c) is Generic: next_in_mro = cls.__mro__[i+1] return next_in_mro.__new__(_gorg(cls)) def cast(typ, val): """Cast a value to a type. This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don't check anything (we want this to be as fast as possible). """ return val def _get_defaults(func): """Internal helper to extract the default arguments, by name.""" code = func.__code__ pos_count = code.co_argcount kw_count = code.co_kwonlyargcount arg_names = code.co_varnames kwarg_names = arg_names[pos_count:pos_count + kw_count] arg_names = arg_names[:pos_count] defaults = func.__defaults__ or () kwdefaults = func.__kwdefaults__ res = dict(kwdefaults) if kwdefaults else {} pos_offset = pos_count - len(defaults) for name, value in zip(arg_names[pos_offset:], defaults): assert name not in res res[name] = value return res def get_type_hints(obj, globalns=None, localns=None): """Return type hints for a function or method object. This is often the same as obj.__annotations__, but it handles forward references encoded as string literals, and if necessary adds Optional[t] if a default value equal to None is set. BEWARE -- the behavior of globalns and localns is counterintuitive (unless you are familiar with how eval() and exec() work). The search order is locals first, then globals. - If no dict arguments are passed, an attempt is made to use the globals from obj, and these are also used as the locals. If the object does not appear to have globals, an exception is raised. - If one dict argument is passed, it is used for both globals and locals. - If two dict arguments are passed, they specify globals and locals, respectively. """ if getattr(obj, '__no_type_check__', None): return {} if globalns is None: globalns = getattr(obj, '__globals__', {}) if localns is None: localns = globalns elif localns is None: localns = globalns defaults = _get_defaults(obj) hints = dict(obj.__annotations__) for name, value in hints.items(): if isinstance(value, str): value = _ForwardRef(value) value = _eval_type(value, globalns, localns) if name in defaults and defaults[name] is None: value = Optional[value] hints[name] = value return hints # TODO: Also support this as a class decorator. def no_type_check(arg): """Decorator to indicate that annotations are not type hints. The argument must be a class or function; if it is a class, it applies recursively to all methods defined in that class (but not to methods defined in its superclasses or subclasses). This mutates the function(s) in place. """ if isinstance(arg, type): for obj in arg.__dict__.values(): if isinstance(obj, types.FunctionType): obj.__no_type_check__ = True else: arg.__no_type_check__ = True return arg def no_type_check_decorator(decorator): """Decorator to give another decorator the @no_type_check effect. This wraps the decorator with something that wraps the decorated function in @no_type_check. """ @functools.wraps(decorator) def wrapped_decorator(*args, **kwds): func = decorator(*args, **kwds) func = no_type_check(func) return func return wrapped_decorator def overload(func): raise RuntimeError("Overloading is only supported in library stubs") class _ProtocolMeta(GenericMeta): """Internal metaclass for _Protocol. This exists so _Protocol classes can be generic without deriving from Generic. """ def __instancecheck__(self, obj): raise TypeError("Protocols cannot be used with isinstance().") def __subclasscheck__(self, cls): if not self._is_protocol: # No structural checks since this isn't a protocol. return NotImplemented if self is _Protocol: # Every class is a subclass of the empty protocol. return True # Find all attributes defined in the protocol. attrs = self._get_protocol_attrs() for attr in attrs: if not any(attr in d.__dict__ for d in cls.__mro__): return False return True def _get_protocol_attrs(self): # Get all Protocol base classes. protocol_bases = [] for c in self.__mro__: if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol': protocol_bases.append(c) # Get attributes included in protocol. attrs = set() for base in protocol_bases: for attr in base.__dict__.keys(): # Include attributes not defined in any non-protocol bases. for c in self.__mro__: if (c is not base and attr in c.__dict__ and not getattr(c, '_is_protocol', False)): break else: if (not attr.startswith('_abc_') and attr != '__abstractmethods__' and attr != '_is_protocol' and attr != '__dict__' and attr != '__slots__' and attr != '_get_protocol_attrs' and attr != '__parameters__' and attr != '__origin__' and attr != '__module__'): attrs.add(attr) return attrs class _Protocol(metaclass=_ProtocolMeta): """Internal base class for protocol classes. This implements a simple-minded structural isinstance check (similar but more general than the one-offs in collections.abc such as Hashable). """ __slots__ = () _is_protocol = True # Various ABCs mimicking those in collections.abc. # A few are simply re-exported for completeness. Hashable = collections_abc.Hashable # Not generic. class Iterable(Generic[T_co], extra=collections_abc.Iterable): __slots__ = () class Iterator(Iterable[T_co], extra=collections_abc.Iterator): __slots__ = () class SupportsInt(_Protocol): __slots__ = () @abstractmethod def __int__(self) -> int: pass class SupportsFloat(_Protocol): __slots__ = () @abstractmethod def __float__(self) -> float: pass class SupportsComplex(_Protocol): __slots__ = () @abstractmethod def __complex__(self) -> complex: pass class SupportsBytes(_Protocol): __slots__ = () @abstractmethod def __bytes__(self) -> bytes: pass class SupportsAbs(_Protocol[T_co]): __slots__ = () @abstractmethod def __abs__(self) -> T_co: pass class SupportsRound(_Protocol[T_co]): __slots__ = () @abstractmethod def __round__(self, ndigits: int = 0) -> T_co: pass class Reversible(_Protocol[T_co]): __slots__ = () @abstractmethod def __reversed__(self) -> 'Iterator[T_co]': pass Sized = collections_abc.Sized # Not generic. class Container(Generic[T_co], extra=collections_abc.Container): __slots__ = () # Callable was defined earlier. class AbstractSet(Sized, Iterable[T_co], Container[T_co], extra=collections_abc.Set): pass class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet): pass # NOTE: Only the value type is covariant. class Mapping(Sized, Iterable[KT], Container[KT], Generic[VT_co], extra=collections_abc.Mapping): pass class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping): pass class Sequence(Sized, Iterable[T_co], Container[T_co], extra=collections_abc.Sequence): pass class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence): pass class ByteString(Sequence[int], extra=collections_abc.ByteString): pass ByteString.register(type(memoryview(b''))) class List(list, MutableSequence[T]): def __new__(cls, *args, **kwds): if _geqv(cls, List): raise TypeError("Type List cannot be instantiated; " "use list() instead") return list.__new__(cls, *args, **kwds) class Set(set, MutableSet[T]): def __new__(cls, *args, **kwds): if _geqv(cls, Set): raise TypeError("Type Set cannot be instantiated; " "use set() instead") return set.__new__(cls, *args, **kwds) class _FrozenSetMeta(GenericMeta): """This metaclass ensures set is not a subclass of FrozenSet. Without this metaclass, set would be considered a subclass of FrozenSet, because FrozenSet.__extra__ is collections.abc.Set, and set is a subclass of that. """ def __subclasscheck__(self, cls): if issubclass(cls, Set): return False return super().__subclasscheck__(cls) class FrozenSet(frozenset, AbstractSet[T_co], metaclass=_FrozenSetMeta): __slots__ = () def __new__(cls, *args, **kwds): if _geqv(cls, FrozenSet): raise TypeError("Type FrozenSet cannot be instantiated; " "use frozenset() instead") return frozenset.__new__(cls, *args, **kwds) class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView): pass class KeysView(MappingView[KT], AbstractSet[KT], extra=collections_abc.KeysView): pass # TODO: Enable Set[Tuple[KT, VT_co]] instead of Generic[KT, VT_co]. class ItemsView(MappingView, Generic[KT, VT_co], extra=collections_abc.ItemsView): pass class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView): pass class Dict(dict, MutableMapping[KT, VT]): def __new__(cls, *args, **kwds): if _geqv(cls, Dict): raise TypeError("Type Dict cannot be instantiated; " "use dict() instead") return dict.__new__(cls, *args, **kwds) # Determine what base class to use for Generator. if hasattr(collections_abc, 'Generator'): # Sufficiently recent versions of 3.5 have a Generator ABC. _G_base = collections_abc.Generator else: # Fall back on the exact type. _G_base = types.GeneratorType class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co], extra=_G_base): __slots__ = () def __new__(cls, *args, **kwds): if _geqv(cls, Generator): raise TypeError("Type Generator cannot be instantiated; " "create a subclass instead") return super().__new__(cls, *args, **kwds) def NamedTuple(typename, fields): """Typed version of namedtuple. Usage:: Employee = typing.NamedTuple('Employee', [('name', str), 'id', int)]) This is equivalent to:: Employee = collections.namedtuple('Employee', ['name', 'id']) The resulting class has one extra attribute: _field_types, giving a dict mapping field names to types. (The field names are in the _fields attribute, which is part of the namedtuple API.) """ fields = [(n, t) for n, t in fields] cls = collections.namedtuple(typename, [n for n, t in fields]) cls._field_types = dict(fields) # Set the module to the caller's module (otherwise it'd be 'typing'). try: cls.__module__ = sys._getframe(1).f_globals.get('__name__', '__main__') except (AttributeError, ValueError): pass return cls class IO(Generic[AnyStr]): """Generic base class for TextIO and BinaryIO. This is an abstract, generic version of the return of open(). NOTE: This does not distinguish between the different possible classes (text vs. binary, read vs. write vs. read/write, append-only, unbuffered). The TextIO and BinaryIO subclasses below capture the distinctions between text vs. binary, which is pervasive in the interface; however we currently do not offer a way to track the other distinctions in the type system. """ __slots__ = () @abstractproperty def mode(self) -> str: pass @abstractproperty def name(self) -> str: pass @abstractmethod def close(self) -> None: pass @abstractmethod def closed(self) -> bool: pass @abstractmethod def fileno(self) -> int: pass @abstractmethod def flush(self) -> None: pass @abstractmethod def isatty(self) -> bool: pass @abstractmethod def read(self, n: int = -1) -> AnyStr: pass @abstractmethod def readable(self) -> bool: pass @abstractmethod def readline(self, limit: int = -1) -> AnyStr: pass @abstractmethod def readlines(self, hint: int = -1) -> List[AnyStr]: pass @abstractmethod def seek(self, offset: int, whence: int = 0) -> int: pass @abstractmethod def seekable(self) -> bool: pass @abstractmethod def tell(self) -> int: pass @abstractmethod def truncate(self, size: int = None) -> int: pass @abstractmethod def writable(self) -> bool: pass @abstractmethod def write(self, s: AnyStr) -> int: pass @abstractmethod def writelines(self, lines: List[AnyStr]) -> None: pass @abstractmethod def __enter__(self) -> 'IO[AnyStr]': pass @abstractmethod def __exit__(self, type, value, traceback) -> None: pass class BinaryIO(IO[bytes]): """Typed version of the return of open() in binary mode.""" __slots__ = () @abstractmethod def write(self, s: Union[bytes, bytearray]) -> int: pass @abstractmethod def __enter__(self) -> 'BinaryIO': pass class TextIO(IO[str]): """Typed version of the return of open() in text mode.""" __slots__ = () @abstractproperty def buffer(self) -> BinaryIO: pass @abstractproperty def encoding(self) -> str: pass @abstractproperty def errors(self) -> str: pass @abstractproperty def line_buffering(self) -> bool: pass @abstractproperty def newlines(self) -> Any: pass @abstractmethod def __enter__(self) -> 'TextIO': pass class io: """Wrapper namespace for IO generic classes.""" __all__ = ['IO', 'TextIO', 'BinaryIO'] IO = IO TextIO = TextIO BinaryIO = BinaryIO io.__name__ = __name__ + '.io' sys.modules[io.__name__] = io Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')), lambda p: p.pattern) Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')), lambda m: m.re.pattern) class re: """Wrapper namespace for re type aliases.""" __all__ = ['Pattern', 'Match'] Pattern = Pattern Match = Match re.__name__ = __name__ + '.re' sys.modules[re.__name__] = re
53,772
Python
.py
1,290
32.113178
79
0.582873
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,192
explore_panel.py
DamnWidget_anaconda/anaconda_lib/explore_panel.py
# Copyright (C) 2013 ~ 2016 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details import sublime from ._typing import List from Default.history_list import get_jump_history_for_view class ExplorerPanel: """ Creates a panel that can be used to explore nested options sets The data structure for the options is as follows: Options[ { 'title': 'Title Data' 'details': 'Details Data', 'location': 'File: {} Line: {} Column: {}', 'position': 'filepath:line:col', 'options': [ { 'title': 'Title Data' 'details': 'Details Data', 'location': 'File: {} Line: {} Column: {}', 'position': 'filepath:line:col', 'options': [ ]... } ] } ] So we can nest as many levels as we want """ def __init__(self, view: sublime.View, options: List) -> None: self.options = options self.view = view self.selected = [] # type: List self.restore_point = view.sel()[0] def show(self, cluster: List, forced: bool=False) -> None: """Show the quick panel with the given options """ if not cluster: cluster = self.options if len(cluster) == 1 and not forced: try: Jumper(self.view, cluster[0]['position']).jump() except KeyError: if len(cluster[0].get('options', [])) == 1 and not forced: Jumper( self.view, cluster[0]['options'][0]['position']).jump() return self.last_cluster = cluster quick_panel_options = [] for data in cluster: tmp = [data['title']] if 'details' in data: tmp.append(data['details']) if 'location' in data: tmp.append(data['location']) quick_panel_options.append(tmp) self.view.window().show_quick_panel( quick_panel_options, on_select=self.on_select, on_highlight=lambda index: self.on_select(index, True) ) def on_select(self, index: int, transient: bool=False) -> None: """Called when an option is been made in the quick panel """ if index == -1: self._restore_view() return cluster = self.last_cluster node = cluster[index] if transient and 'options' in node: return if 'options' in node: self.prev_cluster = self.last_cluster opts = node['options'][:] opts.insert(0, {'title': '<- Go Back', 'position': 'back'}) sublime.set_timeout(lambda: self.show(opts), 0) else: if node['position'] == 'back' and not transient: sublime.set_timeout(lambda: self.show(self.prev_cluster), 0) elif node['position'] != 'back': Jumper(self.view, node['position']).jump(transient) def _restore_view(self): """Restore the view and location """ sublime.active_window().focus_view(self.view) self.view.show(self.restore_point) if self.view.sel()[0] != self.restore_point: self.view.sel().clear() self.view.sel().add(self.restore_point) class Jumper: """Jump to the specified file line and column making an indicator to toggle """ def __init__(self, view: sublime.View, position: str) -> None: self.position = position self.view = view def jump(self, transient: bool=False) -> None: """Jump to the selection """ flags = sublime.ENCODED_POSITION if transient is True: flags |= sublime.TRANSIENT get_jump_history_for_view(self.view).push_selection(self.view) sublime.active_window().open_file(self.position, flags) if not transient: self._toggle_indicator() def _toggle_indicator(self) -> None: """Toggle mark indicator to focus the cursor """ path, line, column = self.position.rsplit(':', 2) pt = self.view.text_point(int(line) - 1, int(column)) region_name = 'anaconda.indicator.{}.{}'.format( self.view.id(), line ) for i in range(3): delta = 300 * i * 2 sublime.set_timeout(lambda: self.view.add_regions( region_name, [sublime.Region(pt, pt)], 'comment', 'bookmark', sublime.DRAW_EMPTY_AS_OVERWRITE ), delta) sublime.set_timeout( lambda: self.view.erase_regions(region_name), delta + 300 )
4,970
Python
.py
126
27.698413
79
0.531782
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,193
worker.py
DamnWidget_anaconda/anaconda_lib/worker.py
# Copyright (C) 2013 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details """Maintain this just for compatibility """ from .workers.market import Market as Worker # from .store import WorkerStore as Worker __all__ = ['Worker']
285
Python
.py
7
39.142857
65
0.762774
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,194
persistent_list.py
DamnWidget_anaconda/anaconda_lib/persistent_list.py
# -*- coding: utf8 -*- # Copyright (C) 2013 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details """Just a persistent list """ import os import pickle import logging class PersistentList(list): """Just a persistent list """ _file_path = os.path.join( os.path.dirname(__file__), os.pardir, '.disabled_views') def __init__(self): super(PersistentList, self).__init__() try: with open(self._file_path, 'rb') as fileobj: self.load(fileobj) except IOError: pass except Exception as e: logging.error( 'Detected error {}, deleting persistent list...'.format(e)) os.remove(self._file_path) def __setitem__(self, key, value): super(PersistentList, self).__setitem__(key, value) self.sync() def __delitem__(self, key): super(PersistentList, self).__delitem__(key) self.sync() def append(self, value): super(PersistentList, self).append(value) self.sync() def remove(self, value): super(PersistentList, self).remove(value) self.sync() def pop(self, index=None): if index is not None: value = super(PersistentList, self).pop(index) else: value = super(PersistentList, self).pop() self.sync() return value def sort(self, **kwargs): super(PersistentList, self).sort(**kwargs) self.sync() def load(self, fileobj): """Load the pickle contents """ return self.extend(pickle.load(fileobj)) def sync(self): """Write bytes and str elements of the list to the disk """ with open(self._file_path, 'wb') as fileobj: l = [i for i in list(self) if type(i) is str or type(i) is bytes] return pickle.dump(l, fileobj, 2)
1,948
Python
.py
56
26.607143
77
0.592176
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,195
jediusages.py
DamnWidget_anaconda/anaconda_lib/jediusages.py
# Copyright (C) 2013 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details """Common jedi class to work with Jedi functions """ import sublime from functools import partial from ._typing import Union, Dict class JediUsages(object): """Work with Jedi definitions """ def __init__(self, text): self.text = text def process(self, usages: bool=False, data: Dict =None) -> None: """Process the definitions """ view = self.text.view if not data['success']: sublime.status_message('Unable to find {}'.format( view.substr(view.word(view.sel()[0]))) ) return definitions = data['goto'] if not usages else data['usages'] if len(definitions) == 0: sublime.status_message('Unable to find {}'.format( view.substr(view.word(view.sel()[0]))) ) return if definitions is not None and len(definitions) == 1 and not usages: self._jump(*definitions[0]) else: self._show_options(definitions, usages) def _jump(self, filename: Union[int, str], lineno: int =None, columno: int =None, transient: bool =False) -> None: """Jump to a window """ # process jumps from options window if type(filename) is int: if filename == -1: # restore view view = self.text.view point = self.point sublime.active_window().focus_view(view) view.show(point) if view.sel()[0] != point: view.sel().clear() view.sel().add(point) return opts = self.options[filename] if len(self.options[filename]) == 4: opts = opts[1:] filename, lineno, columno = opts flags = sublime.ENCODED_POSITION if transient: flags |= sublime.TRANSIENT sublime.active_window().open_file( '{}:{}:{}'.format(filename, lineno or 0, columno or 0), flags ) self._toggle_indicator(lineno, columno) def _show_options(self, defs: Union[str, Dict], usages: bool) -> None: """Show a dropdown quickpanel with options to jump """ view = self.text.view if usages or (not usages and type(defs) is not str): if len(defs) == 4: options = [[ o[0], o[1], 'line: {} column: {}'.format(o[2], o[3]) ] for o in defs] else: options = [[ o[0], 'line: {} column: {}'.format(o[1], o[2]) ] for o in defs] else: if len(defs): options = defs[0] else: sublime.status_message('Unable to find {}'.format( view.substr(view.word(view.sel()[0]))) ) return self.options = defs self.point = self.text.view.sel()[0] self.text.view.window().show_quick_panel( options, self._jump, on_highlight=partial(self._jump, transient=True) ) def _toggle_indicator(self, lineno: int =0, columno: int =0) -> None: """Toggle mark indicator for focus the cursor """ pt = self.text.view.text_point(lineno - 1, columno) region_name = 'anaconda.indicator.{}.{}'.format( self.text.view.id(), lineno ) for i in range(3): delta = 300 * i * 2 sublime.set_timeout(lambda: self.text.view.add_regions( region_name, [sublime.Region(pt, pt)], 'comment', 'bookmark', sublime.DRAW_EMPTY_AS_OVERWRITE ), delta) sublime.set_timeout( lambda: self.text.view.erase_regions(region_name), delta + 300 )
4,045
Python
.py
106
26.40566
76
0.521339
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,196
constants.py
DamnWidget_anaconda/anaconda_lib/constants.py
# Copyright (C) 2013 - 2016 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details from ..anaconda_lib import aenum as enum class WorkerStatus(enum.Enum): """Worker status unique enumeration """ incomplete = 0 healthy = 1 faulty = 2 quiting = 3
325
Python
.py
10
28.6
72
0.712903
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,197
ioloop.py
DamnWidget_anaconda/anaconda_lib/ioloop.py
# -*- coding: utf8 -*- # Copyright (C) 2013 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details """ Minimalist asynchronous network library just to fit Anaconda's needs and replace the horrible asyncore/asynchat Example of usage: import ioloop class TestClient(ioloop.EventHandler): '''Client for test ''' def __init__(self, host, port): ioloop.EventHandler.__init__(self, (host, port)) self.message = [] def ready_to_write(self): return True if self.outbuffer else False def handle_read(self, data): self.message.append(data) def process_message(self): print(b''.join(self.message)) self.message = [] """ import os import sys import time import errno import socket import select import logging import traceback import threading from ._typing import List, Tuple, Any # noqa NOT_TERMINATE = True class IOHandlers(object): """Class that register and unregister IOHandler """ _shared_state = {} # type: Dict[Any, Any] def __init__(self) -> None: self.__dict__ = IOHandlers._shared_state if hasattr(self, 'instanced') and self.instanced is True: return self._handler_pool = {} # type: Dict[int, EventHandler] self._lock = threading.Lock() self.instanced = True # type: bool def ready_to_read(self) -> List['EventHandler']: """Return back all the handlers that are ready to read """ return [h for h in self._handler_pool.values() if h.ready_to_read()] def ready_to_write(self): """Return back all the handlers that are ready to write """ return [h for h in self._handler_pool.values() if h.ready_to_write()] def register(self, handler): """Register a new handler """ logging.info( 'Registering handler with address {}'.format(handler.address)) with self._lock: if handler.fileno() not in self._handler_pool: self._handler_pool.update({handler.fileno(): handler}) def unregister(self, handler): """Unregister the given handler """ with self._lock: if handler.fileno() in self._handler_pool: self._handler_pool.pop(handler.fileno()) class EventHandler(object): """Event handler class """ def __init__(self, address: Tuple[str, int], sock: socket.socket=None) -> None: # noqa self._write_lock = threading.RLock() self._read_lock = threading.RLock() self.address = address self.outbuffer = b'' self.inbuffer = b'' self.sock = sock if sock is None: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect(address) self.connected = True self.sock.setblocking(False) IOHandlers().register(self) def __del__(self) -> None: if self in IOHandlers()._handler_pool.values(): IOHandlers().unregister(self) def fileno(self) -> int: """Return the associated file descriptor """ return self.sock.fileno() def send(self) -> int: """Send outgoing data """ with self._write_lock: while len(self.outbuffer) > 0: try: sent = self.sock.send(self.outbuffer) self.outbuffer = self.outbuffer[sent:] except socket.error as error: if error.args[0] == errno.EAGAIN: time.sleep(0.1) elif error.args[0] in ( errno.ECONNRESET, errno.ENOTCONN, errno.ESHUTDOWN, errno.ECONNABORTED, errno.EPIPE ): self.close() return 0 elif os.name == 'posix': # Windows doesn't seems to have EBADFD if sys.platform == 'darwin': # OS X uses EBADF as EBADFD. why? no idea asks Tim if error.args[0] == errno.EBADF: self.close() return 0 else: if error.args[0] == errno.EBADFD: self.close() return 0 raise else: raise def recv(self) -> None: """Receive some data """ try: data = self.sock.recv(4096) except socket.error as error: if error.args[0] in (errno.EWOULDBLOCK, errno.EAGAIN): return None elif error.args[0] == errno.ECONNRESET: self.close() return None else: raise if not data: self.close() return None self.inbuffer += data while self.inbuffer: match = b'\r\n' index = self.inbuffer.find(match) if index != -1: if index > 0: self.handle_read(self.inbuffer[:index]) self.inbuffer = self.inbuffer[index+len(match):] self.process_message() else: index = len(match) - 1 while index and not self.inbuffer.endswith(match[:index]): index -= 1 if index: if index != len(self.inbuffer): self.handle_read(self.inbuffer[:-index]) self.inbuffer = self.inbuffer[-index:] break else: self.handle_read(self.inbuffer) self.inbuffer = b'' def push(self, data: bytes) -> None: """Push some bytes into the write buffer """ self.outbuffer += data def handle_read(self, data: bytes) -> None: """Handle data readign from select """ raise RuntimeError('You have to implement this method') def process_message(self) -> None: """Process the full message """ raise RuntimeError('You have to implement this method') def ready_to_read(self) -> bool: """This handler is ready to read """ return True def ready_to_write(self) -> bool: """This handler is ready to write """ return True def close(self) -> None: """Close the socket and unregister the handler """ if self in IOHandlers()._handler_pool.values(): IOHandlers().unregister(self) self.sock.close() self.connected = False def poll() -> None: """Poll the select """ recv = send = [] # type: List[bytes] try: if os.name != 'posix': if IOHandlers()._handler_pool: recv, send, _ = select.select( IOHandlers().ready_to_read(), IOHandlers().ready_to_write(), [], 0 ) else: recv, send, _ = select.select( IOHandlers().ready_to_read(), IOHandlers().ready_to_write(), [], 0 ) except select.error: err = sys.exc_info()[1] if err.args[0] == errno.EINTR: return raise for handler in recv: if handler is None or handler.ready_to_read() is not True: continue handler.recv() for handler in send: if handler is None or handler.ready_to_write() is not True: continue handler.send() def loop() -> None: """Main event loop """ def restart_poll(error: Exception) -> None: logging.error( 'Unhandled exception in poll, restarting the poll request') logging.error(error) for traceback_line in traceback.format_exc().splitlines(): logging.error(traceback_line) with IOHandlers()._lock: for handler in IOHandlers()._handler_pool.values(): handler.close() IOHandlers()._handler_pool = {} def inner_loop() -> None: while NOT_TERMINATE: try: poll() time.sleep(0.01) except OSError as error: if os.name != 'posix' and error.errno == os.errno.WSAENOTSOCK: msg = ( 'Unfortunately, the Windows socket is in inconsistent' ' state, restart your sublime text 3. If the problem ' 'persist, fill an issue report on:' ' https://github.com/DamnWidget/anaconda/issues' ) logging.error(msg) import sublime sublime.error_message(msg) terminate() else: restart_poll(error) except Exception as error: restart_poll(error) # cleanup for handler in IOHandlers()._handler_pool.values(): handler.close() threading.Thread(target=inner_loop).start() def terminate() -> None: """Terminate the loop """ global NOT_TERMINATE NOT_TERMINATE = False def restart() -> None: """Restart the loop """ global NOT_TERMINATE if NOT_TERMINATE is True: NOT_TERMINATE = False terminate() NOT_TERMINATE = True loop()
9,619
Python
.py
266
24.620301
91
0.531314
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,198
kite.py
DamnWidget_anaconda/anaconda_lib/kite.py
import sublime class Integration: """Checks if Kite integration is turned on """ @classmethod def enabled(cls): """Returns True if Kite integration is enabled """ globalsettings = sublime.load_settings('Preferences.sublime-settings') settings = sublime.load_settings('AnacondaKite.sublime-settings') enabled = settings.get('integrate_with_kite', False) not_ignored = 'Kite' not in globalsettings.get('ignored_packages') if enabled and not_ignored: try: from Kite.lib.installer import check from Kite.lib.exceptions import KiteNotSupported if not check.is_running(): return False except ImportError: return False except KiteNotSupported: # Kite will raise KiteNotSupported on Linux return True return True return False @classmethod def enable(cls): """Enable Kite integration """ settings = sublime.load_settings('AnacondaKite.sublime-settings') settings.set('integrate_with_kite', True) settings.save_settings('AnacondaKite.sublime-settings') @classmethod def disable(cls): """Disable Kite integration """ settings = sublime.load_settings('AnacondaKite.sublime-settings') settings.set('integrate_with_kite', False) settings.save_settings('AnacondaKite.sublime-settings')
1,521
Python
.py
39
29.025641
78
0.631793
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
28,199
callback.py
DamnWidget_anaconda/anaconda_lib/callback.py
# -*- coding: utf8 -*- # Copyright (C) 2014 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details """Minimalist Callbacks implementation based on @NorthIsUp pull request """ import sys import uuid import logging from threading import RLock from functools import partial import sublime from ..anaconda_lib import aenum as enum from ._typing import Callable, Any, Union logger = logging.getLogger(__name__) logger.addHandler(logging.StreamHandler(sys.stdout)) logger.setLevel(logging.DEBUG) @enum.unique class CallbackStatus(enum.Enum): """Callback status unique enumeration """ unfired = 'unfired' succeeded = 'succeeded' failed = 'failed' timed_out = 'timed_out' class Callback(object): """This class implements an error safe non retriable callbacks mechanism Instances of this class can be passed as callbacks to Anaconda's asynchronous client methods. You can pass callback methods for success, error or timeout using the constructor parameters `on_success`, `on_failure` and `on_timeout` or you can just call the `on` method. Take into account that if the timeout value is set to 0 (or less), the timeout callback will never be called. .. note:: A callback object can be called only once, try to call it more than once should result in a RuntimeError raising """ def __init__(self, on_success: Callable=None, on_failure: Callable=None, on_timeout: Callable=None, timeout: Union[int, float]=0) -> None: # noqa self._lock = RLock() self._timeout = 0 # type: Union[int, float] self.uid = uuid.uuid4() # type: uuid.UUID self.waiting_for_timeout = False self._status = CallbackStatus.unfired # type: enum.Enum self.callbacks = {'succeeded': on_success, 'failed': on_failure} # type: Dict[str, Callable] # noqa if on_timeout is not None and callable(on_timeout): self.callbacks['timed_out'] = on_timeout self.timeout = timeout if on_timeout is not None and timeout > 0: self.initialize_timeout() def __call__(self, *args: Any, **kwargs: Any) -> Any: """This is called directly form the JSONClient when receive a message """ with self._lock: self._infere_status_from_data(*args, **kwargs) return self._fire_callback(*args, **kwargs) @property def id(self) -> uuid.UUID: """Return back the callback id """ return self.uid @property def hexid(self) -> str: """Return back the callback hexadecimal id """ return self.uid.hex @property def timeout(self): """Return back the callback timeout """ return self._timeout @timeout.setter def timeout(self, value: Union[int, float]) -> None: """Set the timeout, take sure its an interger or float value """ if not isinstance(value, (int, float)): raise RuntimeError('Callback.timeout must be integer or float!') self._timeout = value @property def status(self) -> enum.Enum: """Return the callback status """ return self.status @status.setter def status(self, status: CallbackStatus) -> None: """Set the callback status, it can be set only once. This function is Thread Safe :param status: it can be a CallbackStatus property or an string with one of the valid status values; succeeded, failed, timed_out """ with self._lock: if self._status != CallbackStatus.unfired: if self._status != CallbackStatus.timed_out: raise RuntimeError( 'Callback {} already fired!'.format(self.hexid) ) else: logger.info( 'Calback {} came back with data but it\'s status ' 'was `timed_out` already'.format(self.hexid) ) return if isinstance(status, CallbackStatus): self._status = status else: status = CallbackStatus._member_map_.get(status) if status is not None: self._status = status else: raise RuntimeError( 'Status {} does not exists!'.format(status) ) def initialize_timeout(self) -> None: """Initialize the timeouts if any """ def _timeout_callback(*args: Any, **kwargs: Any) -> None: """Defualt timeout callback dummy method, can be overriden """ raise RuntimeError('Timeout occurred on {}'.format(self.hexid)) def _on_timeout(func: Callable, *args: Any, **kwargs: Any) -> None: """We need this wrapper to don't call timeout by accident """ if self._status is CallbackStatus.unfired: self.status = CallbackStatus.timed_out func(*args, **kwargs) if self.timeout > 0: self.waiting_for_timeout = True callback = self.callbacks.get('timed_out', _timeout_callback) sublime.set_timeout( partial(_on_timeout, callback), self.timeout * 1000 ) def on(self, success: Callable=None, error: Callable=None, timeout: Callable=None) -> None: # noqa """Another (more semantic) way to initialize the callback object """ if success is not None and self.callbacks.get('succeeded') is None: self.callbacks['succeeded'] = success if error is not None and self.callbacks.get('failed') is None: self.callbacks['failed'] = error if timeout is not None and self.callbacks.get('timed_out') is None: if callable(timeout): self.callbacks['timed_out'] = timeout self.initialize_timeout() def _infere_status_from_data(self, *args: Any, **kwargs: Any) -> None: """ Set the status based on extracting a code from the callback data. Supports two protocols checked in the followin order: 1) data = {'status': 'succeeded|failed|timed_out'} 2) data = {'success': True|False} <- back compatibility """ data = kwargs.get('data') or args[0] if args else {} if 'status' in data: self.status = data['status'] elif 'success' in data: smap = {True: 'succeeded', False: 'failed'} self.status = smap[data['success']] else: self.status = 'succeeded' # almost safe, trust me def _fire_callback(self, *args: Any, **kwargs: Any) -> Any: """Fire the right calback based on the status """ def _panic(*args: Any, **kwargs: Any) -> None: """Just called on panic situations """ if self.status is CallbackStatus.failed: callback = self.callbacks.get('succeeded') if callback is not None: return callback(*args, **kwargs) raise RuntimeError( 'We tried to call non existing callback {}!'.format( self.status.value ) ) callback = self.callbacks.get(self._status.value, _panic) return callback and callback(*args, **kwargs)
7,520
Python
.py
172
33.610465
150
0.599781
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)