getLinkInfo.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. var _ = require('lodash');
  2. var path = require('canonical-path');
  3. /**
  4. * @dgService getLinkInfo
  5. * @description
  6. * Get link information to a document that matches the given url
  7. * @kind function
  8. * @param {String} url The url to match
  9. * @param {String} title An optional title to return in the link information
  10. * @return {Object} The link information
  11. *
  12. * @property {boolean} relativeLinks Whether we expect the links to be relative to the originating doc
  13. */
  14. module.exports = function getLinkInfo(getDocFromAlias, encodeCodeBlock, log) {
  15. return function getLinkInfoImpl(url, title, currentDoc) {
  16. var linkInfo = {
  17. url: url,
  18. type: 'url',
  19. valid: true,
  20. title: title || url
  21. };
  22. if ( !url ) {
  23. throw new Error('Invalid url');
  24. }
  25. var docs = getDocFromAlias(url, currentDoc);
  26. if ( !getLinkInfoImpl.useFirstAmbiguousLink && docs.length > 1 ) {
  27. linkInfo.valid = false;
  28. linkInfo.errorType = 'ambiguous';
  29. linkInfo.error = 'Ambiguous link: "' + url + '".\n' +
  30. docs.reduce(function(msg, doc) { return msg + '\n "' + doc.id + '" ('+ doc.docType + ') : (' + doc.path + ' / ' + doc.fileInfo.relativePath + ')'; }, 'Matching docs: ');
  31. } else if ( docs.length >= 1 ) {
  32. linkInfo.url = docs[0].path;
  33. linkInfo.title = title || encodeCodeBlock(docs[0].name, true);
  34. linkInfo.type = 'doc';
  35. if ( getLinkInfoImpl.relativeLinks && currentDoc && currentDoc.path ) {
  36. var currentFolder = path.dirname(currentDoc.path);
  37. var docFolder = path.dirname(linkInfo.url);
  38. var relativeFolder = path.relative(path.join('/', currentFolder), path.join('/', docFolder));
  39. linkInfo.url = path.join(relativeFolder, path.basename(linkInfo.url));
  40. log.debug(currentDoc.path, docs[0].path, linkInfo.url);
  41. }
  42. } else if ( url.indexOf('#') > 0 ) {
  43. var pathAndHash = url.split('#');
  44. linkInfo = getLinkInfoImpl(pathAndHash[0], title, currentDoc);
  45. linkInfo.url = linkInfo.url + '#' + pathAndHash[1];
  46. return linkInfo;
  47. } else if ( url.indexOf('/') === -1 && url.indexOf('#') !== 0 ) {
  48. linkInfo.valid = false;
  49. linkInfo.errorType = 'missing';
  50. linkInfo.error = 'Invalid link (does not match any doc): "' + url + '"';
  51. } else {
  52. linkInfo.title = title || (( url.indexOf('#') === 0 ) ? url.substring(1) : path.basename(url, '.html'));
  53. }
  54. return linkInfo;
  55. };
  56. };