notmuch-tagrewriter 0.1.0

Retag notmuch mails
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
use derive_more::derive::{AsMut, AsRef, Debug, Deref, DerefMut, Display, From, FromStr};
use itertools::{Either, Itertools};
use log::{debug, trace};
use serde::{Deserialize, Serialize};
use serde_with::{DeserializeFromStr, SerializeDisplay};
use std::{
    collections::{BTreeMap, BTreeSet},
    fmt::Display,
    str::FromStr,
};

use crate::{
    dnf::{BooleanLike, LitteralTrait, Sign, SignedLitteral},
    state::{EffectiveState, StateTrait},
};

/// A struct describing a tag.
///
/// This is just a wrapper around `String`.
#[derive(
    PartialEq,
    Eq,
    Clone,
    Hash,
    PartialOrd,
    Ord,
    Serialize,
    Deserialize,
    Deref,
    DerefMut,
    Display,
    From,
    FromStr,
    Debug,
)]
#[display("{_0}")]
#[debug("tag:{_0}")]
pub struct Tag(String);

impl LitteralTrait for Tag {}

/// A type representing whether a tag in present or absent
#[derive(Hash, PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
pub enum KnownTagState {
    /// State has tag
    Present,
    /// State does not have tag
    Absent,
}

impl BooleanLike for KnownTagState {
    const TRUTHY: Self = KnownTagState::Present;
    const FALSY: Self = KnownTagState::Absent;
}

impl From<(Tag, KnownTagState)> for SignedLitteral<Tag> {
    fn from((tag, sign): (Tag, KnownTagState)) -> Self {
        Self::Val {
            litteral: tag,
            sign: Sign::from_bool(sign.as_bool()),
        }
    }
}

/// A type representing the knowledge about the tag.
#[derive(PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
pub enum TagKnowledge {
    /// Tag may or may not be present
    Unknown,
    /// We know if tag is present or not
    Known(KnownTagState),
}

impl From<KnownTagState> for TagKnowledge {
    fn from(value: KnownTagState) -> Self {
        Self::Known(value)
    }
}

impl Default for TagKnowledge {
    fn default() -> Self {
        Self::Unknown
    }
}

impl Imply for KnownTagState {
    fn implies(&self, other: &Self) -> bool {
        return self == other;
    }
}

impl From<KnownTagState> for bool {
    fn from(value: KnownTagState) -> Self {
        match value {
            KnownTagState::Absent => false,
            KnownTagState::Present => true,
        }
    }
}

impl Imply for TagKnowledge {
    fn implies(&self, other: &Self) -> bool {
        match self {
            Self::Unknown => self == other,
            Self::Known(kts) => match other {
                Self::Unknown => true,
                Self::Known(kts2) => kts.implies(kts2),
            },
        }
    }
}

/// An action to execute on a tag
#[derive(Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
pub enum TagAction {
    /// Add tag
    Add,
    /// Remove tag
    Remove,
}

impl BooleanLike for TagAction {
    const FALSY: Self = Self::Remove;
    const TRUTHY: Self = Self::Add;
}

/// Trait for types than can imply themselves. It a weak partial ordering.
pub trait Imply {
    /// True if self implies other.
    fn implies(&self, other: &Self) -> bool;
}

/// Trait to represent types as notmuch queries
pub trait AsQuery {
    /// Get the query representing the item.
    fn as_query(&self) -> String;
}

/// A type representing tags to add or delete.
#[derive(
    Debug,
    PartialEq,
    Eq,
    Deref,
    DerefMut,
    Clone,
    PartialOrd,
    Ord,
    From,
    AsRef,
    SerializeDisplay,
    DeserializeFromStr,
)]
pub struct Vector(BTreeMap<Tag, TagAction>);

impl AsQuery for Vector {
    fn as_query(&self) -> String {
        EffectiveState::from(
            self.0
                .iter()
                .map(|(t, ta)| (t.clone(), ta.as_other()))
                .collect::<BTreeMap<Tag, KnownTagState>>(),
        )
        .as_query()
    }
}

impl Vector {
    /// Make a new vector
    pub fn new() -> Self {
        Vector(BTreeMap::new())
    }

    /// Translate a state by applying the vector
    pub fn translate(&self, point: &EffectiveState) -> EffectiveState {
        let mut translated = point.clone();
        translated.extend(self.iter().map(|(t, a)| (t.clone(), a.clone().into())));
        translated
    }

