gitea源码

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import {AnsiUp} from 'ansi_up';
  2. const replacements: Array<[RegExp, string]> = [
  3. [/\x1b\[\d+[A-H]/g, ''], // Move cursor, treat them as no-op
  4. [/\x1b\[\d?[JK]/g, '\r'], // Erase display/line, treat them as a Carriage Return
  5. ];
  6. // render ANSI to HTML
  7. export function renderAnsi(line: string): string {
  8. // create a fresh ansi_up instance because otherwise previous renders can influence
  9. // the output of future renders, because ansi_up is stateful and remembers things like
  10. // unclosed opening tags for colors.
  11. const ansi_up = new AnsiUp();
  12. ansi_up.use_classes = true;
  13. if (line.endsWith('\r\n')) {
  14. line = line.substring(0, line.length - 2);
  15. } else if (line.endsWith('\n')) {
  16. line = line.substring(0, line.length - 1);
  17. }
  18. if (line.includes('\x1b')) {
  19. for (const [regex, replacement] of replacements) {
  20. line = line.replace(regex, replacement);
  21. }
  22. }
  23. if (!line.includes('\r')) {
  24. return ansi_up.ansi_to_html(line);
  25. }
  26. // handle "\rReading...1%\rReading...5%\rReading...100%",
  27. // convert it into a multiple-line string: "Reading...1%\nReading...5%\nReading...100%"
  28. const lines = [];
  29. for (const part of line.split('\r')) {
  30. if (part === '') continue;
  31. const partHtml = ansi_up.ansi_to_html(part);
  32. if (partHtml !== '') {
  33. lines.push(partHtml);
  34. }
  35. }
  36. // the log message element is with "white-space: break-spaces;", so use "\n" to break lines
  37. return lines.join('\n');
  38. }