aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe/src/config/json_config_source.rs
blob: 264b0e1818fabb5fa30ca10dc7a686b42132e406 (plain)
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! ref: composer/src/Composer/Config/JsonConfigSource.php

use anyhow::Result;
use indexmap::IndexMap;
use shirabe_php_shim::{
    array_unshift, call_user_func_array, chmod, explode, file_get_contents, file_put_contents,
    implode, is_writable, sprintf, PhpMixed, RuntimeException, Silencer, PHP_EOL,
};

use crate::config::config_source_interface::ConfigSourceInterface;
use crate::json::json_file::JsonFile;
use crate::json::json_manipulator::JsonManipulator;
use crate::json::json_validation_exception::JsonValidationException;
use crate::util::filesystem::Filesystem;

/// JSON Configuration Source
#[derive(Debug)]
pub struct JsonConfigSource {
    /// @var JsonFile
    file: JsonFile,

    /// @var bool
    auth_config: bool,
}

impl JsonConfigSource {
    /// Constructor
    pub fn new(file: JsonFile, auth_config: bool) -> Self {
        Self { file, auth_config }
    }

    /// @param mixed ...$args
    fn manipulate_json(
        &mut self,
        method: &str,
        // TODO(phase-b): callback signature uses &mut $config (PHP reference) and variadic args
        fallback: Box<dyn Fn(&mut PhpMixed, &mut Vec<PhpMixed>)>,
        mut args: Vec<PhpMixed>,
    ) -> Result<()> {
        let contents;
        if self.file.exists() {
            if !is_writable(self.file.get_path()) {
                return Err(RuntimeException {
                    message: sprintf(
                        "The file \"%s\" is not writable.",
                        &[PhpMixed::String(self.file.get_path().to_string())],
                    ),
                    code: 0,
                }
                .into());
            }

            if !Filesystem::is_readable(self.file.get_path()) {
                return Err(RuntimeException {
                    message: sprintf(
                        "The file \"%s\" is not readable.",
                        &[PhpMixed::String(self.file.get_path().to_string())],
                    ),
                    code: 0,
                }
                .into());
            }

            contents = file_get_contents(self.file.get_path()).unwrap_or_default();
        } else if self.auth_config {
            contents = "{\n}\n".to_string();
        } else {
            contents = "{\n    \"config\": {\n    }\n}\n".to_string();
        }

        let mut manipulator = JsonManipulator::new(&contents);

        let new_file = !self.file.exists();

        // override manipulator method for auth config files
        let mut method = method.to_string();
        if self.auth_config && method == "addConfigSetting" {
            method = "addSubNode".to_string();
            let parts = explode(".", args[0].as_string().unwrap_or(""));
            let main_node = parts.get(0).cloned().unwrap_or_default();
            let name = parts.get(1).cloned().unwrap_or_default();
            args = vec![
                PhpMixed::String(main_node),
                PhpMixed::String(name),
                args[1].clone(),
            ];
        } else if self.auth_config && method == "removeConfigSetting" {
            method = "removeSubNode".to_string();
            let parts = explode(".", args[0].as_string().unwrap_or(""));
            let main_node = parts.get(0).cloned().unwrap_or_default();
            let name = parts.get(1).cloned().unwrap_or_default();
            args = vec![PhpMixed::String(main_node), PhpMixed::String(name)];
        }

        // try to update cleanly
        // PHP: call_user_func_array([$manipulator, $method], $args)
        let manipulator_result: bool = call_user_func_array(
            // TODO(phase-b): callable [manipulator, method] requires bound-method dispatch
            todo!("[manipulator, method] callable"),
            &PhpMixed::List(args.iter().map(|a| Box::new(a.clone())).collect()),
        )
        .as_bool()
        .unwrap_or(false);
        if manipulator_result {
            file_put_contents(self.file.get_path(), manipulator.get_contents().as_bytes());
        } else {
            // on failed clean update, call the fallback and rewrite the whole file
            let mut config = self.file.read()?;
            self.array_unshift_ref(&mut args, &mut config);
            fallback(&mut config, &mut args);
            // avoid ending up with arrays for keys that should be objects
            for prop in [
                "require",
                "require-dev",
                "conflict",
                "provide",
                "replace",
                "suggest",
                "config",
                "autoload",
                "autoload-dev",
                "scripts",
                "scripts-descriptions",
                "scripts-aliases",
                "support",
            ] {
                if let PhpMixed::Array(map) = &mut config {
                    if let Some(boxed) = map.get(prop) {
                        if let PhpMixed::Array(inner) = boxed.as_ref() {
                            if inner.is_empty() {
                                // PHP: $config[$prop] = new \stdClass;
                                map.insert(
                                    prop.to_string(),
                                    Box::new(PhpMixed::Array(IndexMap::new())),
                                );
                            }
                        }
                    }
                }
            }
            for prop in ["psr-0", "psr-4"] {
                if let PhpMixed::Array(map) = &mut config {
                    if let Some(autoload) = map.get_mut("autoload") {
                        if let PhpMixed::Array(autoload_map) = autoload.as_mut() {
                            if let Some(inner) = autoload_map.get(prop) {
                                if let PhpMixed::Array(inner_map) = inner.as_ref() {
                                    if inner_map.is_empty() {
                                        autoload_map.insert(
                                            prop.to_string(),
                                            Box::new(PhpMixed::Array(IndexMap::new())),
                                        );
                                    }
                                }
                            }
                        }
                    }
                    if let Some(autoload_dev) = map.get_mut("autoload-dev") {
                        if let PhpMixed::Array(autoload_dev_map) = autoload_dev.as_mut() {
                            if let Some(inner) = autoload_dev_map.get(prop) {
                                if let PhpMixed::Array(inner_map) = inner.as_ref() {
                                    if inner_map.is_empty() {
                                        autoload_dev_map.insert(
                                            prop.to_string(),
                                            Box::new(PhpMixed::Array(IndexMap::new())),
                                        );
                                    }
                                }
                            }
                        }
                    }
                }
            }
            for prop in [
                "platform",
                "http-basic",
                "bearer",
                "gitlab-token",
                "gitlab-oauth",
                "github-oauth",
                "custom-headers",
                "forgejo-token",
                "preferred-install",
            ] {
                if let PhpMixed::Array(map) = &mut config {
                    if let Some(cfg) = map.get_mut("config") {
                        if let PhpMixed::Array(cfg_map) = cfg.as_mut() {
                            if let Some(inner) = cfg_map.get(prop) {
                                if let PhpMixed::Array(inner_map) = inner.as_ref() {
                                    if inner_map.is_empty() {
                                        cfg_map.insert(
                                            prop.to_string(),
                                            Box::new(PhpMixed::Array(IndexMap::new())),
                                        );
                                    }
                                }
                            }
                        }
                    }
                }
            }
            self.file.write(config, shirabe_php_shim::JSON_UNESCAPED_SLASHES
                | shirabe_php_shim::JSON_PRETTY_PRINT
                | shirabe_php_shim::JSON_UNESCAPED_UNICODE)?;
        }

        // TODO(phase-b): use anyhow::Result<Result<T, E>> to model PHP try/catch
        match self.file.validate_schema(JsonFile::LAX_SCHEMA, None) {
            Ok(_) => {}
            Err(e) => {
                // TODO(phase-b): downcast e to JsonValidationException to match the specific catch
                let _jve: &JsonValidationException = todo!("downcast e to JsonValidationException");
                // restore contents to the original state
                file_put_contents(self.file.get_path(), contents.as_bytes());
                return Err(RuntimeException {
                    message: format!(
                        "Failed to update composer.json with a valid format, reverting to the original content. Please report an issue to us with details (command you run and a copy of your composer.json). {}{}",
                        PHP_EOL,
                        implode(PHP_EOL, todo!("e.get_errors()")),
                    ),
                    code: 0,
                }
                .into());
            }
        }

        if new_file {
            let path = self.file.get_path().to_string();
            let _ = Silencer::call(|| {
                chmod(&path, 0o600);
                Ok(())
            });
        }

        Ok(())
    }

