Skip to main content

codex_patcher/toml/
operations.rs

1use crate::toml::errors::TomlError;
2use crate::toml::query::SectionPath;
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub struct Constraints {
6    pub ensure_absent: bool,
7    pub ensure_present: bool,
8}
9
10impl Constraints {
11    pub fn none() -> Self {
12        Self {
13            ensure_absent: false,
14            ensure_present: false,
15        }
16    }
17}
18
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum Positioning {
21    AfterSection(SectionPath),
22    BeforeSection(SectionPath),
23    AtEnd,
24    AtBeginning,
25}
26
27impl Positioning {
28    pub fn resolve(
29        after_section: Option<SectionPath>,
30        before_section: Option<SectionPath>,
31        at_end: bool,
32        at_beginning: bool,
33    ) -> Result<Self, TomlError> {
34        let mut count = 0;
35        if after_section.is_some() {
36            count += 1;
37        }
38        if before_section.is_some() {
39            count += 1;
40        }
41        if at_end {
42            count += 1;
43        }
44        if at_beginning {
45            count += 1;
46        }
47        if count > 1 {
48            return Err(TomlError::InvalidPositioning {
49                message: "only one positioning directive is allowed".to_string(),
50            });
51        }
52        if let Some(path) = after_section {
53            return Ok(Positioning::AfterSection(path));
54        }
55        if let Some(path) = before_section {
56            return Ok(Positioning::BeforeSection(path));
57        }
58        if at_beginning {
59            return Ok(Positioning::AtBeginning);
60        }
61        Ok(Positioning::AtEnd)
62    }
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub enum TomlOperation {
67    InsertSection {
68        text: String,
69        positioning: Positioning,
70    },
71    AppendSection {
72        text: String,
73    },
74    ReplaceValue {
75        value: String,
76    },
77    DeleteSection,
78    ReplaceKey {
79        new_key: String,
80    },
81}