aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe/src/package/loader/json_loader.rs
blob: 5f8cc4fda19ed4276bbb00d8d0bb43c2b94fb1ce (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
//! ref: composer/src/Composer/Package/Loader/JsonLoader.php

use crate::json::JsonFile;
use crate::package::PackageInterfaceHandle;
use crate::package::loader::LoaderInterface;
use anyhow::Result;
use std::path::Path;

pub enum JsonLoaderInput {
    File(JsonFile),
    String(String),
}

pub struct JsonLoader {
    loader: Box<dyn LoaderInterface>,
}

impl JsonLoader {
    pub fn new(loader: Box<dyn LoaderInterface>) -> Self {
        Self { loader }
    }

    pub fn load(&self, json: JsonLoaderInput) -> Result<PackageInterfaceHandle> {
        let config = match json {
            JsonLoaderInput::File(mut json_file) => json_file.read()?,
            JsonLoaderInput::String(ref s) if Path::new(s).exists() => {
                let contents = std::fs::read_to_string(s)?;
                JsonFile::parse_json(Some(&contents), Some(s))?
            }
            JsonLoaderInput::String(ref s) => JsonFile::parse_json(Some(s), None)?,
        };

        // TODO(phase-b): JsonFile::parse_json returns PhpMixed; loader::load expects IndexMap
        let _ = config;
        self.loader.load(indexmap::IndexMap::new(), None)
    }
}