1
0

fs.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. import * as fs from 'fs';
  6. import * as path from 'path';
  7. const REPO_ROOT = path.join(__dirname, '../');
  8. const existingDirCache = new Set();
  9. export function ensureDir(dirname: string) {
  10. /** @type {string[]} */
  11. const dirs = [];
  12. while (dirname.length > REPO_ROOT.length) {
  13. dirs.push(dirname);
  14. dirname = path.dirname(dirname);
  15. }
  16. dirs.reverse();
  17. dirs.forEach((dir) => {
  18. if (!existingDirCache.has(dir)) {
  19. try {
  20. fs.mkdirSync(dir);
  21. } catch (err) {}
  22. existingDirCache.add(dir);
  23. }
  24. });
  25. }
  26. /**
  27. * Copy a file.
  28. */
  29. export function copyFile(_source: string, _destination: string) {
  30. const source = path.join(REPO_ROOT, _source);
  31. const destination = path.join(REPO_ROOT, _destination);
  32. ensureDir(path.dirname(destination));
  33. fs.writeFileSync(destination, fs.readFileSync(source));
  34. console.log(`Copied ${_source} to ${_destination}`);
  35. }
  36. /**
  37. * Remove a directory and all its contents.
  38. */
  39. export function removeDir(_dirPath: string, keep?: (filename: string) => boolean) {
  40. if (typeof keep === 'undefined') {
  41. keep = () => false;
  42. }
  43. const dirPath = path.join(REPO_ROOT, _dirPath);
  44. if (!fs.existsSync(dirPath)) {
  45. return;
  46. }
  47. rmDir(dirPath, _dirPath);
  48. console.log(`Deleted ${_dirPath}`);
  49. /**
  50. * @param {string} dirPath
  51. * @param {string} relativeDirPath
  52. * @returns {boolean}
  53. */
  54. function rmDir(dirPath, relativeDirPath) {
  55. let keepsFiles = false;
  56. const entries = fs.readdirSync(dirPath);
  57. for (const entry of entries) {
  58. const filePath = path.join(dirPath, entry);
  59. const relativeFilePath = path.join(relativeDirPath, entry);
  60. if (keep(relativeFilePath)) {
  61. keepsFiles = true;
  62. continue;
  63. }
  64. if (fs.statSync(filePath).isFile()) {
  65. fs.unlinkSync(filePath);
  66. } else {
  67. keepsFiles = rmDir(filePath, relativeFilePath) || keepsFiles;
  68. }
  69. }
  70. if (!keepsFiles) {
  71. fs.rmdirSync(dirPath);
  72. }
  73. return keepsFiles;
  74. }
  75. }