    /// Prepend a reference to an element to the beginning of an array.
    ///
    /// @param  mixed[] $array
    /// @param  mixed $value
    fn array_unshift_ref(&self, array: &mut Vec<PhpMixed>, value: &mut PhpMixed) -> i64 {
        let return_val = array_unshift(array, PhpMixed::String(String::new()));
        // PHP: $array[0] = &$value; (PHP reference)
        // TODO(phase-b): retain reference semantics so later mutations of $value propagate
        array[0] = value.clone();

        return_val.map(|_| 0).unwrap_or(0) + array.len() as i64
    }
}

impl ConfigSourceInterface for JsonConfigSource {
    fn get_name(&self) -> String {
        self.file.get_path().to_string()
    }

    fn add_repository(
        &mut self,
        name: &str,
        config: Option<IndexMap<String, PhpMixed>>,
        append: bool,
    ) -> Result<()> {
        let name_owned = name.to_string();
        let config_owned = config.clone();
        self.manipulate_json(
            "addRepository",
            Box::new(move |cfg: &mut PhpMixed, args: &mut Vec<PhpMixed>| {
                // TODO(phase-b): port the closure body — args are [$cfg, $repo, $repoConfig, $append]
                let _ = (cfg, args);
                todo!("addRepository fallback closure body");
            }),
            vec![
                PhpMixed::String(name_owned),
                config_owned
                    .map(|m| {
                        PhpMixed::Array(m.into_iter().map(|(k, v)| (k, Box::new(v))).collect())
                    })
                    .unwrap_or(PhpMixed::Bool(false)),
                PhpMixed::Bool(append),
            ],
        )
    }

