All files / src/utils docblock.js

100% Statements 21/21
100% Branches 13/13
100% Functions 5/5
100% Lines 21/21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67                              8x     83x 83x 243x   83x     8x             168x 168x 113x 117x     55x 4x 4x           168x 83x   85x               3x 3x   3x 7x     3x    
/*
 * Copyright (c) 2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @flow
 */
 
/**
 * Helper functions to work with docblock comments.
 */
 
var DOCLET_PATTERN = /^@(\w+)(?:$|\s((?:[^](?!^@\w))*))/gmi;
 
function parseDocblock(str) {
  var lines = str.split('\n');
  for (var i = 0, l = lines.length; i < l; i++) {
    lines[i] = lines[i].replace(/^\s*\*\s?/, '');
  }
  return lines.join('\n').trim();
}
 
let DOCBLOCK_HEADER = /^\*\s/;
 
/**
 * Given a path, this function returns the closest preceding docblock if it
 * exists.
 */
export function getDocblock(path: NodePath): ?string {
  var comments = [];
  if (path.node.leadingComments) {
    comments = path.node.leadingComments.filter(
      comment => comment.type === 'CommentBlock' &&
        DOCBLOCK_HEADER.test(comment.value)
    );
  } else if (path.node.comments) {
    comments = path.node.comments.filter(
      comment => comment.leading &&
        comment.type === 'CommentBlock' &&
        DOCBLOCK_HEADER.test(comment.value)
    );
  }
 
  if (comments.length > 0) {
    return parseDocblock(comments[comments.length - 1].value);
  }
  return null;
}
 
/**
 * Given a string, this functions returns an object with doclet names as keys
 * and their "content" as values.
 */
export function getDoclets(str: string): Object {
  var doclets = Object.create(null);
  var match = DOCLET_PATTERN.exec(str);
 
  for (; match; match = DOCLET_PATTERN.exec(str)) {
    doclets[match[1]] = match[2] || true;
  }
 
  return doclets;
}