swc_common/plugin/
metadata.rs1use std::env;
2
3use once_cell::sync::Lazy;
4use rustc_hash::FxHashMap;
5
6#[derive(Copy, Clone)]
12pub enum TransformPluginMetadataContextKind {
13 Filename = 1,
16 Env = 2,
17 Cwd = 3,
18}
19
20impl From<u32> for TransformPluginMetadataContextKind {
21 fn from(key: u32) -> TransformPluginMetadataContextKind {
22 match key {
23 1 => TransformPluginMetadataContextKind::Filename,
24 2 => TransformPluginMetadataContextKind::Env,
25 3 => TransformPluginMetadataContextKind::Cwd,
26 _ => panic!("Invalid TransformPluginMetadataContextKind key"),
27 }
28 }
29}
30
31pub struct TransformPluginMetadataContext {
35 pub filename: Option<String>,
38 pub env: String,
41 pub cwd: Option<String>,
43 pub experimental: FxHashMap<String, String>,
44}
45
46impl TransformPluginMetadataContext {
47 pub fn new(
48 filename: Option<String>,
49 env: String,
50 experimental: Option<FxHashMap<String, String>>,
51 ) -> Self {
52 static CWD: Lazy<Option<String>> = Lazy::new(|| {
53 env::current_dir()
54 .map(|cwd| cwd.as_path().to_string_lossy().to_string())
55 .ok()
56 });
57
58 TransformPluginMetadataContext {
59 filename,
60 env,
61 cwd: CWD.clone(),
62 experimental: experimental.unwrap_or_default(),
63 }
64 }
65
66 pub fn get(&self, key: &TransformPluginMetadataContextKind) -> Option<String> {
67 match key {
68 TransformPluginMetadataContextKind::Filename => self.filename.clone(),
69 TransformPluginMetadataContextKind::Env => Some(self.env.clone()),
70 TransformPluginMetadataContextKind::Cwd => self.cwd.clone(),
71 }
72 }
73}
74
75pub struct Context(pub FxHashMap<String, String>);
76
77#[cfg(feature = "encoding-impl")]
78impl cbor4ii::core::enc::Encode for Context {
79 #[inline]
80 fn encode<W: cbor4ii::core::enc::Write>(
81 &self,
82 writer: &mut W,
83 ) -> Result<(), cbor4ii::core::enc::Error<W::Error>> {
84 use cbor4ii::core::types;
85
86 types::Map::bounded(self.0.len(), writer)?;
87 for (k, v) in self.0.iter() {
88 k.encode(writer)?;
89 v.encode(writer)?;
90 }
91
92 Ok(())
93 }
94}
95
96#[cfg(feature = "encoding-impl")]
97impl<'de> cbor4ii::core::dec::Decode<'de> for Context {
98 #[inline]
99 fn decode<R: cbor4ii::core::dec::Read<'de>>(
100 reader: &mut R,
101 ) -> Result<Self, cbor4ii::core::dec::Error<R::Error>> {
102 use cbor4ii::core::types;
103
104 let len = types::Map::len(reader)?.ok_or_else(|| cbor4ii::core::dec::Error::Mismatch {
105 name: &"Context",
106 found: 0,
107 })?;
108 let len = std::cmp::min(len, 4096);
109 let mut map = FxHashMap::with_capacity_and_hasher(len, Default::default());
110 for _ in 0..len {
111 let k = String::decode(reader)?;
112 let v = String::decode(reader)?;
113 map.insert(k, v);
114 }
115
116 Ok(Context(map))
117 }
118}