Skip to main content

onetaskgraph_plugin_api/
status_mapping.rs

1//! `status_mapping`: the one grammar every source that names its statuses is configured with.
2//!
3//! A source whose backend has a vocabulary of status names of its own — a board's `Status`
4//! options, a Linear team's workflow states and its workspace's project statuses — is told
5//! which name each [`StatusCategory`] is, for each [`ItemKind`], by one object:
6//!
7//! ```yaml
8//! status_mapping:
9//!   todo: Todo                                 # every kind
10//!   draft: null                                # disabled for every kind
11//!   done: { task: Done, project: Completed }   # per kind
12//! ```
13//!
14//! The keys are status categories, spelled exactly as [`StatusCategory`] serializes. A value
15//! is a non-blank name for every kind, `null` to disable the category for every kind, or an
16//! object with the optional keys `task` and `project`, each a non-blank name, where a key left
17//! out leaves the category unmapped for that kind. Anything else is refused as the
18//! configuration is read, naming the category and the offending part.
19//!
20//! Defined here rather than in each plugin because it is one concept with one grammar: two
21//! spellings of it would let a configuration that loads under one source be refused, or read
22//! differently, under another.
23
24use std::{borrow::Cow, fmt};
25
26use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
27use serde::{
28    Deserialize, Deserializer, Serialize, Serializer,
29    de::{self, MapAccess, Visitor},
30    ser::SerializeMap,
31};
32use serde_json::Value;
33
34use crate::{ItemKind, SourceError, SourceName, StatusCategory};
35
36/// Every status category, in the contract's own order — the order a mapping is held and
37/// reported in.
38const CATEGORIES: [StatusCategory; 9] = [
39    StatusCategory::Draft,
40    StatusCategory::Backlog,
41    StatusCategory::Todo,
42    StatusCategory::Queued,
43    StatusCategory::InProgress,
44    StatusCategory::InReview,
45    StatusCategory::Done,
46    StatusCategory::Cancelled,
47    StatusCategory::Unknown,
48];
49
50/// Where `category` sits in [`CATEGORIES`] — an exhaustive match, so a category the contract
51/// adds fails to compile here rather than going unmapped.
52const fn position(category: StatusCategory) -> usize {
53    match category {
54        StatusCategory::Draft => 0,
55        StatusCategory::Backlog => 1,
56        StatusCategory::Todo => 2,
57        StatusCategory::Queued => 3,
58        StatusCategory::InProgress => 4,
59        StatusCategory::InReview => 5,
60        StatusCategory::Done => 6,
61        StatusCategory::Cancelled => 7,
62        StatusCategory::Unknown => 8,
63    }
64}
65
66const _: () = {
67    let mut index = 0;
68    while index < CATEGORIES.len() {
69        assert!(position(CATEGORIES[index]) == index);
70        index += 1;
71    }
72};
73
74/// A category as the configuration spells it — `in-progress`, `queued`.
75const fn category_key(category: StatusCategory) -> &'static str {
76    match category {
77        StatusCategory::Draft => "draft",
78        StatusCategory::Backlog => "backlog",
79        StatusCategory::Todo => "todo",
80        StatusCategory::Queued => "queued",
81        StatusCategory::InProgress => "in-progress",
82        StatusCategory::InReview => "in-review",
83        StatusCategory::Done => "done",
84        StatusCategory::Cancelled => "cancelled",
85        StatusCategory::Unknown => "unknown",
86    }
87}
88
89/// An item kind as the configuration spells it.
90const fn kind_key(kind: ItemKind) -> &'static str {
91    match kind {
92        ItemKind::Task => "task",
93        ItemKind::Project => "project",
94    }
95}
96
97/// One status name a source's backend holds: a board option, a workflow state, a project
98/// status.
99///
100/// Validated on the way in, so a blank name — which nothing in any backend can be called — is
101/// a name this type cannot hold. Compared case-insensitively wherever a source matches it,
102/// because every backend this product reads matches its own names that way.
103#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
104#[serde(try_from = "String", into = "String")]
105pub struct StatusName(String);
106
107impl StatusName {
108    /// The name, as the configuration spells it.
109    #[must_use]
110    pub fn as_str(&self) -> &str {
111        &self.0
112    }
113
114    /// Whether `other` is this name, as every backend compares its own: ignoring ASCII case.
115    #[must_use]
116    pub fn matches(&self, other: &str) -> bool {
117        self.0.eq_ignore_ascii_case(other)
118    }
119}
120
121impl TryFrom<String> for StatusName {
122    type Error = String;
123
124    fn try_from(name: String) -> Result<Self, Self::Error> {
125        if name.trim().is_empty() {
126            Err("a status name cannot be blank".to_owned())
127        } else {
128            Ok(Self(name))
129        }
130    }
131}
132
133impl From<StatusName> for String {
134    fn from(name: StatusName) -> Self {
135        name.0
136    }
137}
138
139impl fmt::Display for StatusName {
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        f.write_str(&self.0)
142    }
143}
144
145impl JsonSchema for StatusName {
146    fn schema_name() -> Cow<'static, str> {
147        "StatusName".into()
148    }
149
150    fn json_schema(_: &mut SchemaGenerator) -> Schema {
151        json_schema!({
152            "description": "One status name a source's backend holds, matched ignoring case. Never blank.",
153            "type": "string",
154            "minLength": 1,
155            "pattern": "\\S"
156        })
157    }
158}
159
160/// What one category of a `status_mapping` names: one name for every kind, or a name for
161/// each kind it maps.
162///
163/// Four variants rather than a pair of optional names, so a per-kind object naming no kind —
164/// which the grammar refuses — is a value this type cannot hold.
165#[derive(Debug, Clone, PartialEq, Eq)]
166pub enum StatusNames {
167    /// The same name for a task and for a project: the bare-string form.
168    Every(StatusName),
169    /// `{ task: … }`: a name for a task, and the category unmapped for a project.
170    Task(StatusName),
171    /// `{ project: … }`: a name for a project, and the category unmapped for a task.
172    Project(StatusName),
173    /// `{ task: …, project: … }`: a name for each.
174    PerKind {
175        /// The name for a task.
176        task: StatusName,
177        /// The name for a project.
178        project: StatusName,
179    },
180}
181
182impl StatusNames {
183    /// The name this gives `kind`, or `None` where it leaves that kind unmapped.
184    #[must_use]
185    pub fn for_kind(&self, kind: ItemKind) -> Option<&StatusName> {
186        match (self, kind) {
187            (Self::Every(name), _)
188            | (Self::Task(name), ItemKind::Task)
189            | (Self::Project(name), ItemKind::Project)
190            | (Self::PerKind { task: name, .. }, ItemKind::Task)
191            | (Self::PerKind { project: name, .. }, ItemKind::Project) => Some(name),
192            (Self::Task(_), ItemKind::Project) | (Self::Project(_), ItemKind::Task) => None,
193        }
194    }
195
196    /// One configured value, read with the category it is under so a refusal can name it.
197    fn parse(category: StatusCategory, value: Value) -> Result<Self, String> {
198        let at = category_key(category);
199        let name = |value: Value, path: &str| -> Result<StatusName, String> {
200            match value {
201                Value::String(name) => StatusName::try_from(name).map_err(|_| {
202                    format!("status_mapping.{path} is blank; a status name cannot be blank")
203                }),
204                Value::Null => Err(format!(
205                    "status_mapping.{path} is null; leave that key out to leave {at} unmapped for \
206                     that kind, or set status_mapping.{at} to null to disable {at} for every kind"
207                )),
208                other => Err(format!(
209                    "status_mapping.{path} is {other}, which is not a status name; write the \
210                     name as a string"
211                )),
212            }
213        };
214        match value {
215            Value::String(_) => name(value, at).map(Self::Every),
216            Value::Object(object) => {
217                if object.is_empty() {
218                    return Err(format!(
219                        "status_mapping.{at} is an empty object, which maps no kind; to disable \
220                         {at} for every kind, write null"
221                    ));
222                }
223                let mut task = None;
224                let mut project = None;
225                for (key, value) in object {
226                    match key.as_str() {
227                        "task" => task = Some(name(value, &format!("{at}.task"))?),
228                        "project" => project = Some(name(value, &format!("{at}.project"))?),
229                        other => {
230                            return Err(format!(
231                                "status_mapping.{at} names {other:?}, which is not an item kind; \
232                                 the kinds are task and project"
233                            ));
234                        }
235                    }
236                }
237                Ok(match (task, project) {
238                    (Some(task), Some(project)) => Self::PerKind { task, project },
239                    (Some(task), None) => Self::Task(task),
240                    (None, Some(project)) => Self::Project(project),
241                    (None, None) => unreachable!("a non-empty object of known keys names a kind"),
242                })
243            }
244            other => Err(format!(
245                "status_mapping.{at} is {other}, which is none of a status name, null, or an \
246                 object with the keys task and project"
247            )),
248        }
249    }
250}
251
252impl Serialize for StatusNames {
253    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
254        match self {
255            Self::Every(name) => name.serialize(serializer),
256            Self::Task(task) => {
257                let mut map = serializer.serialize_map(Some(1))?;
258                map.serialize_entry("task", task)?;
259                map.end()
260            }
261            Self::Project(project) => {
262                let mut map = serializer.serialize_map(Some(1))?;
263                map.serialize_entry("project", project)?;
264                map.end()
265            }
266            Self::PerKind { task, project } => {
267                let mut map = serializer.serialize_map(Some(2))?;
268                map.serialize_entry("task", task)?;
269                map.serialize_entry("project", project)?;
270                map.end()
271            }
272        }
273    }
274}
275
276impl JsonSchema for StatusNames {
277    fn schema_name() -> Cow<'static, str> {
278        "StatusNames".into()
279    }
280
281    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
282        let name = generator.subschema_for::<StatusName>();
283        let only = |kind: &str| {
284            json_schema!({
285                "type": "object",
286                "properties": { (kind): name },
287                "required": [kind],
288                "additionalProperties": false
289            })
290        };
291        json_schema!({
292            "description": "What one category of a status_mapping names: one name for every item kind, or an object naming it for a task, for a project, or for each. A kind the object leaves out leaves the category unmapped for that kind.",
293            "anyOf": [
294                name,
295                only("task"),
296                only("project"),
297                {
298                    "type": "object",
299                    "properties": { "task": name, "project": name },
300                    "required": ["task", "project"],
301                    "additionalProperties": false
302                }
303            ]
304        })
305    }
306}
307
308/// Why a mapping gives no name for one category and one kind.
309#[derive(Debug, Clone, Copy, PartialEq, Eq)]
310pub enum UnmappedStatus {
311    /// The mapping does not mention the category at all.
312    Unconfigured,
313    /// The mapping sets the category to `null`, disabling it for every kind.
314    Disabled,
315    /// The mapping names the category for the other kind only.
316    OtherKindOnly,
317}
318
319impl UnmappedStatus {
320    /// The refusal of a status write `source` has no name for: naming the source, the kind,
321    /// the category, why, and the key to set.
322    #[must_use]
323    pub fn refusal(
324        self,
325        source: &SourceName,
326        category: StatusCategory,
327        kind: ItemKind,
328    ) -> SourceError {
329        let at = category_key(category);
330        let of = kind_key(kind);
331        let why = match self {
332            Self::Unconfigured => format!("its status_mapping does not name {at}"),
333            Self::Disabled => {
334                format!("its status_mapping sets {at} to null, disabling it for every kind")
335            }
336            Self::OtherKindOnly => format!("its status_mapping names {at} for the other kind only"),
337        };
338        SourceError::Refused {
339            message: format!(
340                "source {source} has no {of} status name for {at}: {why}; next: set \
341                 status_mapping.{at}.{of} of this source to the {of} status {at} should be \
342                 written as"
343            ),
344        }
345    }
346}
347
348/// One source's `status_mapping`: for each status category it mentions, the names it gives
349/// each item kind, or `null`.
350///
351/// Held in the contract's category order with each category at most once, so iterating it
352/// reports in that order and a category named twice is a state it cannot hold.
353#[derive(Debug, Clone, Default, PartialEq, Eq)]
354pub struct StatusMapping {
355    entries: Vec<(StatusCategory, Option<StatusNames>)>,
356}
357
358impl StatusMapping {
359    /// Whether the mapping mentions no category at all.
360    #[must_use]
361    pub fn is_empty(&self) -> bool {
362        self.entries.is_empty()
363    }
364
365    /// Whether the mapping mentions `category`, as a name or as `null`.
366    #[must_use]
367    pub fn mentions(&self, category: StatusCategory) -> bool {
368        self.entries.iter().any(|(held, _)| *held == category)
369    }
370
371    /// What the mapping says of `category`: `None` where it does not mention it, `Some(None)`
372    /// where it sets it to `null`, and the names otherwise.
373    #[must_use]
374    pub fn entry(&self, category: StatusCategory) -> Option<Option<&StatusNames>> {
375        self.entries
376            .iter()
377            .find(|(held, _)| *held == category)
378            .map(|(_, names)| names.as_ref())
379    }
380
381    /// The name `category` is written as for `kind`, or why the mapping gives none.
382    ///
383    /// # Errors
384    ///
385    /// The [`UnmappedStatus`] saying which of the three ways the mapping gives no name.
386    pub fn name_for(
387        &self,
388        category: StatusCategory,
389        kind: ItemKind,
390    ) -> Result<&StatusName, UnmappedStatus> {
391        match self.entry(category) {
392            None => Err(UnmappedStatus::Unconfigured),
393            Some(None) => Err(UnmappedStatus::Disabled),
394            Some(Some(names)) => names.for_kind(kind).ok_or(UnmappedStatus::OtherKindOnly),
395        }
396    }
397
398    /// Every name the mapping gives `kind`, with its category, in category order.
399    pub fn names(&self, kind: ItemKind) -> impl Iterator<Item = (StatusCategory, &StatusName)> {
400        self.entries.iter().filter_map(move |(category, names)| {
401            names
402                .as_ref()
403                .and_then(|names| names.for_kind(kind))
404                .map(|name| (*category, name))
405        })
406    }
407
408    /// The category a `kind` name reads as, when the mapping names it for that kind.
409    #[must_use]
410    pub fn category_of(&self, kind: ItemKind, name: &str) -> Option<StatusCategory> {
411        self.names(kind)
412            .find_map(|(category, mapped)| mapped.matches(name).then_some(category))
413    }
414
415    /// Refuse two categories sent to one name of one kind, ignoring case: that name could read
416    /// back as only one of them.
417    ///
418    /// Takes the names to compare rather than reading this mapping's own, so a source whose
419    /// unmentioned categories keep shipped defaults compares what it really resolves to.
420    ///
421    /// # Errors
422    ///
423    /// [`SourceError::Config`] naming the source, the kind, both categories and the name.
424    pub fn distinct<'a>(
425        source: &SourceName,
426        kind: ItemKind,
427        names: impl IntoIterator<Item = (StatusCategory, &'a str)>,
428    ) -> Result<(), SourceError> {
429        let mut seen: Vec<(StatusCategory, &str)> = Vec::new();
430        for (category, name) in names {
431            if let Some((other, _)) = seen
432                .iter()
433                .find(|(_, held)| held.eq_ignore_ascii_case(name))
434            {
435                return Err(SourceError::Config {
436                    message: format!(
437                        "source {source}: status_mapping sends both {} and {} to the {} status \
438                         {name:?}; one name cannot read back as two categories, so map one of \
439                         them to another name",
440                        category_key(*other),
441                        category_key(category),
442                        kind_key(kind),
443                    ),
444                });
445            }
446            seen.push((category, name));
447        }
448        Ok(())
449    }
450}
451
452impl Serialize for StatusMapping {
453    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
454        let mut map = serializer.serialize_map(Some(self.entries.len()))?;
455        for (category, names) in &self.entries {
456            map.serialize_entry(category_key(*category), names)?;
457        }
458        map.end()
459    }
460}
461
462impl<'de> Deserialize<'de> for StatusMapping {
463    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
464        struct Entries;
465
466        impl<'de> Visitor<'de> for Entries {
467            type Value = StatusMapping;
468
469            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
470                f.write_str("a status_mapping object keyed by status category")
471            }
472
473            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<StatusMapping, A::Error> {
474                let mut entries: Vec<(StatusCategory, Option<StatusNames>)> = Vec::new();
475                while let Some(key) = map.next_key::<String>()? {
476                    let category = CATEGORIES
477                        .into_iter()
478                        .find(|category| category_key(*category) == key)
479                        .ok_or_else(|| {
480                            de::Error::custom(format!(
481                                "status_mapping names {key:?}, which is not a status category; \
482                                 the categories are {}",
483                                CATEGORIES.map(category_key).join(", ")
484                            ))
485                        })?;
486                    if entries.iter().any(|(held, _)| *held == category) {
487                        return Err(de::Error::custom(format!(
488                            "status_mapping names {key} twice"
489                        )));
490                    }
491                    let value: Value = map.next_value()?;
492                    let names = match value {
493                        Value::Null => None,
494                        value => {
495                            Some(StatusNames::parse(category, value).map_err(de::Error::custom)?)
496                        }
497                    };
498                    entries.push((category, names));
499                }
500                entries.sort_by_key(|(category, _)| position(*category));
501                Ok(StatusMapping { entries })
502            }
503        }
504
505        deserializer.deserialize_map(Entries)
506    }
507}
508
509impl JsonSchema for StatusMapping {
510    fn schema_name() -> Cow<'static, str> {
511        "StatusMapping".into()
512    }
513
514    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
515        let category = generator.subschema_for::<StatusCategory>();
516        let names = generator.subschema_for::<StatusNames>();
517        json_schema!({
518            "description": "Which name each status category is, for each item kind. Keyed by status category; each value is one name for every kind, null to disable the category for every kind, or an object naming it for a task, a project or each.",
519            "type": "object",
520            "propertyNames": category,
521            "additionalProperties": { "anyOf": [names, { "type": "null" }] }
522        })
523    }
524}
525
526#[cfg(test)]
527mod tests {
528    use serde_json::json;
529
530    use super::*;
531
532    fn read(value: Value) -> Result<StatusMapping, String> {
533        serde_json::from_value(value).map_err(|error| error.to_string())
534    }
535
536    #[test]
537    fn every_form_the_grammar_admits_loads_and_answers_by_kind() {
538        let mapping = read(json!({
539            "todo": "Todo",
540            "draft": null,
541            "done": {"task": "Done", "project": "Completed"},
542            "queued": {"task": "Queued"},
543            "backlog": {"project": "Idea"},
544        }))
545        .unwrap();
546        let name = |category, kind| mapping.name_for(category, kind).map(StatusName::as_str);
547        assert_eq!(name(StatusCategory::Todo, ItemKind::Task), Ok("Todo"));
548        assert_eq!(name(StatusCategory::Todo, ItemKind::Project), Ok("Todo"));
549        assert_eq!(
550            name(StatusCategory::Draft, ItemKind::Task),
551            Err(UnmappedStatus::Disabled)
552        );
553        assert_eq!(
554            name(StatusCategory::Done, ItemKind::Project),
555            Ok("Completed")
556        );
557        assert_eq!(
558            name(StatusCategory::Queued, ItemKind::Project),
559            Err(UnmappedStatus::OtherKindOnly)
560        );
561        assert_eq!(
562            name(StatusCategory::Backlog, ItemKind::Task),
563            Err(UnmappedStatus::OtherKindOnly)
564        );
565        assert_eq!(
566            name(StatusCategory::Unknown, ItemKind::Task),
567            Err(UnmappedStatus::Unconfigured)
568        );
569        assert_eq!(
570            mapping.category_of(ItemKind::Project, "completed"),
571            Some(StatusCategory::Done)
572        );
573        assert_eq!(mapping.category_of(ItemKind::Task, "Completed"), None);
574        // Held and written back in the contract's order, every form as it was given.
575        assert_eq!(
576            serde_json::to_value(&mapping).unwrap(),
577            json!({"draft": null, "backlog": {"project": "Idea"}, "todo": "Todo",
578                   "queued": {"task": "Queued"}, "done": {"task": "Done", "project": "Completed"}})
579        );
580        assert_eq!(
581            read(serde_json::to_value(&mapping).unwrap()).unwrap(),
582            mapping
583        );
584    }
585
586    #[test]
587    fn every_form_the_grammar_refuses_is_refused_naming_the_part() {
588        for (value, said) in [
589            (
590                json!({"doing": "Doing"}),
591                "\"doing\", which is not a status category",
592            ),
593            (
594                json!({"done": {}}),
595                "status_mapping.done is an empty object, which maps no kind; to disable done for every kind, write null",
596            ),
597            (
598                json!({"done": {"task": "Done", "epic": "Done"}}),
599                "status_mapping.done names \"epic\", which is not an item kind",
600            ),
601            (
602                json!({"done": {"task": null}}),
603                "status_mapping.done.task is null",
604            ),
605            (
606                json!({"done": {"project": " "}}),
607                "status_mapping.done.project is blank",
608            ),
609            (json!({"done": ""}), "status_mapping.done is blank"),
610            (json!({"done": 3}), "status_mapping.done is 3"),
611            (
612                json!({"done": {"task": 3}}),
613                "status_mapping.done.task is 3",
614            ),
615        ] {
616            let error = read(value.clone()).unwrap_err();
617            assert!(
618                error.contains(said),
619                "{value} was refused with {error:?}, not naming {said:?}"
620            );
621        }
622    }
623
624    /// The keys this grammar reads and writes, and the kinds its refusals name, are the
625    /// contract's own serialization of `StatusCategory` and `ItemKind`: a variant renamed on the
626    /// wire there and not here fails this rather than a configuration.
627    #[test]
628    fn every_key_is_the_contracts_own_spelling_of_its_category_and_kind() {
629        for category in CATEGORIES {
630            assert_eq!(
631                serde_json::to_value(category).unwrap(),
632                json!(category_key(category))
633            );
634        }
635        for kind in [ItemKind::Task, ItemKind::Project] {
636            assert_eq!(serde_json::to_value(kind).unwrap(), json!(kind_key(kind)));
637        }
638    }
639
640    #[test]
641    fn two_categories_on_one_name_of_one_kind_are_refused_ignoring_case() {
642        let source = SourceName::new("work").unwrap();
643        let error = StatusMapping::distinct(
644            &source,
645            ItemKind::Task,
646            [
647                (StatusCategory::Todo, "Todo"),
648                (StatusCategory::Queued, "TODO"),
649            ],
650        )
651        .unwrap_err();
652        assert!(
653            error.to_string().contains(
654                "source work: status_mapping sends both todo and queued to the task status \"TODO\""
655            ),
656            "{error}"
657        );
658        StatusMapping::distinct(
659            &source,
660            ItemKind::Task,
661            [
662                (StatusCategory::Todo, "Todo"),
663                (StatusCategory::Queued, "Queued"),
664            ],
665        )
666        .unwrap();
667    }
668
669    #[test]
670    fn an_unmapped_status_is_refused_naming_the_source_kind_category_and_key() {
671        let source = SourceName::new("work").unwrap();
672        let message = UnmappedStatus::OtherKindOnly
673            .refusal(&source, StatusCategory::InProgress, ItemKind::Project)
674            .to_string();
675        for part in [
676            "source work",
677            "project status name for in-progress",
678            "status_mapping.in-progress.project",
679        ] {
680            assert!(message.contains(part), "{message} does not name {part}");
681        }
682    }
683}