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. /** @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. } else {
  48. return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`;
  49. }
  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;