rspack_plugin_copy 0.100.8

rspack copy plugin
Documentation
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
use std::{
  borrow::Cow,
  fmt::Display,
  hash::Hash,
  ops::DerefMut,
  path::{MAIN_SEPARATOR, Path, PathBuf},
  sync::{Arc, LazyLock, Mutex},
};

use cow_utils::CowUtils;
use derive_more::Debug;
use fast_glob::glob_match;
use futures::future::{BoxFuture, join_all};
use regex::Regex;
use rspack_core::{
  AssetInfo, AssetInfoRelated, Compilation, CompilationAsset, CompilationLogger,
  CompilationProcessAssets, Filename, GlobMatchOptions, Logger, PathData, Plugin,
  escape_glob_pattern, find_files_by_glob,
  rspack_sources::{BoxSource, RawBufferSource, Source, SourceExt},
};
use rspack_error::{Diagnostic, Error, Result};
use rspack_hash::{HashDigest, HashFunction, HashSalt, RspackHash, RspackHashDigest};
use rspack_hook::{plugin, plugin_hook};
use rspack_paths::{Utf8Path, Utf8PathBuf};
use rspack_util::fx_hash::FxDashSet;
use sugar_path::SugarPath;

#[derive(Debug)]
pub struct CopyRspackPluginOptions {
  pub patterns: Vec<CopyPattern>,
}

#[derive(Debug, Clone)]
pub struct Info {
  pub immutable: Option<bool>,
  pub minimized: Option<bool>,
  pub chunk_hash: Option<Vec<String>>,
  pub content_hash: Option<Vec<String>>,
  pub development: Option<bool>,
  pub hot_module_replacement: Option<bool>,
  pub related: Option<Related>,
  pub version: Option<String>,
}

#[derive(Debug, Clone)]
pub struct Related {
  pub source_map: Option<String>,
}

#[derive(Debug, Clone, Copy)]
pub enum FromType {
  Dir,
  File,
  Glob,
}

#[derive(Debug, Clone)]
pub enum ToType {
  Dir,
  File,
  Template,
}

impl Display for ToType {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.write_str(match self {
      ToType::Dir => "dir",
      ToType::File => "file",
      ToType::Template => "template",
    })
  }
}

pub type TransformerFn =
  Box<dyn for<'a> Fn(Vec<u8>, &'a str) -> BoxFuture<'a, Result<BoxSource>> + Sync + Send>;

pub struct ToFnCtx<'a> {
  pub context: &'a Utf8Path,
  pub absolute_filename: &'a Utf8Path,
}

pub type ToFn = Box<dyn for<'a> Fn(ToFnCtx<'a>) -> BoxFuture<'a, Result<String>> + Sync + Send>;

pub enum ToOption {
  String(String),
  Fn(ToFn),
}

#[derive(Debug)]
pub struct CopyPattern {
  pub from: String,
  #[debug(skip)]
  pub to: Option<ToOption>,
  pub context: Option<Utf8PathBuf>,
  pub to_type: Option<ToType>,
  pub no_error_on_missing: bool,
  pub info: Option<Info>,
  pub force: bool,
  pub priority: i32,
  pub glob_options: CopyGlobOptions,
  pub copy_permissions: Option<bool>,
  #[debug(skip)]
  pub transform_fn: Option<TransformerFn>,
  pub cache: Option<bool>,
}

#[derive(Debug, Clone)]
pub struct CopyGlobOptions {
  pub case_sensitive_match: Option<bool>,
  pub dot: Option<bool>,
  pub ignore: Option<Vec<String>>,
}

#[derive(Debug, Clone)]
pub struct RunPatternResult {
  pub source_filename: Utf8PathBuf,
  pub absolute_filename: Utf8PathBuf,
  pub filename: String,
  pub source: BoxSource,
  pub info: Option<Info>,
  pub force: bool,
  pub priority: i32,
  pub pattern_index: usize,
}

#[plugin]
#[derive(Debug)]
pub struct CopyRspackPlugin {
  pub patterns: Vec<CopyPattern>,
}

