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
use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use super::scenario::Version;

/// A stanza telling APT to install a specific new package, or to upgrade or downgrade a package
/// to a specific version.
#[derive(Serialize, Deserialize, Debug, Default, Eq, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct Install {
    /// The identifier of the package to install.
    ///
    /// Must reference the identifier of a package in the package universe
    /// (see [`Package::id`](super::scenario::Package::id)).
    pub install: String,

    /// The name of the package to install.
    ///
    /// While optional, it is highly recommend to set this field to the value of the field
    /// ([`Package::package`](super::scenario::Package::package)) of the corresponding
    /// package in the package universe.
    pub package: Option<String>,

    /// The version of the package to install.
    ///
    /// While optional, it is highly recommend to set this field to the value of the field
    /// ([`Package::version`](super::scenario::Package::version)) of the corresponding
    /// package in the package universe.
    pub version: Option<Version>,

    /// The architecture of the package to install.
    ///
    /// While optional, it is highly recommend to set this field to the value of the field
    /// ([`Package::architecture`](super::scenario::Package::architecture)) of the corresponding
    /// package in the package universe.
    pub architecture: Option<String>,

    /// Extra optional fields supported by [`Package`](super::scenario::Package) stanzas.
    #[serde(flatten)]
    pub extra: HashMap<String, String>,
}

/// A stanza telling APT to remove a specific package.
#[derive(Serialize, Deserialize, Debug, Default, Eq, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct Remove {
    /// The identifier of the package to remove.
    ///
    /// Must reference the identifier of a package in the package universe
    /// (see [`Package::id`](super::scenario::Package::id)).
    pub remove: String,

    /// The name of the package to remove.
    ///
    /// While optional, it is highly recommend to set this field to the value of the field
    /// ([`Package::package`](super::scenario::Package::package)) of the corresponding
    /// package in the package universe.
    pub package: Option<String>,

    /// The version of the package to remove.
    ///
    /// While optional, it is highly recommend to set this field to the value of the field
    /// ([`Package::version`](super::scenario::Package::version)) of the corresponding
    /// package in the package universe.
    pub version: Option<Version>,

    /// The architecture of the package to remove.
    ///
    /// While optional, it is highly recommend to set this field to the value of the field
    /// ([`Package::architecture`](super::scenario::Package::architecture)) of the corresponding
    /// package in the package universe.
    pub architecture: Option<String>,

    /// Extra optional fields supported by [`Package`](super::scenario::Package) stanzas.
    #[serde(flatten)]
    pub extra: HashMap<String, String>,
}

/// A stanza telling APT that a specific package can be autoremoved as a consequence of the
/// executed user request.
#[derive(Serialize, Deserialize, Debug, Default, Eq, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct Autoremove {
    /// The identifier of the package that can be autoremoved.
    ///
    /// Must reference the identifier of a package in the package universe
    /// (see [`Package::id`](super::scenario::Package::id)).
    pub autoremove: String,

    /// Extra optional fields supported by [`Package`](super::scenario::Package) stanzas.
    #[serde(flatten)]
    pub extra: HashMap<String, String>,
}

/// An [Error stanza][error] reporting the error(s) faced when trying to fulfill an
/// unsatisfiable user request.
///
/// [error]: https://salsa.debian.org/apt-team/apt/-/blob/a8367745/doc/external-dependency-solver-protocol.md#error
#[derive(Serialize, Deserialize, Debug, Default, Eq, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct Error {
    /// A unique error identifier, such as a UUID. The value of this field is ignored.
    pub error: String,

    /// Human-readable text explaining the cause of the solver error.
    ///
    /// If multiline, the first line conveys a short message, which is then explained in more
    /// detail in subsequent lines.
    pub message: String,
}

/// A stanza in an [`Answer::Solution`].
#[derive(Serialize, Debug, Eq, PartialEq)]
#[serde(untagged)]
pub enum Action {
    /// A single [`Install`] stanza in an [`Answer::Solution`].
    Install(Install),
    /// A single [`Remove`] stanza in an [`Answer::Solution`].
    Remove(Remove),
    /// A single [`Autoremove`] stanza in an [`Answer::Solution`].
    Autoremove(Autoremove),
}

impl From<Install> for Action {
    fn from(value: Install) -> Self {
        Self::Install(value)
    }
}

impl From<Remove> for Action {
    fn from(value: Remove) -> Self {
        Self::Remove(value)
    }
}

impl From<Autoremove> for Action {
    fn from(value: Autoremove) -> Self {
        Self::Autoremove(value)
    }
}

/// The [answer] returned from the external solver to APT upon completion of the dependency
/// resolution process.
///
/// [answer]: https://salsa.debian.org/apt-team/apt/-/blob/a8367745/doc/external-dependency-solver-protocol.md#answer
#[derive(Serialize, Debug, Eq, PartialEq)]
#[serde(untagged)]
pub enum Answer {
    /// A list of stanzas describing the [`Action`]s to be made to the set of installed packages
    /// to satisfy the user's request.
    Solution(Vec<Action>),
    /// A single [`Error`] stanza reporting an error during the dependency resolution process.
    Error(Error),
}

impl Answer {
    /// Writes this [`Answer`] to the given `writer`. On error, returns an [`AnswerWriteError`].
    pub fn write_to(&self, writer: impl std::io::Write) -> Result<(), AnswerWriteError> {
        rfc822_like::to_writer(writer, self).map_err(Into::into)
    }
}

impl From<Error> for Answer {
    fn from(value: Error) -> Self {
        Self::Error(value)
    }
}

/// The error returned when [`Answer::write_to`] fails.
///
/// Though the implementation details are hidden, the struct implements [`std::error::Error`]
/// and a human-friendly [`std::fmt::Display`] implementation.
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct AnswerWriteError(#[from] rfc822_like::ser::Error);

#[cfg(test)]
mod tests {
    use indoc::indoc;

    use crate::test_util::ser_test;

    use super::*;

    ser_test! {
        test_action: {
            indoc! {"
                Install: abc
            "} =>
            Action::Install(Install {
                install: "abc".into(),
                ..Default::default()
            }),
        }
    }

    ser_test! {
        test_answer: {
            indoc! {"
                Install: 123
                Architecture: amd64

                Remove: 234
                Package: bar
                Version: 0.1.2

                Autoremove: 345
            "} =>
            Answer::Solution(
                vec![
                    Install {
                        install: "123".into(),
                        architecture: Some("amd64".into()),
                        ..Default::default()
                    }.into(),
                    Remove {
                        remove: "234".into(),
                        package: Some("bar".into()),
                        version: Some("0.1.2".try_into().unwrap()),
                        ..Default::default()
                    }.into(),
                    Autoremove {
                        autoremove: "345".into(),
                        ..Default::default()
                    }.into(),
                ]
            ),
            indoc! {"
                Error: foo
                Message: bar
                 baz
            "} =>
            Answer::Error(Error {
                error: "foo".to_string(),
                message: "bar\nbaz".to_string(),
            }),
        }
    }
}