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
//! The module implements configuration-related utilities and structures.

use crate::utils::IdMap;
use anyhow::{bail, Context, Error};
use serde::{Deserialize, Serialize};
use std::{
    collections::HashMap,
    fs::read_to_string,
    path::{Path, PathBuf},
};

/// The collection of widget configurations or errors.
pub(crate) type WidgetConfigCollection = IdMap<Result<WidgetConfig, String>>;

/// Full configuration of a widget.
#[derive(Clone, Serialize)]
#[cfg_attr(test, derive(PartialEq, Debug))]
#[serde(rename_all = "camelCase")]
pub(crate) struct WidgetConfig {
    /// Deskulpt configuration [`DeskulptConf`].
    pub(crate) deskulpt_conf: DeskulptConf,
    /// External dependencies, empty if None.
    pub(crate) external_deps: HashMap<String, String>,
    /// Absolute path to the widget directory.
    ///
    /// It is absolute so that we do not need to query the widget base directory state
    /// [`crate::states::WidgetBaseDirectoryState`] and call join to be able to obtain
    /// the absolute path.
    pub(crate) directory: PathBuf,
}

/// Deskulpt configuration of a widget, corresponding to `deskulpt.conf.json`.
#[derive(Clone, Deserialize, Serialize)]
#[cfg_attr(test, derive(PartialEq, Debug))]
pub(crate) struct DeskulptConf {
    /// The name of the widget.
    pub(crate) name: String,
    /// The entry file of the widget, relative to the widget directory.
    pub(crate) entry: String,
    /// Whether to ignore the widget.
    ///
    /// Setting this to `true` will exclude the widget from the widget collection.
    pub(crate) ignore: bool,
}

#[derive(Deserialize)]
struct PackageJson {
    dependencies: Option<HashMap<String, String>>,
}

