mail_deduplicate.cli module¶
The mdedup command: its options, their validation and the run Config.
- mail_deduplicate.cli.DEFAULT_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.cli.DEFAULT_MINIMAL_HEADERS = 4¶
Cap on the number of headers that must be present in a mail to compute a solid hash.
The per-mail floor is
min(DEFAULT_MINIMAL_HEADERS, len(hash_headers)). A near-empty or corrupted mail whose hash would rest on too few headers gets no hash, and the run keeps it like a mail without duplicates. The floor relaxes automatically when--hash-headernarrows the hash to fewer headers than this cap.
- class mail_deduplicate.cli.Preset(*values)[source]¶
Bases:
StrEnumNamed sets of option values, each a starting point for a run.
A preset is an alias of the options
PRESET_OPTIONSlists for it.- CONSERVATIVE = 'conservative'¶
Treats as copies only the mails whose bytes are identical.
- DEFAULT = 'default'¶
Keeps the built-in defaults.
- AGGRESSIVE = 'aggressive'¶
Trusts the
Message-IDheader alone to group copies.
- mail_deduplicate.cli.PRESET_OPTIONS: dict[Preset, tuple[tuple[str, str | bool], ...]] = {Preset.AGGRESSIVE: (('--hash-header', 'Message-ID'),), Preset.CONSERVATIVE: (('--raw-headers', True), ('--hash-body', 'raw'), ('--size-threshold', '-1'), ('--content-threshold', '-1'), ('--strategy', 'select-one')), Preset.DEFAULT: ()}¶
The options each preset stands for, spelled as on the command line.
apply_preset()gives each of them its value, unless the user set that option. A value that relies on other values of the same preset applies only while all of them apply: seeDEPENDENT_OPTIONS.The conservative preset hashes the bytes of the whole mail, which only identical copies share. The thresholds then have nothing left to catch, and turning them off spares a second read of each mail. When the user replaces one of its two hashing options, copies that differ can share a hash, so the thresholds stay on. Identical copies are interchangeable, so the preset also keeps one of each.
The aggressive preset trusts
Message-IDalone, so the copies whose other headers a mailing list or a gateway rewrote still share a hash. The thresholds stay the only check against two mails that reuse an ID. Its copies can differ, so which one to keep stays the user’s choice.
- mail_deduplicate.cli.LINKED_OPTIONS: tuple[frozenset[str], ...] = (frozenset({'hash_headers', 'raw_headers'}),)¶
Options that make one choice between them, by their name.
--raw-headershashes every header, so a--hash-headerlist has nothing left to select. The user setting either option decides the headers, so a preset value for the other one gives way too.
- mail_deduplicate.cli.DEPENDENT_OPTIONS: dict[str, frozenset[str]] = {'content_threshold': frozenset({'hash_body', 'raw_headers'}), 'size_threshold': frozenset({'hash_body', 'raw_headers'})}¶
Options whose preset value relies on the preset values of others, by their name.
A preset value of such an option applies only while each option it relies on keeps the value of the same preset: the preset gives that value, or the user gives the same one. When one of them gives way, the option gives way too, and keeps its default or the user’s value. The rule ignores an option that the preset does not set.
The thresholds can stay off only while the hash covers every byte of a mail, which
--raw-headersand--hash-body rawdo together.
- mail_deduplicate.cli.QUIET_OVERRIDES = frozenset({'strategies'})¶
Options the user can set over a preset with no warning, by their name.
The strategy decides which copy stays, not what counts as a copy.
- mail_deduplicate.cli.preset_word(flag, value)[source]¶
One option of a preset, as typed on the command line.
- Return type:
- mail_deduplicate.cli.preset_words(preset)[source]¶
The options a preset stands for, as typed on the command line.
- Return type:
- class mail_deduplicate.cli.Config[source]¶
Bases:
TypedDictHolds global configuration.
- hash_body: BodyHasher¶
- time_source: TimeSource¶
- 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 one or more ASCII characters between 33 and 126 (both inclusive) according to RFC-5322.
- mail_deduplicate.cli.unique_strategies(ctx, param, value)[source]¶
Deduplicate strategies provided as parameters to the CLI, preserving order.
Strategies are deduplicated by the selection function they point to, so repeating a strategy already listed under one of its aliases is ignored too.
- class mail_deduplicate.cli.RegexpType[source]¶
Bases:
ParamTypeA regular expression on the path of a mail, compiled as soon as it is read.
- mail_deduplicate.cli.unique_regexps(ctx, param, value)[source]¶
Deduplicate the regular expressions provided to the CLI, preserving order.
A repeated expression cannot decide a set that its first occurrence left undecided. An empty expression matches every path, so it decides no set at all. Both are ignored, and an option left without expressions counts as not set.
- mail_deduplicate.cli.PATH_STRATEGIES = (Strategy.DISCARD_MATCHING_PATH, Strategy.DISCARD_NON_MATCHING_PATH, Strategy.SELECT_MATCHING_PATH, Strategy.SELECT_NON_MATCHING_PATH)¶
Strategies relying on the
-r/--regexpparameter.
- mail_deduplicate.cli.EXPORT_ACTIONS = (Action.COPY_SELECTED, Action.COPY_DISCARDED, Action.MOVE_SELECTED, Action.MOVE_DISCARDED)¶
Actions relying on the
-E/--exportparameter.
- mail_deduplicate.cli.echo_step(title)[source]¶
Print the heading of a pipeline step, after a blank line.
The blank line is printed on its own, outside the heading’s style. Styled as part of the heading, its escapes open the style on the line above the text, so any tool reading the output line by line (a pager,
grep, a capture cut with--head) finds a style open on a line that closes it nowhere.
- mail_deduplicate.cli.human_join(items)[source]¶
Renders IDs as an English enumeration, for the help screen.
The options mentioning the strategies and actions that take an extra parameter read them from the two tuples above, instead of spelling them out again and drifting from them.
- Return type:
- class mail_deduplicate.cli.AnyValueIn(param_name, targets, label, negate=False)[source]¶
Bases:
PredicateCondition that is true when any of a parameter’s values is in a target set.
The parameter’s resolved value is inspected, so defaults count, not only user-provided values. Single values and
multiple=Truetuples are normalized to a common shape. Setnegateto invert the membership test: true when none of the values is in the target set.Whatever
negatesays, the condition silently evaluates to false when no mail source is provided: the CLI then only prints its help screen and exits, so no parameter combination deserves a validation error.The same applies in
-H/--hash-onlymode: selection and action steps never run there, so options they require (like--exportfor the default copy-selected action) must not be demanded. Options from those steps are separately reported as ignored by the hash-only code path.
- class mail_deduplicate.cli.MdedupCommand(*args, report_url=None, version_fields=None, config_schema=None, config_strict=False, schema_strict=False, fallback_sections=(), config_validators=(), included_params=None, excluded_params=None, config_cascade=False, extra_option_at_end=True, option_priorities=None, populate_auto_envvars=True, extra_keywords=None, excluded_keywords=None, examples=(), **kwargs)[source]¶
Bases:
CommandThe
mdedupcommand, with a help screen that lists every strategy.Todo
Drop the
("py:meth", "invoke")entry ofnitpick_ignoreindocs/conf.pyonce a click-extra release newer than10.4.0qualifies the cross-references of theCommand.__init__docstring. Autodoc appends that docstring here, and its bareinvoketarget resolves against this module, where it does not exist.Like
cloup.Command.__init__, with Click Extra’s defaults and parameters.- Parameters:
report_url (
str|None) – URL of the issue form of the project, likehttps://github.com/orchard/harvest/issues/new. Set on the root command, an error that the CLI has no rule for then ends the run with a bug report linking to that form, instead of a bare traceback. Seeinvoke().version_fields (
dict[str,Any] |None) – dictionary ofVersionOptiontemplate field overrides forwarded to the version option. Accepts any field fromVersionOption.template_fields(likeprog_name,version,git_branch). Lets you customize--versionoutput from the command decorator without replacing the defaultparamslist.config_strict (
bool) – forwarded to the defaultConfigOption’sstrictsetting: configuration keys not matching any CLI parameter raise an error instead of being silently ignored. Like the otherconfig_*and*_paramsforwards, it spares you from replacing the whole defaultparamslist to customize the config option.config_cascade (
bool) – forwarded to the defaultConfigOption’scascadesetting: auto-discovery layers every configuration file it finds, the most local one winning on key lookup, instead of stopping at the first.excluded_params (
Sequence[str] |None) – additional parameter IDs to block from configuration files, merged into the defaultConfigOption’sexcluded_paramsblocklist. Additive, unlike the option-levelexcluded_paramswhich replaces the default blocklist entirely. Items are fully-qualified parameter IDs (likemycli.mail_sources). Mutually exclusive withincluded_params.extra_keywords (
HelpKeywords|None) – aHelpKeywordsinstance whose entries are merged into the auto-collected keyword set. Use this to inject additional strings for help screen highlighting.excluded_keywords (
HelpKeywords|None) – aHelpKeywordsinstance whose entries are removed from the auto-collected keyword set. Use this to suppress highlighting of specific strings.examples (
Sequence[Sequence[str]]) – a sequence of(description, command)string pairs showing the command in use. They are rendered in anExamples:section of the help screen, in the man page, and in every –help-format rendering. A malformed pair raisesTypeErrorhere, at command construction, rather than on the first--helpa user runs.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.option_priorities (
Mapping[str,float] |None) – maps an option to its priority in the help screen, relative toDEFAULT_PRIORITY, lowest shown first. Keys are matched against each parameter’s long and short flags first, then its destination name, so the--config/--no-configpair (which shares theconfigdestination) stays addressable one flag at a time. Presentation only:self.params, and with it the order callbacks are evaluated in, is left alone. Positional arguments are never reordered, their sequence being part of the command’s grammar.populate_auto_envvars (
bool) – forces all parameters to have their auto-generated environment variables registered. This addresses the shortcoming ofclickwhich only evaluates them dynamically. Once registered, the auto-generated environment variables get displayed in the help screen, fixing click#2483 issue. On Windows, environment variable names are case-insensitive, so they are normalized 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 = True(Cloup feature)Aligns option groups in help screen.
Every command carries the sections of
DEFAULT_OPTION_GROUPS, so leaving each to compute its own column width would step the help text left and right from one section to the next. Aligned, a command’s own options keep the column click-extra’s widest option sets, which is what thedefault_options_*_helpfixtures ofclick_extra.pytestmatch against.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--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:@command( context_settings={ "show_default": False, ... } )
- mail_deduplicate.cli.flag_names(param)[source]¶
Every spelling of an option, joined as the help screen lists them.
- Return type:
- mail_deduplicate.cli.user_set(ctx, name)[source]¶
Whether the user gave a parameter its value, from any source but its default.
A value from a configuration file or the environment counts as set.
- Return type:
- mail_deduplicate.cli.apply_preset(ctx, preset)[source]¶
The values a preset gives the options the user left at their default.
An option the user set keeps its value. The run warns about each one that overrides the preset with another value, unless
QUIET_OVERRIDESlists it. The options of aLINKED_OPTIONSgroup give way together. A value that relies on other values of the preset, asDEPENDENT_OPTIONSlists, gives way with any of them, and the run names the options that then keep their defaults.