formatLocation.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. * Returns formatted position.
  10. * @param {SourcePosition} pos position
  11. * @returns {string} formatted position
  12. */
  13. const formatPosition = (pos) => {
  14. if (pos && typeof pos === "object") {
  15. if ("line" in pos && "column" in pos) {
  16. return `${pos.line}:${pos.column}`;
  17. } else if ("line" in pos) {
  18. return `${pos.line}:?`;
  19. }
  20. }
  21. return "";
  22. };
  23. /**
  24. * Returns formatted location.
  25. * @param {DependencyLocation} loc location
  26. * @returns {string} formatted location
  27. */
  28. const formatLocation = (loc) => {
  29. if (loc && typeof loc === "object") {
  30. if ("start" in loc && loc.start && "end" in loc && loc.end) {
  31. if (
  32. typeof loc.start === "object" &&
  33. typeof loc.start.line === "number" &&
  34. typeof loc.end === "object" &&
  35. typeof loc.end.line === "number" &&
  36. typeof loc.end.column === "number" &&
  37. loc.start.line === loc.end.line
  38. ) {
  39. return `${formatPosition(loc.start)}-${loc.end.column}`;
  40. } else if (
  41. typeof loc.start === "object" &&
  42. typeof loc.start.line === "number" &&
  43. typeof loc.start.column !== "number" &&
  44. typeof loc.end === "object" &&
  45. typeof loc.end.line === "number" &&
  46. typeof loc.end.column !== "number"
  47. ) {
  48. return `${loc.start.line}-${loc.end.line}`;
  49. }
  50. return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`;
  51. }
  52. if ("start" in loc && loc.start) {
  53. return formatPosition(loc.start);
  54. }
  55. if ("name" in loc && "index" in loc) {
  56. return `${loc.name}[${loc.index}]`;
  57. }
  58. if ("name" in loc) {
  59. return loc.name;
  60. }
  61. }
  62. return "";
  63. };
  64. module.exports = formatLocation;