line-endings.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. export function unixToWin(patch) {
  2. if (Array.isArray(patch)) {
  3. // It would be cleaner if instead of the line below we could just write
  4. // return patch.map(unixToWin)
  5. // but mysteriously TypeScript (v5.7.3 at the time of writing) does not like this and it will
  6. // refuse to compile, thinking that unixToWin could then return StructuredPatch[][] and the
  7. // result would be incompatible with the overload signatures.
  8. // See bug report at https://github.com/microsoft/TypeScript/issues/61398.
  9. return patch.map(p => unixToWin(p));
  10. }
  11. return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map(hunk => (Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map((line, i) => {
  12. var _a;
  13. return (line.startsWith('\\') || line.endsWith('\r') || ((_a = hunk.lines[i + 1]) === null || _a === void 0 ? void 0 : _a.startsWith('\\')))
  14. ? line
  15. : line + '\r';
  16. }) }))) });
  17. }
  18. export function winToUnix(patch) {
  19. if (Array.isArray(patch)) {
  20. // (See comment above equivalent line in unixToWin)
  21. return patch.map(p => winToUnix(p));
  22. }
  23. return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map(hunk => (Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map(line => line.endsWith('\r') ? line.substring(0, line.length - 1) : line) }))) });
  24. }
  25. /**
  26. * Returns true if the patch consistently uses Unix line endings (or only involves one line and has
  27. * no line endings).
  28. */
  29. export function isUnix(patch) {
  30. if (!Array.isArray(patch)) {
  31. patch = [patch];
  32. }
  33. return !patch.some(index => index.hunks.some(hunk => hunk.lines.some(line => !line.startsWith('\\') && line.endsWith('\r'))));
  34. }
  35. /**
  36. * Returns true if the patch uses Windows line endings and only Windows line endings.
  37. */
  38. export function isWin(patch) {
  39. if (!Array.isArray(patch)) {
  40. patch = [patch];
  41. }
  42. return patch.some(index => index.hunks.some(hunk => hunk.lines.some(line => line.endsWith('\r'))))
  43. && patch.every(index => index.hunks.every(hunk => hunk.lines.every((line, i) => { var _a; return line.startsWith('\\') || line.endsWith('\r') || ((_a = hunk.lines[i + 1]) === null || _a === void 0 ? void 0 : _a.startsWith('\\')); })));
  44. }