/// Read a widget directory into a widget configuration.
///
/// This function reads the `deskulpt.conf.json` file and optionally the `package.json`
/// file in the given widget directory `path`.
///
/// If widget configuration is loaded successfully, it will return `Ok(Some(config))`.
/// If the directory does not represent a widget that is meant to be rendered, it will
/// return `Ok(None)`. Any failure to load the configuration will return an error.
///
/// The cases where a directory is not meant to be rendered include:
/// - `deskulpt.conf.json` is not found.
/// - The `ignore` flag in `deskulpt.conf.json` is set to `true`.
pub(crate) fn read_widget_config(path: &Path) -> Result<Option<WidgetConfig>, Error> {
    if !path.is_absolute() || !path.is_dir() {
        // We require absolute path because it will be directly used as the widget
        // directory in the configuration; there is no need to check path existence
        // because `is_dir` already does that
        bail!(
            "Absolute path to an existing directory is expected; got: {}",
            path.display()
        );
    }

    let deskulpt_conf_path = path.join("deskulpt.conf.json");
    let deskulpt_conf_str = match read_to_string(deskulpt_conf_path) {
        Ok(deskulpt_conf_str) => deskulpt_conf_str,
        Err(e) => {
            match e.kind() {
                // If the configuration file is not found we consider it not a widget
                // and ignore it without raising an error; in other cases, we do find
                // the configuration file but failed to read it, thus the error
                std::io::ErrorKind::NotFound => return Ok(None),
                _ => return Err(e).context("Failed to read deskulpt.conf.json"),
            }
        },
    };
    let deskulpt_conf: DeskulptConf = serde_json::from_str(&deskulpt_conf_str)
        .context("Failed to interpret deskulpt.conf.json")?;

    // Respect the `ignore` flag in configuration
    if deskulpt_conf.ignore {
        return Ok(None);
    }

    let package_json_path = path.join("package.json");
    let external_deps = if package_json_path.exists() {
        let package_json_str =
            read_to_string(package_json_path).context("Failed to read package.json")?;
        let package_json: PackageJson = serde_json::from_str(&package_json_str)
            .context("Failed to interpret package.json")?;
        package_json.dependencies.unwrap_or_default()
    } else {
        Default::default()
    };

    Ok(Some(WidgetConfig {
        directory: path.to_path_buf(),
        deskulpt_conf,
        external_deps,
    }))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testing::{assert_err_eq, ChainReason};
    use path_clean::PathClean;
    use pretty_assertions::assert_eq;
    use rstest::rstest;
    use std::env::current_dir;

    /// Get the absolute path to the fixture directory.
    fn fixture_dir() -> PathBuf {
        current_dir().unwrap().join("tests/fixtures/config").clean()
    }

    /// Get the standard Deskulpt configuration.
    fn get_standard_deskulpt_conf() -> DeskulptConf {
        DeskulptConf {
            name: "sample".to_string(),
            entry: "index.jsx".to_string(),
            ignore: false,
        }
    }

    #[rstest]
    // A standard configuration with both `deskulpt.conf.json` and `package.json`
    #[case::standard(
        fixture_dir().join("standard"),
        Some(WidgetConfig {
            directory: fixture_dir().join("standard"),
            deskulpt_conf: get_standard_deskulpt_conf(),
            external_deps: [("express".to_string(), "^4.17.1".to_string())].into(),
        }),
    )]
    // A standard configuration with `deskulpt.conf.json` but no `package.json`
    #[case::no_package_json(
        fixture_dir().join("no_package_json"),
        Some(WidgetConfig {
            directory: fixture_dir().join("no_package_json"),
            deskulpt_conf: get_standard_deskulpt_conf(),
            external_deps: HashMap::new(),
        }),
    )]
    // `package.json` does not contain `dependencies` field
    #[case::package_json_no_dependencies(
        fixture_dir().join("package_json_no_dependencies"),
        Some(WidgetConfig {
            directory: fixture_dir().join("package_json_no_dependencies"),
            deskulpt_conf: get_standard_deskulpt_conf(),
            external_deps: HashMap::new(),
        }),
    )]
    // No configuration file, should not be treated as a widget
    #[case::no_conf(fixture_dir().join("no_conf"), None)]
    // Widget is explicitly ignored
    #[case::ignore_true(fixture_dir().join("ignore_true"), None)]
    fn test_read_ok(
        #[case] path: PathBuf,
        #[case] expected_config: Option<WidgetConfig>,
    ) {
        let result = read_widget_config(&path)
            .expect("Expected successful read of widget configuration");
        assert_eq!(result, expected_config);
    }

    #[rstest]
    // Input path is not absolute
    #[case::not_absolute(
        "tests/fixtures/config/not_absolute",
        vec![ChainReason::Exact(
            "Absolute path to an existing directory is expected; got: \
            tests/fixtures/config/not_absolute".to_string()
        )],
    )]
    // Input path is not a directory
    #[case::not_dir(
        fixture_dir().join("not_a_directory"),
        vec![ChainReason::Exact(format!(
            "Absolute path to an existing directory is expected; got: {}",
            fixture_dir().join("not_a_directory").display(),
        ))],
    )]
    // Input path does not exist
    #[case::non_existent(
        fixture_dir().join("non_existent"),
        vec![ChainReason::Exact(format!(
            "Absolute path to an existing directory is expected; got: {}",
            fixture_dir().join("non_existent").display(),
        ))],
    )]
    // `deskulpt.conf.json` is not readable (is a directory)
    #[case::conf_not_readable(
        fixture_dir().join("conf_not_readable"),
        vec![
            ChainReason::Exact("Failed to read deskulpt.conf.json".to_string()),
            ChainReason::IOError,
        ],
    )]
    // `deskulpt.conf.json` is missing a field
    #[case::conf_missing_field(
        fixture_dir().join("conf_missing_field"),
        vec![
            ChainReason::Exact("Failed to interpret deskulpt.conf.json".to_string()),
            ChainReason::SerdeError,
        ],
    )]
    // `package.json` is not readable (is a directory)
    #[case::package_json_not_readable(
        fixture_dir().join("package_json_not_readable"),
        vec![
            ChainReason::Exact("Failed to read package.json".to_string()),
            ChainReason::IOError,
        ],
    )]
    fn test_read_error(
        #[case] path: PathBuf,
        #[case] expected_error: Vec<ChainReason>,
    ) {
        let error = read_widget_config(&path)
            .expect_err("Expected an error reading widget configuration");
        assert_err_eq(error, expected_error);
    }
}