    fn insert_repository(
        &mut self,
        name: &str,
        config: Option<IndexMap<String, PhpMixed>>,
        reference_name: &str,
        offset: i64,
    ) -> Result<()> {
        let name_owned = name.to_string();
        let config_owned = config.clone();
        let reference_name_owned = reference_name.to_string();
        self.manipulate_json(
            "insertRepository",
            Box::new(move |cfg: &mut PhpMixed, args: &mut Vec<PhpMixed>| {
                // TODO(phase-b): port the closure body
                let _ = (cfg, args);
                todo!("insertRepository fallback closure body");
            }),
            vec![
                PhpMixed::String(name_owned),
                config_owned
                    .map(|m| {
                        PhpMixed::Array(m.into_iter().map(|(k, v)| (k, Box::new(v))).collect())
                    })
                    .unwrap_or(PhpMixed::Bool(false)),
                PhpMixed::String(reference_name_owned),
                PhpMixed::Int(offset),
            ],
        )
    }

    fn set_repository_url(&mut self, name: &str, url: &str) -> Result<()> {
        let _name_owned = name.to_string();
        let _url_owned = url.to_string();
        self.manipulate_json(
            "setRepositoryUrl",
            Box::new(move |cfg: &mut PhpMixed, args: &mut Vec<PhpMixed>| {
                // PHP: foreach ($config['repositories'] ?? [] as $index => $repository) { ... }
                let _ = (cfg, args);
                todo!("setRepositoryUrl fallback closure body");
            }),
            vec![PhpMixed::String(name.to_string()), PhpMixed::String(url.to_string())],
        )
    }

    fn remove_repository(&mut self, name: &str) -> Result<()> {
        self.manipulate_json(
            "removeRepository",
            Box::new(move |cfg: &mut PhpMixed, args: &mut Vec<PhpMixed>| {
                let _ = (cfg, args);
                todo!("removeRepository fallback closure body");
            }),
            vec![PhpMixed::String(name.to_string())],
        )
    }

    fn add_config_setting(&mut self, name: &str, value: PhpMixed) -> Result<()> {
        let auth_config = self.auth_config;
        self.manipulate_json(
            "addConfigSetting",
            Box::new(move |cfg: &mut PhpMixed, args: &mut Vec<PhpMixed>| {
                // PHP: [$key, $host] = explode('.', $key, 2);
                let _ = (cfg, args, auth_config);
                todo!("addConfigSetting fallback closure body");
            }),
            vec![PhpMixed::String(name.to_string()), value],
        )
    }

    fn remove_config_setting(&mut self, name: &str) -> Result<()> {
        let auth_config = self.auth_config;
        self.manipulate_json(
            "removeConfigSetting",
            Box::new(move |cfg: &mut PhpMixed, args: &mut Vec<PhpMixed>| {
                let _ = (cfg, args, auth_config);
                todo!("removeConfigSetting fallback closure body");
            }),
            vec![PhpMixed::String(name.to_string())],
        )
    }

    fn add_property(&mut self, name: &str, value: PhpMixed) -> Result<()> {
        self.manipulate_json(
            "addProperty",
            Box::new(move |cfg: &mut PhpMixed, args: &mut Vec<PhpMixed>| {
                let _ = (cfg, args);
                todo!("addProperty fallback closure body");
            }),
            vec![PhpMixed::String(name.to_string()), value],
        )
    }

    fn remove_property(&mut self, name: &str) -> Result<()> {
        self.manipulate_json(
            "removeProperty",
            Box::new(move |cfg: &mut PhpMixed, args: &mut Vec<PhpMixed>| {
                let _ = (cfg, args);
                todo!("removeProperty fallback closure body");
            }),
            vec![PhpMixed::String(name.to_string())],
        )
    }

    fn add_link(&mut self, r#type: &str, name: &str, value: &str) -> Result<()> {
        self.manipulate_json(
            "addLink",
            Box::new(move |cfg: &mut PhpMixed, args: &mut Vec<PhpMixed>| {
                // PHP: $config[$type][$name] = $value;
                let _ = (cfg, args);
                todo!("addLink fallback closure body");
            }),
            vec![
                PhpMixed::String(r#type.to_string()),
                PhpMixed::String(name.to_string()),
                PhpMixed::String(value.to_string()),
            ],
        )
    }

    fn remove_link(&mut self, r#type: &str, name: &str) -> Result<()> {
        self.manipulate_json(
            "removeSubNode",
            Box::new(move |cfg: &mut PhpMixed, args: &mut Vec<PhpMixed>| {
                // PHP: unset($config[$type][$name]);
                let _ = (cfg, args);
                todo!("removeLink fallback (unset subnode) closure body");
            }),
            vec![
                PhpMixed::String(r#type.to_string()),
                PhpMixed::String(name.to_string()),
            ],
        )?;
        self.manipulate_json(
            "removeMainKeyIfEmpty",
            Box::new(move |cfg: &mut PhpMixed, args: &mut Vec<PhpMixed>| {
                // PHP: if (0 === count($config[$type])) { unset($config[$type]); }
                let _ = (cfg, args);
                todo!("removeLink fallback (unset main key if empty) closure body");
            }),
            vec![PhpMixed::String(r#type.to_string())],
        )
    }
}