static TEMPLATE_RE: LazyLock<Regex> =
  LazyLock::new(|| Regex::new(r"\[\\*([\w:]+)\\*\]").expect("This never fail"));

fn normalize_glob_path_separators(path: &str) -> Cow<'_, str> {
  if cfg!(windows) {
    path.cow_replace('\\', "/")
  } else {
    Cow::Borrowed(path)
  }
}

impl CopyRspackPlugin {
  pub fn new(patterns: Vec<CopyPattern>) -> Self {
    Self::new_inner(patterns)
  }

  fn get_content_hash(
    source: &BoxSource,
    function: &HashFunction,
    digest: &HashDigest,
    salt: &HashSalt,
  ) -> RspackHashDigest {
    let mut hasher = RspackHash::with_salt(function, salt);
    source.buffer().hash(&mut hasher);
    hasher.digest(digest)
  }

  #[allow(clippy::too_many_arguments)]
  async fn analyze_every_entry(
    entry: Utf8PathBuf,
    pattern: &CopyPattern,
    context: &Utf8Path,
    output_path: &Utf8Path,
    from_type: FromType,
    file_dependencies: &FxDashSet<PathBuf>,
    diagnostics: Arc<Mutex<Vec<Diagnostic>>>,
    compilation: &Compilation,
    logger: &CompilationLogger,
    pattern_index: usize,
  ) -> Result<Option<RunPatternResult>> {
    // Exclude directories
    if entry.is_dir() {
      return Ok(None);
    }
    if let Some(ignore) = &pattern.glob_options.ignore
      && ignore
        .iter()
        .any(|ignore| glob_match(ignore.as_bytes(), entry.as_str().as_bytes()))
    {
      return Ok(None);
    }

    let from = entry;

    logger.debug(format!("found '{from}'"));

    let absolute_filename = if from.is_absolute() {
      from.clone()
    } else {
      context.join(&from)
    };

    let to = if let Some(to) = pattern.to.as_ref() {
      let to = match to {
        ToOption::String(s) => s.to_owned(),
        ToOption::Fn(r) => {
          let result = r(ToFnCtx {
            context,
            absolute_filename: &absolute_filename,
          })
          .await;

          match result {
            Ok(to) => to,
            Err(e) => {
              diagnostics
                .lock()
                .expect("failed to obtain lock of `diagnostics`")
                .push(Diagnostic::error(
                  "Run copy to fn error".into(),
                  e.to_string(),
                ));
              String::new()
            }
          }
        }
      };

      to.as_path().normalize().to_string_lossy().to_string()
    } else {
      String::new()
    };

    let to_type = if let Some(to_type) = pattern.to_type.as_ref() {
      to_type.clone()
    } else if TEMPLATE_RE.is_match(&to) {
      ToType::Template
    } else if Path::new(&to).extension().is_none() || to.ends_with(MAIN_SEPARATOR) {
      ToType::Dir
    } else {
      ToType::File
    };

    logger.log(format!("'to' option '{to}' determined as '{to_type}'"));

    let relative = pathdiff::diff_utf8_paths(&absolute_filename, context);
    let filename = if matches!(to_type, ToType::Dir) {
      if let Some(relative) = &relative {
        Utf8PathBuf::from(&to).join(relative)
      } else {
        to.into()
      }
    } else {
      to.into()
    };

    let filename = if filename.is_absolute() {
      if let Some(filename) = pathdiff::diff_utf8_paths(filename, output_path) {
        filename
      } else {
        return Ok(None);
      }
    } else {
      filename
    };

    logger.log(format!(
      "determined that '{from}' should write to '{filename}'"
    ));

    let Some(source_filename) = relative else {
      return Ok(None);
    };

    // If this came from a glob or dir, add it to the file dependencies
    if matches!(from_type, FromType::Dir | FromType::Glob) {
      logger.debug(format!("added '{absolute_filename}' as a file dependency",));

      file_dependencies.insert(
        absolute_filename
          .to_path_buf()
          .into_std_path_buf()
          .normalize()
          .into_owned(),
      );
    }

    // TODO cache

    logger.debug(format!("reading '{absolute_filename}'..."));
    // TODO inputFileSystem

    let data = compilation.input_filesystem.read(&absolute_filename).await;

    let source_vec = match data {
      Ok(data) => {
        logger.debug(format!("read '{absolute_filename}'..."));

        data
      }
      Err(e) => {
        let e: Error = e.into();
        diagnostics
          .lock()
          .expect("failed to obtain lock of `diagnostics`")
          .push(e.into());
        return Ok(None);
      }
    };

    let mut source = RawBufferSource::from(source_vec.clone()).boxed();

    if let Some(transformer) = &pattern.transform_fn {
      logger.debug(format!("transforming content for '{absolute_filename}'..."));
      // TODO: support cache in the future.
      handle_transform(
        transformer,
        source_vec,
        absolute_filename.clone(),
        &mut source,
        diagnostics,
      )
      .await
    }

    let filename = if matches!(&to_type, ToType::Template) {
      logger.log(format!(
        "interpolating template '{filename}' for '${source_filename}'...`"
      ));

      let content_hash = Self::get_content_hash(
        &source,
        &compilation.options.output.hash_function,
        &compilation.options.output.hash_digest,
        &compilation.options.output.hash_salt,
      );
      let content_hash = content_hash.rendered(compilation.options.output.hash_digest_length);
      let template_str = compilation
        .get_asset_path(
          &Filename::from(filename.to_string()),
          PathData::default()
            .filename(source_filename.as_str())
            .content_hash(content_hash)
            .hash_optional(compilation.get_hash()),
        )
        .await?;

      logger.log(format!(
        "interpolated template '{template_str}' for '{filename}'"
      ));

      template_str
    } else {
      filename.as_str().normalize().to_string_lossy().to_string()
    };

    Ok(Some(RunPatternResult {
      source_filename,
      absolute_filename,
      filename,
      source,
      info: pattern.info.clone(),
      force: pattern.force,
      priority: pattern.priority,
      pattern_index,
    }))
  }