    /// Retag a message according to this vector.
    pub fn execute(&self, message: &notmuch::Message, dry_run: bool) -> Result<(), notmuch::Error> {
        trace!("Tagging message {}", message.id());
        if !dry_run {
            for (tag, action) in self.iter() {
                match action {
                    TagAction::Add => message.add_tag(&tag)?,
                    TagAction::Remove => message.remove_tag(&tag)?,
                }
            }
        }
        Ok(())
    }

    /// Tries to insert a new direction in the vector.
    /// Fails if the vector already contains a direction for a given tag.
    fn try_insert_direction<Direction>(&mut self, direction: Direction) -> Result<(), VectorError>
    where
        Direction: Into<(Tag, TagAction)>,
    {
        let (tag, action) = direction.into();
        match self.insert(tag.clone(), action) {
            Some(_) => Err(VectorError::AmbiguousRule(tag)),
            None => Ok(()),
        }
    }

    /// Converts an iterable of directions to a vector
    ///
    /// Fails is a direction is given multiple times.
    fn try_from_iterator<I, VD>(iter: I) -> Result<Self, VectorError>
    where
        I: IntoIterator<Item = VD>,
        VD: Into<(Tag, TagAction)>,
    {
        Self::try_from_failible_iterator(iter.into_iter().map(Result::Ok))
    }

    /// Tries to convert an iterable of parsing results to a vector.
    fn try_from_failible_iterator<I, VD>(iter: I) -> Result<Self, VectorError>
    where
        I: IntoIterator<Item = Result<VD, VectorError>>,
        VD: Into<(Tag, TagAction)>,
    {
        let mut empty_transition = Self::new();
        iter.into_iter()
            .try_for_each(|trans| empty_transition.try_insert_direction(trans?))?;
        Ok(empty_transition)
    }

    /// Iterate over the directions in the vector
    fn iter_elements(&self) -> impl Iterator<Item = VectorDirection> + use<'_> {
        self.iter()
            .map(|(t, a)| VectorDirection::from((t.clone(), *a)))
    }
}

/// Error type for Vector
#[derive(Debug)]
pub enum VectorError {
    ParseError(&'static str),
    AmbiguousRule(Tag), // TODO Do I want to check ambiguity or do I want that last wins ?
}

impl std::fmt::Display for VectorError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::AmbiguousRule(tag) => write!(f, "Ambiguous transition for tag {}", tag),
            Self::ParseError(msg) => write!(f, "Parse error: {msg}"),
        }
    }
}

impl Display for Vector {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            self.iter_elements().map(|e| e.to_string()).join(" ")
        )
    }
}

impl FromStr for Vector {
    type Err = VectorError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Vector::try_from_failible_iterator(s.split_whitespace().map(VectorDirection::from_str))
    }
}
// Vector Direction {{{

/// Enum describing a tag and the action associated to it when performing a translation.
///
/// This type can be parsed from a string: `+tag` is parsed as `Add("tag")`, `-tag` is parsed as
/// `Remove("tag")`.
#[derive(Debug, Eq, PartialEq, Clone, Display, SerializeDisplay, DeserializeFromStr)]
pub enum VectorDirection {
    /// Add this tag
    #[display("+{}", _0)]
    Add(Tag),
    /// Remove this tag
    #[display("-{}", _0)]
    Remove(Tag),
}

impl VectorDirection {
    /// Get the tag out of this transition element
    fn get_tag(&self) -> &Tag {
        match self {
            VectorDirection::Add(t) => t,
            VectorDirection::Remove(t) => t,
        }
    }

    /// Get the action this transition element should perform
    fn get_action(&self) -> TagAction {
        match self {
            VectorDirection::Add(_) => TagAction::Add,
            VectorDirection::Remove(_) => TagAction::Remove,
        }
    }
}

impl From<(Tag, TagAction)> for VectorDirection {
    fn from((t, action): (Tag, TagAction)) -> Self {
        match action {
            TagAction::Add => VectorDirection::Add(t),
            TagAction::Remove => VectorDirection::Remove(t),
        }
    }
}

impl From<VectorDirection> for (Tag, TagAction) {
    fn from(value: VectorDirection) -> Self {
        (value.get_tag().clone(), value.get_action())
    }
}

impl FromStr for VectorDirection {
    type Err = VectorError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut chars = s.chars();
        match (chars.next(), chars.as_str()) {
            (_, "") => Err(VectorError::ParseError("Empty tag")),
            (Some('+'), t) => Ok(Self::Add(t.to_string().into())),
            (Some('-'), t) => Ok(Self::Remove(t.to_string().into())),
            _ => Err(VectorError::ParseError("Not a valid transition string")),
        }
    }
}

