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:

CC

Since mailman apparently sometimes trims list members from the CC header to avoid sending duplicates. Which means that copies of mail reflected back from the list server will have a different CC to the copy saved by the MUA at send-time.

BCC

Because 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-To

Since a mail could be CC’d to two lists with different Reply-To munging 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-header narrows the hash to fewer headers than this cap.

class mail_deduplicate.cli.Preset(*values)[source]¶

Bases: StrEnum

Named sets of option values, each a starting point for a run.

A preset is an alias of the options PRESET_OPTIONS lists 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-ID header 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: see DEPENDENT_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-ID alone, 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-headers hashes every header, so a --hash-header list 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-headers and --hash-body raw do 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:

str

mail_deduplicate.cli.preset_words(preset)[source]¶

The options a preset stands for, as typed on the command line.

Return type:

str

class mail_deduplicate.cli.Config[source]¶

Bases: TypedDict

Holds global configuration.

input_format: BoxFormat | None¶
force_unlock: bool¶
raw_headers: bool¶
hash_headers: tuple[str, ...]¶
minimal_headers: int¶
hash_body: BodyHasher¶
hash_only: bool¶
cache: bool¶
cache_path: Path | None¶
size_threshold: int¶
content_threshold: int¶
show_diff: bool¶
strategies: tuple[Strategy, ...]¶
time_source: TimeSource¶
regexps: tuple[Pattern[str], ...]¶
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 one or more ASCII characters between 33 and 126 (both inclusive) according to RFC-5322.

Return type:

tuple[str, ...]

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.

Return type:

tuple[Strategy, ...]

class mail_deduplicate.cli.RegexpType[source]¶

Bases: ParamType

A regular expression on the path of a mail, compiled as soon as it is read.

name: str = 'regexp'¶

the descriptive name of this type

envvar_list_splitter: ClassVar[str | None] = '\n'¶

Separator of the expressions in an environment variable.

Click splits the variable of a repeatable option on whitespace by default, and an expression can hold spaces.

convert(value, param, ctx)[source]¶

Compile value, or refuse it with a usage error.

A configuration file can give a number, like a year. A string option reads it as text, and so does this type.

Return type:

Pattern[str]

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.

Return type:

tuple[Pattern[str], ...]

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/--regexp parameter.

mail_deduplicate.cli.EXPORT_ACTIONS = (Action.COPY_SELECTED, Action.COPY_DISCARDED, Action.MOVE_SELECTED, Action.MOVE_DISCARDED)¶

Actions relying on the -E/--export parameter.

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.

Parameters:

title (str) – the step’s name, after the bullet.

Return type:

None

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:

str

class mail_deduplicate.cli.AnyValueIn(param_name, targets, label, negate=False)[source]¶

Bases: Predicate

Condition 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=True tuples are normalized to a common shape. Set negate to invert the membership test: true when none of the values is in the target set.

Whatever negate says, 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-only mode: selection and action steps never run there, so options they require (like --export for the default copy-selected action) must not be demanded. Options from those steps are separately reported as ignored by the hash-only code path.

description(ctx)[source]¶

Succinct description of the predicate (alias: desc).

Return type:

str

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: Command

The mdedup command, with a help screen that lists every strategy.

Todo

Drop the ("py:meth", "invoke") entry of nitpick_ignore in docs/conf.py once a click-extra release newer than 10.4.0 qualifies the cross-references of the Command.__init__ docstring. Autodoc appends that docstring here, and its bare invoke target 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, like https://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. See invoke().

  • version_fields (dict[str, Any] | None) – dictionary of VersionOption template field overrides forwarded to the version option. Accepts any field from VersionOption.template_fields (like prog_name, version, git_branch). Lets you customize --version output from the command decorator without replacing the default params list.

  • config_strict (bool) – forwarded to the default ConfigOption’s strict setting: configuration keys not matching any CLI parameter raise an error instead of being silently ignored. Like the other config_* and *_params forwards, it spares you from replacing the whole default params list to customize the config option.

  • config_cascade (bool) – forwarded to the default ConfigOption’s cascade setting: 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 default ConfigOption’s excluded_params blocklist. Additive, unlike the option-level excluded_params which replaces the default blocklist entirely. Items are fully-qualified parameter IDs (like mycli.mail_sources). Mutually exclusive with included_params.

  • extra_keywords (HelpKeywords | None) – a HelpKeywords instance whose entries are merged into the auto-collected keyword set. Use this to inject additional strings for help screen highlighting.

  • excluded_keywords (HelpKeywords | None) – a HelpKeywords instance 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 an Examples: section of the help screen, in the man page, and in every –help-format rendering. A malformed pair raises TypeError here, at command construction, rather than on the first --help a user runs.

  • extra_option_at_end (bool) – reorders all parameters attached to the command, by moving all instances of ExtraOption at 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 to DEFAULT_PRIORITY, lowest shown first. Keys are matched against each parameter’s long and short flags first, then its destination name, so the --config / --no-config pair (which shares the config destination) 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 of click which 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:

Additionally, these Cloup context settings are set:

Click Extra also adds its own context_settings:

  • show_choices = None (Click Extra feature)

    If set to True or False, 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 whose prompt property is set.

    Defaults to None, which will leave all options untouched, and let them decide of their own show_choices setting.

  • show_envvar = None (Click Extra feature)

    If set to True or False, 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 own show_envvar setting. The rationale being that discoverability of environment variables is enabled by the --params option, 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_settings parameter:

@command(
    context_settings={
        "show_default": False,
        ...
    }
)
format_help(ctx, formatter)[source]¶

Extend the help screen with the description of all available strategies.

Return type:

None

mail_deduplicate.cli.flag_names(param)[source]¶

Every spelling of an option, joined as the help screen lists them.

Return type:

str

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:

bool

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_OVERRIDES lists it. The options of a LINKED_OPTIONS group give way together. A value that relies on other values of the preset, as DEPENDENT_OPTIONS lists, gives way with any of them, and the run names the options that then keep their defaults.

Parameters:
  • ctx (Context) – the context of the run, holding the values of its parameters.

  • preset (Preset) – the preset to apply.

Return type:

dict[str, Any]

Returns:

the value of each option the preset sets, by parameter name.

mail_deduplicate.cli.ignored_step_options(ctx)[source]¶

User-provided options from the steps -H/--hash-only never runs.

Collects the options attached to the sections of steps after #2 whose value does not come from a default, so the run can report them as ignored.

Return type:

list[str]