Skip to main content

ai6_safehouse_copy/
lib.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! `ai6-safehouse-copy`: the `copy` safe-house provider. Each Mission gets a plain copy of
6//! the source directory and the copy is always kept. There is no history, so the provider
7//! reports none and a cover check says the work is not checkable.
8
9#![doc = include_str!("../README.md")]
10
11guatiao::providers!(Copier);
12
13mod tree;
14
15use ai6_api::safehouse::{
16    ChangeLog, SafeHouseInfo, SafeHouseProvider, SafeHouseReport, SafeHouseRun, SafeHouseSpec,
17};
18use guatiao::library::{Object, ProviderError};
19use guatiao::{FromValue, Schema, Status, ToValue, Value};
20
21use tree::Tree;
22
23/// `copy` provider configuration; every field has a default.
24#[derive(ToValue, FromValue, Schema, Debug, Clone, Copy, PartialEq, Eq)]
25#[map(crate = ::guatiao)]
26pub struct CopyConfig {
27    /// Give each Mission its own copy. Off, Missions work in the source itself.
28    #[schema(title = "A copy for each Mission", section = "operation")]
29    #[map(default = true)]
30    pub isolate: bool,
31    /// Characters of an Operation or Mission ID kept in the name of its directory (a hash of
32    /// the whole ID follows, so distinct IDs never collide). Default 72.
33    #[map(default = 72)]
34    pub name_chars: u64,
35}
36
37impl Default for CopyConfig {
38    fn default() -> Self {
39        Self {
40            isolate: true,
41            name_chars: 72,
42        }
43    }
44}
45
46/// Makes a Mission's workspace as a plain copy of the source directory.
47#[derive(Debug, Clone, Copy, Default, guatiao::Provider)]
48#[provider(
49    SafeHouseProvider,
50    id = "copy",
51    name = "copy",
52    crate = ::guatiao,
53    config = CopyConfig
54)]
55pub struct Copier {
56    config: CopyConfig,
57}
58
59impl Copier {
60    /// A provider with `config`.
61    pub fn new(config: CopyConfig) -> Self {
62        Self { config }
63    }
64}
65
66impl TryFrom<CopyConfig> for Copier {
67    type Error = ProviderError;
68
69    fn try_from(config: CopyConfig) -> Result<Self, Self::Error> {
70        Ok(Self::new(config))
71    }
72}
73
74impl SafeHouseProvider for Copier {
75    fn open(&self, spec: &Value) -> Result<Object<dyn SafeHouseRun>, ProviderError> {
76        let spec = SafeHouseSpec::from_value(spec)
77            .map_err(|error| refuse(Status::GUATIAO_ERR_BAD_VALUE, error))?;
78        if spec.clone.is_some() {
79            return Err(refuse(
80                Status::GUATIAO_ERR_UNSUPPORTED,
81                "the copy provider does not clone repositories",
82            ));
83        }
84        let directory = Tree::open(
85            &spec,
86            usize::try_from(self.config.name_chars).unwrap_or(usize::MAX),
87        )
88        .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error))?;
89        Ok(CopySafeHouse(directory).into_object())
90    }
91}
92
93struct CopySafeHouse(Tree);
94
95impl SafeHouseRun for CopySafeHouse {
96    fn info(&self) -> Result<Value, ProviderError> {
97        value(&SafeHouseInfo {
98            path: self.0.path.to_string_lossy().into_owned(),
99            branch: None,
100            base: None,
101            supports_history: false,
102            isolated: self.0.isolated,
103        })
104    }
105
106    fn changes(&self) -> Result<Value, ProviderError> {
107        value(&ChangeLog::default())
108    }
109
110    fn finish(&self) -> Result<Value, ProviderError> {
111        value(&SafeHouseReport {
112            path: self.0.path.to_string_lossy().into_owned(),
113            branch: None,
114            base: None,
115            kept: self.0.path.exists(),
116            changes: Vec::new(),
117        })
118    }
119
120    fn discard(&self) -> Result<(), ProviderError> {
121        if !self.0.isolated {
122            return Err(refuse(
123                Status::GUATIAO_ERR_BAD_VALUE,
124                "a safe house in the source itself is never removed",
125            ));
126        }
127        match std::fs::remove_dir_all(&self.0.path) {
128            Ok(()) => Ok(()),
129            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
130            Err(error) => Err(refuse(
131                Status::GUATIAO_ERR_INTERNAL,
132                format!("{}: {error}", self.0.path.display()),
133            )),
134        }
135    }
136}
137
138fn value(model: &impl ToValue) -> Result<Value, ProviderError> {
139    model
140        .to_value()
141        .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error))
142}
143
144fn refuse(status: Status, error: impl std::fmt::Display) -> ProviderError {
145    ProviderError::new(status, &error.to_string())
146}