impl From<VectorDirection> for Either<Tag, Tag> {
    fn from(value: VectorDirection) -> Self {
        match value {
            VectorDirection::Add(t) => Either::Left(t),
            VectorDirection::Remove(t) => Either::Right(t),
        }
    }
}

// END Vector Direction }}}

/// A type representing a simple rue: if message matches `source`, apply `vector`.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Arrow {
    /// State to which the transformation applies
    pub source: EffectiveState,
    /// Transformation
    pub vector: Vector,
}

impl From<TagAction> for KnownTagState {
    fn from(value: TagAction) -> Self {
        match value {
            TagAction::Add => Self::Present,
            TagAction::Remove => Self::Absent,
        }
    }
}

impl AsQuery for Arrow {
    fn as_query(&self) -> String {
        format!(
            "({}) and not ({})",
            self.source.as_query(),
            self.vector.as_query()
        )
    }
}

impl Arrow {
    /// The state this arrow points to.
    pub fn target(&self) -> EffectiveState {
        self.vector.translate(&self.source)
    }

    /// Search for messages and retag them
    pub fn execute(
        &self,
        db: &notmuch::Database,
        dry_run: bool,
        lastmod: Option<u64>,
    ) -> Result<(), notmuch::Error> {
        let query_txt = if let Some(last) = lastmod {
            format!("({}) and lastmod:{}..", self.as_query(), last)
        } else {
            self.as_query()
        };

        debug!("Searching for query: {}", query_txt);
        let query = db.create_query(&query_txt)?;
        let count = query.count_messages()?;
        let messages = query.search_messages()?;
        debug!("Tagging {} messges with: {}", count, self.vector);
        for message in messages {
            self.vector.execute(&message, dry_run)?
        }
        Ok(())
    }
}
impl PartialOrd for Arrow {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        let self_level = self.source.height();
        let other_level = other.source.height();
        if self_level == other_level {
            self.source.partial_cmp(&other.source)
        } else {
            self_level.partial_cmp(&other_level)
        }
    }
}

impl Ord for Arrow {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        let self_level = self.source.height();
        let other_level = other.source.height();
        if self_level == other_level {
            self.source.cmp(&other.source)
        } else {
            self_level.cmp(&other_level)
        }
    }
}

/// Labelled arrow designating a rule with a name
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct LabelledArrow {
    pub name: String,
    pub arrow: Arrow,
}

impl LabelledArrow {
    /// Creates an arrow between two states, labelled by epsilon.
    pub fn eplison(source: EffectiveState, target: EffectiveState) -> Self {
        let vector: Vector = Vector(
            target
                .iter()
                .map(|(t, ts)| (t.clone(), ts.as_other()))
                .collect(),
        );
        LabelledArrow {
            name: "ε".to_string(),
            arrow: Arrow { source, vector },
        }
    }

    fn execute(
        &self,
        db: &notmuch::Database,
        dry_run: bool,
        lastmod: Option<u64>,
    ) -> Result<(), notmuch::Error> {
        debug!("Retagging with rule {}.", &self.name);
        self.arrow.execute(db, dry_run, lastmod)
    }
}

impl PartialOrd for LabelledArrow {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.arrow.partial_cmp(&other.arrow)
    }
}

impl Ord for LabelledArrow {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.arrow.cmp(&other.arrow)
    }
}

impl LabelledArrow {
    // Change the source of the base point.
    pub fn move_base_point(&self, source: EffectiveState) -> LabelledArrow {
        LabelledArrow {
            name: self.name.clone(),
            arrow: Arrow {
                source: source,
                vector: self.arrow.vector.clone(),
            },
        }
    }
}

/// A collection of arrows that define the rewriting procedure
#[derive(Debug, PartialEq, Eq, Clone, Deref, DerefMut, AsRef, AsMut, From)]
pub struct Quiver(BTreeSet<LabelledArrow>);

impl Quiver {
    /// Retag messages according to rules.
    pub fn execute(
        &self,
        db: &notmuch::Database,
        dry_run: bool,
        lastmod: Option<u64>,
    ) -> Result<(), notmuch::Error> {
        debug!("Retagging…");
        for arr in self.iter() {
            db.begin_atomic()?;
            arr.execute(db, dry_run, lastmod)?;
            db.end_atomic()?;
        }
        Ok(())
    }
}