formatLocation.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @import { DependencyLocation, SourcePosition } from "../Dependency" */
  7. /**
  8. * Returns formatted position.
  9. * @param {SourcePosition} pos position
  10. * @returns {string} formatted position
  11. */
  12. const formatPosition = (pos) => {
  13. if (pos && typeof pos === "object") {
  14. if ("line" in pos && "column" in pos) {
  15. return `${pos.line}:${pos.column}`;
  16. } else if ("line" in pos) {
  17. return `${pos.line}:?`;
  18. }
  19. }
  20. return "";
  21. };
  22. /**
  23. * Returns formatted location.
  24. * @param {DependencyLocation} loc location
  25. * @returns {string} formatted location
  26. */
  27. const formatLocation = (loc) => {
  28. if (loc && typeof loc === "object") {
  29. if ("start" in loc && loc.start && "end" in loc && loc.end) {
  30. if (
  31. typeof loc.start === "object" &&
  32. typeof loc.start.line === "number" &&
  33. typeof loc.end === "object" &&
  34. typeof loc.end.line === "number" &&
  35. typeof loc.end.column === "number" &&
  36. loc.start.line === loc.end.line
  37. ) {
  38. return `${formatPosition(loc.start)}-${loc.end.column}`;
  39. } else if (
  40. typeof loc.start === "object" &&
  41. typeof loc.start.line === "number" &&
  42. typeof loc.start.column !== "number" &&
  43. typeof loc.end === "object" &&
  44. typeof loc.end.line === "number" &&
  45. typeof loc.end.column !== "number"
  46. ) {
  47. return `${loc.start.line}-${loc.end.line}`;
  48. }
  49. return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`;
  50. }
  51. if ("start" in loc && loc.start) {
  52. return formatPosition(loc.start);
  53. }
  54. if ("name" in loc && "index" in loc) {
  55. return `${loc.name}[${loc.index}]`;
  56. }
  57. if ("name" in loc) {
  58. return loc.name;
  59. }
  60. }
  61. return "";
  62. };
  63. module.exports = formatLocation;