testUtils.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /*
  2. * Copyright (c) 2015, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. *
  9. */
  10. 'use strict';
  11. const fs = require('fs');
  12. const mkdirp = require('mkdirp');
  13. const path = require('path');
  14. const temp = require('temp');
  15. function renameFileTo(oldPath, newFilename) {
  16. const projectPath = path.dirname(oldPath);
  17. const newPath = path.join(projectPath, newFilename);
  18. mkdirp.sync(path.dirname(newPath));
  19. fs.renameSync(oldPath, newPath);
  20. return newPath;
  21. }
  22. function createTempFileWith(content, filename) {
  23. const info = temp.openSync();
  24. let filePath = info.path;
  25. fs.writeSync(info.fd, content);
  26. fs.closeSync(info.fd);
  27. if (filename) {
  28. filePath = renameFileTo(filePath, filename);
  29. }
  30. return filePath;
  31. }
  32. exports.createTempFileWith = createTempFileWith;
  33. function createTransformWith(content, fileName) {
  34. return createTempFileWith(
  35. 'module.exports = function(fileInfo, api, options) { ' + content + ' }',
  36. fileName
  37. );
  38. }
  39. exports.createTransformWith = createTransformWith;
  40. function getFileContent(filePath) {
  41. return fs.readFileSync(filePath).toString();
  42. }
  43. exports.getFileContent = getFileContent;