formatLocation.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
  7. /** @typedef {import("./Dependency").SourcePosition} SourcePosition */
  8. /**
  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. * @param {DependencyLocation} loc location
  24. * @returns {string} formatted location
  25. */
  26. const formatLocation = loc => {
  27. if (loc && typeof loc === "object") {
  28. if ("start" in loc && loc.start && "end" in loc && loc.end) {
  29. if (
  30. typeof loc.start === "object" &&
  31. typeof loc.start.line === "number" &&
  32. typeof loc.end === "object" &&
  33. typeof loc.end.line === "number" &&
  34. typeof loc.end.column === "number" &&
  35. loc.start.line === loc.end.line
  36. ) {
  37. return `${formatPosition(loc.start)}-${loc.end.column}`;
  38. } else if (
  39. typeof loc.start === "object" &&
  40. typeof loc.start.line === "number" &&
  41. typeof loc.start.column !== "number" &&
  42. typeof loc.end === "object" &&
  43. typeof loc.end.line === "number" &&
  44. typeof loc.end.column !== "number"
  45. ) {
  46. return `${loc.start.line}-${loc.end.line}`;
  47. }
  48. return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`;
  49. }
  50. if ("start" in loc && loc.start) {
  51. return formatPosition(loc.start);
  52. }
  53. if ("name" in loc && "index" in loc) {
  54. return `${loc.name}[${loc.index}]`;
  55. }
  56. if ("name" in loc) {
  57. return loc.name;
  58. }
  59. }
  60. return "";
  61. };
  62. module.exports = formatLocation;