fs.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. function rmDir(dirPath: string, relativeDirPath: string): boolean {
  50. let keepsFiles = false;
  51. const entries = fs.readdirSync(dirPath);
  52. for (const entry of entries) {
  53. const filePath = path.join(dirPath, entry);
  54. const relativeFilePath = path.join(relativeDirPath, entry);
  55. if (keep!(relativeFilePath)) {
  56. keepsFiles = true;
  57. continue;
  58. }
  59. if (fs.statSync(filePath).isFile()) {
  60. fs.unlinkSync(filePath);
  61. } else {
  62. keepsFiles = rmDir(filePath, relativeFilePath) || keepsFiles;
  63. }
  64. }
  65. if (!keepsFiles) {
  66. fs.rmdirSync(dirPath);
  67. }
  68. return keepsFiles;
  69. }
  70. }