  async fn run_patter(
    compilation: &Compilation,
    pattern: &CopyPattern,
    index: usize,
    file_dependencies: &FxDashSet<PathBuf>,
    context_dependencies: &FxDashSet<PathBuf>,
    diagnostics: Arc<Mutex<Vec<Diagnostic>>>,
    logger: &CompilationLogger,
  ) -> Result<Option<Vec<Option<RunPatternResult>>>> {
    let orig_from = &pattern.from;
    let normalized_orig_from = Utf8PathBuf::from(orig_from);

    let pattern_context = if pattern.context.is_none() {
      Some(Cow::Borrowed(compilation.options.context.as_path()))
    } else if let Some(ref ctx) = pattern.context
      && !ctx.is_absolute()
    {
      Some(Cow::Owned(compilation.options.context.as_path().join(ctx)))
    } else {
      pattern.context.as_deref().map(Into::into)
    };

    logger.log(format!(
      "starting to process a pattern from '{normalized_orig_from}' using '{pattern_context:?}' context"
    ));

    let mut context =
      pattern_context.unwrap_or_else(|| Cow::Borrowed(compilation.options.context.as_path()));

    let abs_from = if normalized_orig_from.is_absolute() {
      normalized_orig_from
    } else {
      context.join(&normalized_orig_from)
    };

    logger.debug(format!("getting stats for '{abs_from}'..."));

    let from_type = if let Ok(meta) = compilation.input_filesystem.metadata(&abs_from).await {
      if meta.is_directory {
        logger.debug(format!("determined '{abs_from}' is a directory"));
        FromType::Dir
      } else if meta.is_file {
        logger.debug(format!("determined '{abs_from}' is a file"));
        FromType::File
      } else {
        logger.debug(format!("determined '{abs_from}' is a unknown"));
        FromType::Glob
      }
    } else {
      logger.debug(format!("determined '{abs_from}' is a glob"));
      FromType::Glob
    };

    // Enable copy files starts with dot
    let mut dot_enable = pattern.glob_options.dot;

    /*
     * If input is a glob query like `/a/b/**/*.js`, we need to add common directory
     * to context_dependencies
     */
    let mut need_add_context_to_dependency = false;
    let glob_query = match from_type {
      FromType::Dir => {
        logger.debug(format!("added '{abs_from}' as a context dependency"));
        context_dependencies.insert(abs_from.clone().into_std_path_buf());
        context = abs_from.as_path().into();

        if dot_enable.is_none() {
          dot_enable = Some(true);
        }
        let from = normalize_glob_path_separators(abs_from.as_str());
        let escaped = escape_glob_pattern(&from);
        format!("{}/**/*", escaped.trim_end_matches('/'))
      }
      FromType::File => {
        logger.debug(format!("added '{abs_from}' as a file dependency"));
        file_dependencies.insert(
          abs_from
            .clone()
            .into_std_path_buf()
            .normalize()
            .into_owned(),
        );
        context = abs_from.parent().unwrap_or(Utf8Path::new("")).into();

        if dot_enable.is_none() {
          dot_enable = Some(true);
        }

        let from = normalize_glob_path_separators(abs_from.as_str());
        escape_glob_pattern(&from)
      }
      FromType::Glob => {
        need_add_context_to_dependency = true;
        let mut glob_query = if Path::new(orig_from).is_absolute() {
          orig_from.into()
        } else {
          context.join(orig_from).as_str().to_string()
        };
        if cfg!(windows) {
          glob_query = glob_query.cow_replace('\\', "/").into_owned();
        }
        // A glob pattern ending with /** should match all files within a directory, not just the directory itself.
        // Since the standard glob only matches directories, we append /* to align with webpack's behavior.
        if glob_query.ends_with("/**") {
          format!("{glob_query}/*")
        } else {
          glob_query
        }
      }
    };

    logger.log(format!("begin globbing '{glob_query}'..."));

    let glob_match_options = GlobMatchOptions {
      case_sensitive: pattern.glob_options.case_sensitive_match.unwrap_or(true),
      require_literal_leading_dot: !dot_enable.unwrap_or(false),
    };

    let glob_entries = find_files_by_glob(
      &glob_query,
      &glob_match_options,
      compilation.input_filesystem.clone(),
    )
    .await;

    match glob_entries {
      Ok(entries) => {
        let entries: Vec<_> = entries
          .into_iter()
          .filter(|entry| {
            if let Some(filters) = &pattern.glob_options.ignore {
              // If filters length is 0, exist is true by default
              filters
                .iter()
                .all(|filter| !glob_match(filter.as_bytes(), entry.as_str().as_bytes()))
            } else {
              true
            }
          })
          .collect();

        if need_add_context_to_dependency
          && let Some(common_dir) = get_closest_common_parent_dir(
            &entries.iter().map(|it| it.as_path()).collect::<Vec<_>>(),
          )
        {
          // The glob common dir is derived from glob-matched entries, which keep
          // the pattern's raw shape (e.g. a leading `./`, and `/` separators on
          // Windows). Normalize it so the registered context dependency matches
          // the native, normalized paths used everywhere else in the dep graph.
          context_dependencies.insert(common_dir.into_std_path_buf().normalize().into_owned());
        }

        if entries.is_empty() {
          if pattern.no_error_on_missing {
            logger.log(
              "finished to process a pattern from '${normalizedOriginalFrom}' using '${pattern.context}' context to '${pattern.to}'"
            );
            return Ok(None);
          }

          diagnostics
            .lock()
            .expect("failed to obtain lock of `diagnostics`")
            .push(Diagnostic::error(
              "CopyRspackPlugin Error".into(),
              format!("unable to locate '{glob_query}' glob"),
            ));
        }

        let output_path = &compilation.options.output.path;

        let copied_result = join_all(entries.into_iter().map(|entry| async {
          Self::analyze_every_entry(
            entry,
            pattern,
            &context,
            output_path,
            from_type,
            file_dependencies,
            diagnostics.clone(),
            compilation,
            logger,
            index,
          )
          .await
        }))
        .await
        .into_iter()
        .collect::<Result<Vec<_>>>()?;

        if copied_result.is_empty() {
          if pattern.no_error_on_missing {
            return Ok(None);
          }

          // TODO err handler
          diagnostics
            .lock()
            .expect("failed to obtain lock of `diagnostics`")
            .push(Diagnostic::error(
              "CopyRspackPlugin Error".into(),
              format!("unable to locate '{glob_query}' glob"),
            ));
          return Ok(None);
        }

        Ok(Some(copied_result))
      }
      Err(e) => {
        if pattern.no_error_on_missing {
          let to = if let Some(to) = &pattern.to {
            match to {
              ToOption::String(s) => s,
              ToOption::Fn(_) => "",
            }
          } else {
            ""
          };

          logger.log(format!(
            "finished to process a pattern from '{}' using '{}' context to '{:?}'",
            Utf8PathBuf::from(orig_from),
            context,
            to,
          ));

          return Ok(None);
        }

        diagnostics
          .lock()
          .expect("failed to obtain lock of `diagnostics`")
          .push(Diagnostic::error("Glob Error".into(), e.to_string()));

        Ok(None)
      }
    }
  }
}

#[plugin_hook(CompilationProcessAssets for CopyRspackPlugin, stage = Compilation::PROCESS_ASSETS_STAGE_ADDITIONAL)]
async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> {
  let logger = compilation.get_logger("rspack.CopyRspackPlugin");
  let start = logger.time("run pattern");
  let file_dependencies = FxDashSet::default();
  let context_dependencies = FxDashSet::default();
  let diagnostics = Arc::new(Mutex::new(Vec::new()));

  let mut copied_result: Vec<(i32, RunPatternResult)> =
    join_all(self.patterns.iter().enumerate().map(|(index, pattern)| {
      CopyRspackPlugin::run_patter(
        compilation,
        pattern,
        index,
        &file_dependencies,
        &context_dependencies,
        diagnostics.clone(),
        &logger,
      )
    }))
    .await
    .into_iter()
    .collect::<Result<Vec<_>>>()?
    .into_iter()
    .flatten()
    .flat_map(|item| {
      item
        .into_iter()
        .flatten()
        .map(|item| (item.priority, item))
        .collect::<Vec<_>>()
    })
    .collect();
  logger.time_end(start);

  let start = logger.time("emit assets");
  compilation
    .file_dependencies
    .extend(file_dependencies.into_iter().map(Into::into));
  compilation
    .context_dependencies
    .extend(context_dependencies.into_iter().map(Into::into));
  compilation.extend_diagnostics(std::mem::take(
    diagnostics
      .lock()
      .expect("failed to obtain lock of `diagnostics`")
      .deref_mut(),
  ));

  copied_result.sort_unstable_by_key(|a| a.0);

  // Keep track of source to destination file mappings for permission copying
  let mut permission_copies = Vec::new();

  copied_result.into_iter().for_each(|(_priority, result)| {
    let source_path = result.absolute_filename.clone();
    let dest_path = compilation.options.output.path.join(&result.filename);

    if let Some(exist_asset) = compilation.assets_mut().get_mut(&result.filename) {
      if !result.force {
        return;
      }
      exist_asset.set_source(Some(Arc::new(result.source)));
      if let Some(info) = result.info {
        set_info(&mut exist_asset.info, info);
      }
      exist_asset.info.source_filename = Some(result.source_filename.to_string());
      exist_asset.info.copied = Some(true);
    } else {
      let mut asset_info = AssetInfo {
        source_filename: Some(result.source_filename.to_string()),
        copied: Some(true),
        ..Default::default()
      };

      if let Some(info) = result.info {
        set_info(&mut asset_info, info);
      }

      compilation.emit_asset(
        result.filename,
        CompilationAsset::new(Some(Arc::new(result.source)), asset_info),
      );
    }

    // Store the paths for permission copying along with the pattern index
    permission_copies.push((result.pattern_index, source_path, dest_path));
  });
  logger.time_end(start);

  // Handle permission copying after all assets are emitted
  for (pattern_index, source_path, dest_path) in permission_copies.iter() {
    if let Some(pattern) = self.patterns.get(*pattern_index)
      && pattern.copy_permissions.unwrap_or(false)
      && let Ok(Some(permissions)) = compilation.input_filesystem.permissions(source_path).await
    {
      // Make sure the output directory exists
      if let Some(parent) = dest_path.parent() {
        compilation
          .output_filesystem
          .create_dir_all(parent)
          .await
          .unwrap_or_else(|e| {
            logger.warn(format!("Failed to create directory {parent:?}: {e}"));
          });
      }

      // Make sure the file exists before trying to set permissions
      if !dest_path.exists() {
        logger.warn(format!(
          "Destination file {dest_path:?} does not exist, cannot copy permissions"
        ));
        continue;
      }

      if let Err(e) = compilation
        .output_filesystem
        .set_permissions(dest_path, permissions)
        .await
      {
        logger.warn(format!(
          "Failed to copy permissions from {source_path:?} to {dest_path:?}: {e}"
        ));
      } else {
        logger.log(format!(
          "Successfully copied permissions from {source_path:?} to {dest_path:?}"
        ));
      }
    }
  }

  Ok(())
}

impl Plugin for CopyRspackPlugin {
  fn apply(&self, ctx: &mut rspack_core::ApplyContext<'_>) -> Result<()> {
    ctx
      .compilation_hooks
      .process_assets
      .tap(process_assets::new(self));
    Ok(())
  }
}

fn get_closest_common_parent_dir(paths: &[&Utf8Path]) -> Option<Utf8PathBuf> {
  // If there are no matching files, return `None`.
  if paths.is_empty() {
    return None;
  }

  // Get the first file path and use it as the initial value for the common parent directory.
  let mut parent_dir: Utf8PathBuf = paths[0].parent()?.to_path_buf();

  // Iterate over the remaining file paths, updating the common parent directory as necessary.
  for path in paths.iter().skip(1) {
    // Find the common parent directory between the current file path and the previous common parent directory.
    while !path.starts_with(&parent_dir) {
      parent_dir = parent_dir.parent()?.into();
    }
  }

  Some(parent_dir)
}

fn set_info(target: &mut AssetInfo, info: Info) {
  if let Some(minimized) = info.minimized {
    target.minimized.replace(minimized);
  }

  if let Some(immutable) = info.immutable {
    target.immutable.replace(immutable);
  }

  if let Some(chunk_hash) = info.chunk_hash {
    target.chunk_hash = rustc_hash::FxHashSet::from_iter(chunk_hash);
  }

  if let Some(content_hash) = info.content_hash {
    target.content_hash = rustc_hash::FxHashSet::from_iter(content_hash);
  }

  if let Some(development) = info.development {
    target.development.replace(development);
  }

  if let Some(hot_module_replacement) = info.hot_module_replacement {
    target
      .hot_module_replacement
      .replace(hot_module_replacement);
  }

  if let Some(related) = info.related {
    target.related = AssetInfoRelated {
      source_map: related.source_map,
    };
  }

  if let Some(version) = info.version {
    target.version = version;
  }
}

async fn handle_transform(
  transformer: &TransformerFn,
  source_vec: Vec<u8>,
  absolute_filename: Utf8PathBuf,
  source: &mut BoxSource,
  diagnostics: Arc<Mutex<Vec<Diagnostic>>>,
) {
  match transformer(source_vec, absolute_filename.as_str()).await {
    Ok(code) => {
      *source = code;
    }
    Err(e) => {
      diagnostics
        .lock()
        .expect("failed to obtain lock of `diagnostics`")
        .push(Diagnostic::error(
          "Run copy transform fn error".into(),
          e.to_string(),
        ));
    }
  }
}

// If this test fails, you should modify `set_info` function, according to your changes about AssetInfo
// Make sure every field of AssetInfo is considered
#[test]
fn ensure_info_fields() {
  let info = AssetInfo::default();
  std::hint::black_box(info);
}