webpack_stats/
lib.rs

1/*
2 * Copyright [2022] [Kevin Velasco]
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17extern crate core;
18
19// # Webpack stats
20mod common;
21pub(crate) mod rc;
22
23pub use common::*;
24use std::borrow::Cow;
25
26#[cfg(feature = "v5")]
27pub mod v5;
28
29#[derive(serde::Deserialize)]
30pub struct Version<'a> {
31    pub version: Cow<'a, str>,
32}
33
34pub enum WebpackStats<'a> {
35    #[cfg(feature = "v5")]
36    V5(v5::Stats<'a>),
37}
38
39use thiserror::Error;
40
41#[derive(Error, Debug)]
42pub enum DeserializationError {
43    #[error("Could not get version number from json")]
44    VersionDeserializationError,
45    #[error("Could not deserialize stats file: {0}")]
46    StatsDeserializationError(#[from] serde_json::Error),
47    #[error("Unsupported webpack stats version.")]
48    UnsupportedVersion,
49}
50
51pub fn deserialize_any_version<'a>(
52    source: &'a str,
53) -> Result<WebpackStats<'a>, DeserializationError> {
54    // get a version
55    let version: Version<'a> = serde_json::from_str(source)
56        .map_err(|_| DeserializationError::VersionDeserializationError)?;
57
58    let version_major = version
59        .version
60        .trim()
61        .chars()
62        .next()
63        .ok_or(DeserializationError::VersionDeserializationError)?;
64
65    match version_major {
66        #[cfg(feature = "v5")]
67        '5' => Ok(WebpackStats::V5(serde_json::from_str(source)?)),
68        _ => Err(DeserializationError::UnsupportedVersion),
69    }
70}