| 1 | /*
|
|---|
| 2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
|---|
| 3 | Author Tobias Koppers @sokra
|
|---|
| 4 | */
|
|---|
| 5 |
|
|---|
| 6 | "use strict";
|
|---|
| 7 |
|
|---|
| 8 | /** @typedef {import("./Resolver")} Resolver */
|
|---|
| 9 | /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
|
|---|
| 10 |
|
|---|
| 11 | module.exports = class FileExistsPlugin {
|
|---|
| 12 | /**
|
|---|
| 13 | * @param {string | ResolveStepHook} source source
|
|---|
| 14 | * @param {string | ResolveStepHook} target target
|
|---|
| 15 | */
|
|---|
| 16 | constructor(source, target) {
|
|---|
| 17 | this.source = source;
|
|---|
| 18 | this.target = target;
|
|---|
| 19 | }
|
|---|
| 20 |
|
|---|
| 21 | /**
|
|---|
| 22 | * @param {Resolver} resolver the resolver
|
|---|
| 23 | * @returns {void}
|
|---|
| 24 | */
|
|---|
| 25 | apply(resolver) {
|
|---|
| 26 | const target = resolver.ensureHook(this.target);
|
|---|
| 27 | const fs = resolver.fileSystem;
|
|---|
| 28 | resolver
|
|---|
| 29 | .getHook(this.source)
|
|---|
| 30 | .tapAsync("FileExistsPlugin", (request, resolveContext, callback) => {
|
|---|
| 31 | const file = request.path;
|
|---|
| 32 | if (!file) return callback();
|
|---|
| 33 | fs.stat(file, (err, stat) => {
|
|---|
| 34 | // Combine the two miss branches: a stat failure and a
|
|---|
| 35 | // "not a file" result share the same handling — record the
|
|---|
| 36 | // path on `missingDependencies`, log the right reason, then
|
|---|
| 37 | // bail. The error-message ternary picks the wording that
|
|---|
| 38 | // matched the failing condition.
|
|---|
| 39 | if (err || !stat || !stat.isFile()) {
|
|---|
| 40 | if (resolveContext.missingDependencies) {
|
|---|
| 41 | resolveContext.missingDependencies.add(file);
|
|---|
| 42 | }
|
|---|
| 43 | if (resolveContext.log) {
|
|---|
| 44 | resolveContext.log(
|
|---|
| 45 | err || !stat
|
|---|
| 46 | ? `${file} doesn't exist`
|
|---|
| 47 | : `${file} is not a file`,
|
|---|
| 48 | );
|
|---|
| 49 | }
|
|---|
| 50 | return callback();
|
|---|
| 51 | }
|
|---|
| 52 | if (resolveContext.fileDependencies) {
|
|---|
| 53 | resolveContext.fileDependencies.add(file);
|
|---|
| 54 | }
|
|---|
| 55 | resolver.doResolve(
|
|---|
| 56 | target,
|
|---|
| 57 | request,
|
|---|
| 58 | `existing file: ${file}`,
|
|---|
| 59 | resolveContext,
|
|---|
| 60 | callback,
|
|---|
| 61 | );
|
|---|
| 62 | });
|
|---|
| 63 | });
|
|---|
| 64 | }
|
|---|
| 65 | };
|
|---|