testutils.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright 2014 Mozilla Foundation
  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. "use strict";
  17. const fs = require("fs");
  18. const path = require("path");
  19. const rimrafSync = require("rimraf").sync;
  20. exports.removeDirSync = function removeDirSync(dir) {
  21. fs.readdirSync(dir); // Will throw if dir is not a directory
  22. rimrafSync(dir, {
  23. disableGlob: true,
  24. });
  25. };
  26. exports.copySubtreeSync = function copySubtreeSync(src, dest) {
  27. const files = fs.readdirSync(src);
  28. if (!fs.existsSync(dest)) {
  29. fs.mkdirSync(dest);
  30. }
  31. files.forEach(function (filename) {
  32. const srcFile = path.join(src, filename);
  33. const file = path.join(dest, filename);
  34. const stats = fs.statSync(srcFile);
  35. if (stats.isDirectory()) {
  36. copySubtreeSync(srcFile, file);
  37. } else {
  38. fs.writeFileSync(file, fs.readFileSync(srcFile));
  39. }
  40. });
  41. };
  42. exports.ensureDirSync = function ensureDirSync(dir) {
  43. if (fs.existsSync(dir)) {
  44. return;
  45. }
  46. const parts = dir.split(path.sep);
  47. let i = parts.length;
  48. while (i > 1 && !fs.existsSync(parts.slice(0, i - 1).join(path.sep))) {
  49. i--;
  50. }
  51. if (i < 0 || (i === 0 && parts[0])) {
  52. throw new Error();
  53. }
  54. while (i <= parts.length) {
  55. fs.mkdirSync(parts.slice(0, i).join(path.sep));
  56. i++;
  57. }
  58. };