log.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import {inspect} from 'node:util';
  2. import {escapeLines} from '../arguments/escape.js';
  3. import {defaultVerboseFunction} from './default.js';
  4. import {applyVerboseOnLines} from './custom.js';
  5. // This prints on stderr.
  6. // If the subprocess prints on stdout and is using `stdout: 'inherit'`,
  7. // there is a chance both writes will compete (introducing a race condition).
  8. // This means their respective order is not deterministic.
  9. // In particular, this means the verbose command lines might be after the start of the subprocess output.
  10. // Using synchronous I/O does not solve this problem.
  11. // However, this only seems to happen when the stdout/stderr target
  12. // (e.g. a terminal) is being written to by many subprocesses at once, which is unlikely in real scenarios.
  13. export const verboseLog = ({type, verboseMessage, fdNumber, verboseInfo, result}) => {
  14. const verboseObject = getVerboseObject({type, result, verboseInfo});
  15. const printedLines = getPrintedLines(verboseMessage, verboseObject);
  16. const finalLines = applyVerboseOnLines(printedLines, verboseInfo, fdNumber);
  17. if (finalLines !== '') {
  18. console.warn(finalLines.slice(0, -1));
  19. }
  20. };
  21. const getVerboseObject = ({
  22. type,
  23. result,
  24. verboseInfo: {escapedCommand, commandId, rawOptions: {piped = false, ...options}},
  25. }) => ({
  26. type,
  27. escapedCommand,
  28. commandId: `${commandId}`,
  29. timestamp: new Date(),
  30. piped,
  31. result,
  32. options,
  33. });
  34. const getPrintedLines = (verboseMessage, verboseObject) => verboseMessage
  35. .split('\n')
  36. .map(message => getPrintedLine({...verboseObject, message}));
  37. const getPrintedLine = verboseObject => {
  38. const verboseLine = defaultVerboseFunction(verboseObject);
  39. return {verboseLine, verboseObject};
  40. };
  41. // Serialize any type to a line string, for logging
  42. export const serializeVerboseMessage = message => {
  43. const messageString = typeof message === 'string' ? message : inspect(message);
  44. const escapedMessage = escapeLines(messageString);
  45. return escapedMessage.replaceAll('\t', ' '.repeat(TAB_SIZE));
  46. };
  47. // Same as `util.inspect()`
  48. const TAB_SIZE = 2;