Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

utils.js 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing,
  11. software distributed under the License is distributed on an
  12. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. KIND, either express or implied. See the License for the
  14. specific language governing permissions and limitations
  15. under the License.
  16. */
  17. /*
  18. Provides a set of utility methods, which can also be spied on during unit tests.
  19. */
  20. // TODO: Perhaps this should live in cordova-common?
  21. const fs = require('fs-extra');
  22. const { events } = require('cordova-common');
  23. /**
  24. * Reads, searches, and replaces the found occurences with replacementString and then writes the file back out.
  25. * A backup is not made.
  26. *
  27. * @param {string} file A file path to a readable & writable file
  28. * @param {RegExp} searchRegex The search regex
  29. * @param {string} replacementString The string to replace the found occurences
  30. * @returns {void}
  31. */
  32. exports.replaceFileContents = function (file, searchRegex, replacementString) {
  33. let contents;
  34. try {
  35. contents = fs.readFileSync(file).toString();
  36. } catch (ex) {
  37. events.emit('verbose', `Trying to read file: ${file}`);
  38. throw ex;
  39. }
  40. contents = contents.replace(searchRegex, replacementString);
  41. fs.writeFileSync(file, contents);
  42. };
  43. /**
  44. * Reads a file and scans for regex. Returns the line of the first occurence or null if no occurences are found.
  45. *
  46. * @param {string} file A file path
  47. * @param {RegExp} regex A search regex
  48. * @returns string|null
  49. */
  50. exports.grep = function (file, regex) {
  51. const contents = fs.readFileSync(file).toString().replace(/\\r/g, '').split('\n');
  52. for (let i = 0; i < contents.length; i++) {
  53. const line = contents[i];
  54. if (regex.test(line)) {
  55. return line;
  56. }
  57. }
  58. return null;
  59. };