mail_deduplicate packageΒΆ
Expose package-wide elements.
- mail_deduplicate.HASH_HEADERS: tuple[str, ...] = ('Date', 'From', 'To', 'Subject', 'MIME-Version', 'Content-Type', 'Content-Disposition', 'User-Agent', 'X-Priority', 'Message-ID')ΒΆ
Default ordered list of headers to use to compute the unique hash of a mail.
By default we choose to exclude:
CCSince
mailmanapparently sometimes trims list members from theCCheader to avoid sending duplicates. Which means that copies of mail reflected back from the list server will have a differentCCto the copy saved by the MUA at send-time.BCCBecause copies of the mail saved by the MUA at send-time will have
BCC, but copies reflected back from the list server wonβt.Reply-ToSince a mail could be
CCβd to two lists with differentReply-Tomunging options set.
- mail_deduplicate.ADDRESS_HEADERS = frozenset({'bcc', 'cc', 'delivered-to', 'disposition-notification-to', 'envelope-to', 'from', 'original-recipient', 'reply-to', 'resent-bcc', 'resent-cc', 'resent-from', 'resent-reply-to', 'resent-sender', 'resent-to', 'return-path', 'sender', 'to', 'x-envelope-from', 'x-envelope-to', 'x-original-to'})ΒΆ
Headers that contain email addresses.
Danger
These IDs should be kept lower-case, because they are compared to the one provided to those provided to the
-h/--hash-headeroption, that is carried by thehash_headersproperty of the configuration.
- mail_deduplicate.QUOTE_DISCARD_HEADERS = frozenset({'bcc', 'cc', 'delivered-to', 'disposition-notification-to', 'envelope-to', 'from', 'original-recipient', 'reply-to', 'resent-bcc', 'resent-cc', 'resent-from', 'resent-reply-to', 'resent-sender', 'resent-to', 'return-path', 'sender', 'to', 'x-envelope-from', 'x-envelope-to', 'x-original-to'})ΒΆ
Headers from which quotes should be discarded.
E.g.
"Bob" <bob@example.com>should hash to the same thing asBob <bob@example.com>.
- mail_deduplicate.MINIMAL_HEADERS_COUNT = 4ΒΆ
Below this value, we consider not having enough headers to compute a solid hash.
- mail_deduplicate.DEFAULT_SIZE_THRESHOLD = 512ΒΆ
Default size threshold in bytes.
Since weβre ignoring the
Content-Lengthheader by default because of mailing-list effects, we introduced a limit on the allowed difference between the sizes of the message payloads.If this is exceeded, a warning is issued and the messages are not considered duplicates, because this could point to message corruption somewhere, or a false positive.
Note
Headers are not counted towards this threshold, because many headers can be added by mailing list software such as
mailman, or even by the process of sending the mail through various MTAs.One copy could have been stored by the senderβs MUA prior to sending, without any
Receivedheaders, and another copy could be reflected back via aCC-to-self mechanism or mailing list server.This threshold has to be large enough to allow for footers added by mailing list servers.
- mail_deduplicate.DEFAULT_CONTENT_THRESHOLD = 768ΒΆ
Default content threshold in bytes.
As above, we similarly generates unified diffs of duplicates and ensure that the diff is not greater than a certain size to limit false-positives.
- exception mail_deduplicate.TooFewHeaders[source]ΒΆ
Bases:
ExceptionNot enough headers were found to produce a solid hash.
- exception mail_deduplicate.SizeDiffAboveThreshold[source]ΒΆ
Bases:
ExceptionDifference in mail size is greater than threshold..
- exception mail_deduplicate.ContentDiffAboveThreshold[source]ΒΆ
Bases:
ExceptionDifference in mail content is greater than threshold..
SubmodulesΒΆ
mail_deduplicate.action moduleΒΆ
- mail_deduplicate.action.copy_mails(dedup, mails)[source]ΒΆ
Copy provided
mailsto a brand new box or an existing one.- Return type:
- mail_deduplicate.action.move_mails(dedup, mails)[source]ΒΆ
Move provided
mailsto a brand new box or an existing one.- Return type:
- mail_deduplicate.action.delete_mails(dedup, mails)[source]ΒΆ
Remove provided
mailsin-place, from their original boxes.- Return type:
- mail_deduplicate.action.copy_selected(dedup)[source]ΒΆ
Copy all selected mails to a brand new box.
- Return type:
- mail_deduplicate.action.copy_discarded(dedup)[source]ΒΆ
Copy all discarded mails to a brand new box.
- Return type:
- mail_deduplicate.action.move_selected(dedup)[source]ΒΆ
Move all selected mails to a brand new box.
- Return type:
- mail_deduplicate.action.move_discarded(dedup)[source]ΒΆ
Move all discarded mails to a brand new box.
- Return type:
- mail_deduplicate.action.delete_selected(dedup)[source]ΒΆ
Remove in-place all selected mails, from their original boxes.
- Return type:
- mail_deduplicate.action.delete_discarded(dedup)[source]ΒΆ
Remove in-place all discarded mails, from their original boxes.
- Return type:
- class mail_deduplicate.action.Action(*values)[source]ΒΆ
Bases:
EnumDefine all available action IDs.
- COPY_SELECTED = 'copy-selected'ΒΆ
- COPY_DISCARDED = 'copy-discarded'ΒΆ
- MOVE_SELECTED = 'move-selected'ΒΆ
- MOVE_DISCARDED = 'move-discarded'ΒΆ
- DELETE_SELECTED = 'delete-selected'ΒΆ
- DELETE_DISCARDED = 'delete-discarded'ΒΆ
mail_deduplicate.cli moduleΒΆ
- class mail_deduplicate.cli.Config[source]ΒΆ
Bases:
TypedDictHolds global configuration.
- input_format: BoxFormat | NoneΒΆ
- force_unlock: boolΒΆ
- hash_headers: tuple[str, ...]ΒΆ
- hash_body: BodyHasherΒΆ
- hash_only: boolΒΆ
- size_threshold: intΒΆ
- content_threshold: intΒΆ
- show_diff: boolΒΆ
- strategy: str | NoneΒΆ
- time_source: TimeSourceΒΆ
- regexp: re.Pattern | NoneΒΆ
- action: ActionΒΆ
- export: Path | NoneΒΆ
- export_format: BoxFormatΒΆ
- export_append: boolΒΆ
- dry_run: boolΒΆ
- mail_deduplicate.cli.normalize_headers(ctx, param, value)[source]ΒΆ
Validate headers provided as parameters to the CLI.
Headers are case-insensitive in Python implementation, so we normalize them to lower-case.
We then deduplicate them, while preserving order.
Mail headers are expected to be composed of ASCII characters between 33 and 126 (both inclusive) according to RFC-5322.
- mail_deduplicate.cli.compile_regexp(ctx, param, value)[source]ΒΆ
Validate and compile regular expression provided as parameters to the CLI.
- class mail_deduplicate.cli.MdedupCommand(*args, version=None, extra_option_at_end=True, populate_auto_envvars=True, **kwargs)[source]ΒΆ
Bases:
ExtraCommandList of extra parameters:
- Parameters:
version (
str|None) β allows a version string to be set directly on the command. Will be passed to the first instance ofExtraVersionOptionparameter attached to the command.extra_option_at_end (
bool) β reorders all parameters attached to the command, by moving all instances ofExtraOptionat the end of the parameter list. The original order of the options is preserved among themselves.populate_auto_envvars (
bool) β forces all parameters to have their auto-generated environment variables registered. This address the shortcoming ofclickwhich only evaluates them dynamiccaly. By forcing their registration, the auto-generated environment variables gets displayed in the help screen, fixing click#2483 issue. On Windows, environment variable names are case-insensitive, so we normalize them to uppercase.
By default, these Click context settings are applied:
auto_envvar_prefix = self.name(Click feature)Auto-generate environment variables for all options, using the command ID as prefix. The prefix is normalized to be uppercased and all non-alphanumerics replaced by underscores.
help_option_names = ("--help", "-h")(Click feature)Allow help screen to be invoked with either βhelp or -h options.
show_default = True(Click feature)Show all default values in help screen.
Additionally, these Cloup context settings are set:
align_option_groups = False(Cloup feature)show_constraints = True(Cloup feature)show_subcommand_aliases = True(Cloup feature)
Click Extra also adds its own
context_settings:show_choices = None(Click Extra feature)If set to
TrueorFalse, will force that value on all options, so we can globally show or hide choices when prompting a user for input. Only makes sense for options whosepromptproperty is set.Defaults to
None, which will leave all options untouched, and let them decide of their ownshow_choicessetting.show_envvar = None(Click Extra feature)If set to
TrueorFalse, will force that value on all options, so we can globally enable or disable the display of environment variables in help screen.Defaults to
None, which will leave all options untouched, and let them decide of their ownshow_envvarsetting. The rationale being that discoverability of environment variables is enabled by the--show-paramsoption, which is active by default on extra commands. So there is no need to surcharge the help screen.This addresses the click#2313 issue.
To override these defaults, you can pass your own settings with the
context_settingsparameter:@extra_command( context_settings={ "show_default": False, ... } )
mail_deduplicate.deduplicate moduleΒΆ
- mail_deduplicate.deduplicate.STATS_DEF = {'mail_copied': 'Number of mails copied from their original mailbox to another.', 'mail_deleted': 'Number of mails deleted from their mailbox in-place.', 'mail_discarded': 'Number of mails discarded from the final selection.', 'mail_duplicates': 'Number of duplicate mails (sum of mails in all duplicate sets with at least 2 mails).', 'mail_found': 'Total number of mails encountered from all mail sources.', 'mail_hashes': 'Number of unique hashes.', 'mail_moved': 'Number of mails moved from their original mailbox to another.', 'mail_rejected': 'Number of mails rejected individually because they were unparsable or did not have enough metadata to compute hashes.', 'mail_retained': 'Number of valid mails parsed and retained for deduplication.', 'mail_selected': 'Number of mails kept in the final selection on which the action will be performed.', 'mail_skipped': 'Number of mails ignored in the selection step because the whole set they belong to was skipped.', 'mail_unique': 'Number of unique mails (which where automatically added to selection).', 'set_deduplicated': 'Number of valid sets on which the selection strategy was successfully applied.', 'set_single': 'Total number of sets containing only a single mail with no applicable strategy. They were automatically kept in the final selection.', 'set_skipped_content': 'Number of sets skipped from the selection process because they were too dissimilar in content.', 'set_skipped_encoding': 'Number of sets skipped from the selection process because they had encoding issues.', 'set_skipped_size': 'Number of sets skipped from the selection process because they were too dissimilar in size.', 'set_skipped_strategy': 'Number of sets skipped from the selection process because the strategy could not be applied.', 'set_total': 'Total number of duplicate sets.'}ΒΆ
All tracked statistics and their definition.
- class mail_deduplicate.deduplicate.BodyHasher(*values)[source]ΒΆ
Bases:
EnumEnumeration of available body hashing methods.
- SKIP = 'skip'ΒΆ
- RAW = 'raw'ΒΆ
- NORMALIZED = 'normalized'ΒΆ
- class mail_deduplicate.deduplicate.DuplicateSet(hash_key, mail_set, conf)[source]ΒΆ
Bases:
objectA set of mails sharing the same hash.
Implements all the safety checks required before we can apply any selection strategy.
Load-up the duplicate set of mail and freeze pool.
Once loaded-up, the pool of parsed mails is considered frozen for the rest of the duplicate setβs life. This allows aggressive caching of lazy instance attributes depending on the pool content.
- property newest_timestampΒΆ
Returns the newest timestamp among all mails in the set.
- property oldest_timestampΒΆ
Returns the oldest timestamp among all mails in the set.
- property biggest_sizeΒΆ
Returns the biggest size among all mails in the set.
- property smallest_sizeΒΆ
Returns the smallest size among all mails in the set.
- check_differences()[source]ΒΆ
Ensures all mail differs in the limits imposed by size and content thresholds.
Compare all mails of the duplicate set with each other, both in size and content. Raise an error if weβre not within the limits imposed by the threshold settings.
- diff(mail_a, mail_b)[source]ΒΆ
Return difference in bytes between two mailsβ normalized body.
Todo
Rewrite the diff algorithm to not rely on naive unified diff result parsing.
- class mail_deduplicate.deduplicate.Deduplicate(conf)[source]ΒΆ
Bases:
objectLoad-up messages, search for duplicates, apply selection strategy and perform the action.
Similar messages sharing the same hash are grouped together in a
DuplicateSet.- add_source(source_path)[source]ΒΆ
Registers a source of mails, validates and opens it.
Duplicate sources of mails are not allowed, as when we perform the action, we use the path as a unique key to tie back a mail from its source.
- Return type:
- hash_all()[source]ΒΆ
Browse all mails from all registered sources, compute hashes and group mails by hash.
Displays a progress bar as the operation might be slow.
- build_sets()[source]ΒΆ
Build the selected and discarded sets from each duplicate set.
We apply the selection strategy one duplicate set at a time to keep memory footprint low and make the log easier to read.
- assert_stats(first, operator, second)[source]ΒΆ
Render failed stats assertions in plain English.
- ..hint ::
If inconsistent metrics are detected, the CLI will exit with a code numbered
115.This has been arbitrarily chosen in PR #842, to make it unlikely to conflict with other exit codes. Users can rely on
115meaning that the statistics checks failed.
mail_deduplicate.mail moduleΒΆ
- class mail_deduplicate.mail.TimeSource(*values)[source]ΒΆ
Bases:
EnumEnumeration of all supported mail timestamp sources.
- DATE_HEADER = 'date-header'ΒΆ
Timestamp sourced from the messageβs
Dateheader.
- CTIME = 'ctime'ΒΆ
Timestamp is from the emailβs file on the filesystem.
Attention
Only available for
maildirsources.
- class mail_deduplicate.mail.DedupMail(message)[source]ΒΆ
Bases:
objectMessage with deduplication-specific properties and utilities.
Extends standard libraryβs mailbox.Message, and shouldnβt be used directly, but composed with
mailbox.Messagesub-classes.Initialize a pre-parsed
Messageinstance the same way the default factory in Pythonβsmailboxmodule does.- add_box_metadata(box, mail_id)[source]ΒΆ
Post-instantiation utility to attach to mail some metadata derived from its parent box.
Called right after the
__init__()constructor.This allows the mail to carry its own information on its origin box and index.
- Return type:
- property timestamp: float | NoneΒΆ
Compute the normalized canonical timestamp of the mail.
Sourced from the messageβs
Dateheader by default. In the case ofmaildir, can be sourced from the emailβs file from the filesystem.Warning
ctimedoes not refer to creation time on POSIX systems, but rather the last time the inode data changed.Todo
Investigate what mailbox.MaildirMessage.get_date() does and if we can use it.
- property size: intΒΆ
Returns canonical mail size.
Size is computed as the length of the message body, i.e. the payload of the mail stripped of all its headers, not from the mail file persisting on the file- system.
Todo
Allow customization of the way the size is computed, by getting the file size instead for example:
`python size = os.path.getsize(mail_file) `
- hash_key()[source]ΒΆ
Returns the canonical hash of a mail.
Caution
This method hasnβt been made explicitly into a cached property in order to reduce the overall memory footprint.
- Return type:
- property canonical_headers: tuple[tuple[str, str], ...]ΒΆ
Returns the full list of all canonical headers names and values in preparation for hashing.
- pretty_canonical_headers()[source]ΒΆ
Renders a table of headers names and values used to produce the mailβs hash.
Caution
This method hasnβt been made explicitly into a cached property in order to reduce the overall memory footprint.
Returns a string ready to be printed.
- Return type:
- serialized_headers()[source]ΒΆ
Serialize the canonical headers into a single string ready to be hashed.
At this point we should have at an absolute minimum of headers.
Caution
This method hasnβt been made explicitly into a cached property in order to reduce the overall memory footprint.
- Return type:
mail_deduplicate.mail_box moduleΒΆ
Utilities to read and write mail boxes in various formats.
Based on Pythonβs standard library mailbox module.
- class mail_deduplicate.mail_box.BoxStructure(*values)[source]ΒΆ
Bases:
EnumBox structures can be file-based or folder-based.
- FOLDER = 1ΒΆ
- FILE = 2ΒΆ
- class mail_deduplicate.mail_box.BoxFormat(base_class, structure)[source]ΒΆ
Bases:
EnumIDs of all the supported box formats and their metadata.
Each entry is associated to their original base class, and the structure they implement (file-based or folder-based).
From these, we can derive the proper constructor with our own custom
DedupMailfactory.Hint
This could be extended in the future to add support for other mailbox formats and sources, like Gmail accounts, IMAP servers, etc.
- MAILDIR = (<class 'mailbox.Maildir'>, BoxStructure.FOLDER)ΒΆ
- MBOX = (<class 'mailbox.mbox'>, BoxStructure.FILE)ΒΆ
- MH = (<class 'mailbox.MH'>, BoxStructure.FOLDER)ΒΆ
- BABYL = (<class 'mailbox.Babyl'>, BoxStructure.FILE)ΒΆ
- MMDF = (<class 'mailbox.MMDF'>, BoxStructure.FILE)ΒΆ
- property constructorΒΆ
Wrap a subclass of
mailbox.Messagewith our ownDedupMailclass.
- mail_deduplicate.mail_box.FOLDER_FORMATS = (BoxFormat.MAILDIR, BoxFormat.MH)ΒΆ
Box formats implementing a folder-based structure.
Is a tuple to keep natural order defined by
BoxFormat.
- mail_deduplicate.mail_box.FILE_FORMATS = (BoxFormat.MBOX, BoxFormat.BABYL, BoxFormat.MMDF)ΒΆ
Box formats implementing a file-based structure.
Is a tuple to keep natural order defined by
BoxFormat.
- mail_deduplicate.mail_box.MAILDIR_SUBDIRS = frozenset({'cur', 'new', 'tmp'})ΒΆ
List of required sub-folders defining a properly structured maildir.
- mail_deduplicate.mail_box.autodetect_box_type(path)[source]ΒΆ
Auto-detect the format of the mailbox located at the provided path.
Returns a box type as indexed in the BOX_TYPES dictionary above.
If the path is a file, then it is considered as an
mbox. Else, if the provided path is a folder and feature the expecteed sub-directories, it is parsed as amaildir.Todo
Future finer autodetection heuristics should be implemented here. Some ideas:
single mail from a
maildirplain text mail content
other mailbox formats supported in Pythonβs standard library:
MHBabylMMDF
- Return type:
- mail_deduplicate.mail_box.open_box(path, box_format=None, force_unlock=False)[source]ΒΆ
Open a mail box.
Returns a list of boxes, one per sub-folder. All are locked, ready for operations.
If
box_formatis provided, forces the opening of the box in the specified format. Else, defaults to autodetection.
- mail_deduplicate.mail_box.lock_box(box, force_unlock)[source]ΒΆ
Lock an opened box and allows for forced unlocking.
Returns the locked box.
- Return type:
mail_deduplicate.strategy moduleΒΆ
Strategy definitions.
- mail_deduplicate.strategy.select_older(duplicates)[source]ΒΆ
Select all older duplicates.
Discards the newests, i.e. the subset sharing the most recent timestamp.
- mail_deduplicate.strategy.select_oldest(duplicates)[source]ΒΆ
Select all the oldest duplicates.
Discards the newers, i.e. all mail of the duplicate set but those sharing the oldest timestamp.
- mail_deduplicate.strategy.select_newer(duplicates)[source]ΒΆ
Select all newer duplicates.
Discards the oldest, i.e. the subset sharing the most ancient timestamp.
- mail_deduplicate.strategy.select_newest(duplicates)[source]ΒΆ
Select all the newest duplicates.
Discards the olders, i.e. all mail of the duplicate set but those sharing the newest timestamp.
- mail_deduplicate.strategy.select_smaller(duplicates)[source]ΒΆ
Select all smaller duplicates.
Discards the biggests, i.e. the subset sharing the biggest size.
- mail_deduplicate.strategy.select_smallest(duplicates)[source]ΒΆ
Select all the smallest duplicates.
Discards the biggers. i.e. all mail of the duplicate set but those sharing the smallest size.
- mail_deduplicate.strategy.select_bigger(duplicates)[source]ΒΆ
Select all bigger duplicates.
Discards the smallests, i.e. the subset sharing the smallest size.
- mail_deduplicate.strategy.select_biggest(duplicates)[source]ΒΆ
Select all the biggest duplicates.
Discards the smallers, i.e. all mail of the duplicate set but those sharing the biggest size.
- mail_deduplicate.strategy.select_matching_path(duplicates)[source]ΒΆ
Select all duplicates whose file path match the regular expression provided via the βregexp parameter.
- mail_deduplicate.strategy.select_non_matching_path(duplicates)[source]ΒΆ
Select all duplicates whose file path doesnβt match the regular expression provided via the βregexp parameter.
- mail_deduplicate.strategy.select_one(duplicates)[source]ΒΆ
Randomly select one duplicate, and discards all others.
- mail_deduplicate.strategy.select_all_but_one(duplicates)[source]ΒΆ
Randomly discard one duplicate, and select all others.
- mail_deduplicate.strategy.SELECT_NEWEST = 'select-newest'ΒΆ
Time-based strategies.
- mail_deduplicate.strategy.SELECT_BIGGEST = 'select-biggest'ΒΆ
Size-based strategies.
- mail_deduplicate.strategy.SELECT_NON_MATCHING_PATH = 'select-non-matching-path'ΒΆ
Location-based strategies.
- mail_deduplicate.strategy.SELECT_ALL_BUT_ONE = 'select-all-but-one'ΒΆ
Quantity-based strategies.
- mail_deduplicate.strategy.STRATEGY_ALIASES = frozenset({('select-all-but-one', 'discard-one'), ('select-bigger', 'discard-smallest'), ('select-biggest', 'discard-smaller'), ('select-matching-path', 'discard-non-matching-path'), ('select-newer', 'discard-oldest'), ('select-newest', 'discard-older'), ('select-non-matching-path', 'discard-matching-path'), ('select-older', 'discard-newest'), ('select-oldest', 'discard-newer'), ('select-one', 'discard-all-but-one'), ('select-smaller', 'discard-biggest'), ('select-smallest', 'discard-bigger')})ΒΆ
Groups strategy aliases and their definitions.
Aliases are great usability features as it helps users to better reason about the selection operators depending on their mental models.
- mail_deduplicate.strategy.get_method_id(strategy_id)[source]ΒΆ
Transform strategy ID to its method ID.