Coverage for pymend\docstring_parser\parser.py: 100%

1"""The main parsing routine."""

2

3 from typing import Optional

4

5 from pymend.docstring_parser import epydoc, google, numpydoc, rest

6 from pymend.docstring_parser.common import (

7 Docstring,

8 DocstringStyle,

9 ParseError,

10 RenderingStyle,

11)

12

13 _STYLE_MAP = {

14 DocstringStyle.REST: rest,

15 DocstringStyle.GOOGLE: google,

16 DocstringStyle.NUMPYDOC: numpydoc,

17 DocstringStyle.EPYDOC: epydoc,

18}

19

20

21 def parse(

22 text: Optional[str], style: DocstringStyle = DocstringStyle.AUTO

23) -> Docstring:

24 """Parse the docstring into its components.

25

26 Parameters

27 ----------

28 text : Optional[str]

29 docstring text to parse

30 style : DocstringStyle

31 docstring style (Default value = DocstringStyle.AUTO)

32

33 Returns

34 -------

35 Docstring

36 parsed docstring representation

37

38 Raises

39 ------

40 ParserError

41 If none of the available module an parse the docstring

42 """

43 if style != DocstringStyle.AUTO:

44 return _STYLE_MAP[style].parse(text)

45

46 exc: Optional[Exception] = None

47 rets: list[Docstring] = []

48 for module in _STYLE_MAP.values():

49 try:

50 ret = module.parse(text)

51 except ParseError as ex:

52 exc = ex

53 else:

54 rets.append(ret)

55

56 if not rets and exc:

57 raise exc

58

59 return sorted(rets, key=lambda d: (len(d.examples), len(d.meta)), reverse=True)[0]

60

61

62 def compose(

63 docstring: Docstring,

64 style: DocstringStyle = DocstringStyle.AUTO,

65 rendering_style: RenderingStyle = RenderingStyle.COMPACT,

66 indent: str = " ",

67) -> str:

68 """Render a parsed docstring into docstring text.

69

70 Parameters

71 ----------

72 docstring : Docstring

73 parsed docstring representation

74 style : DocstringStyle

75 docstring style to render (Default value = DocstringStyle.AUTO)

76 indent : str

77 the characters used as indentation in the docstring string

78 (Default value = ' ')

79 rendering_style : RenderingStyle

80 The rendering style to use. (Default value = RenderingStyle.COMPACT)

81

82 Returns

83 -------

84 str

85 docstring text

86

87 Raises

88 ------

89 ValueError

90 If no output style could be determined.

91 """

92 if style == DocstringStyle.AUTO:

93 if docstring.style is None:

94 msg = (

95 "Detected docstring.style of `None` and requested style of `AUTO`.\n"

96 "Either the docstring to compose has to have its style set"

97 " (for example by calling `parse`) or an "

98 "output style has to be provided."

99 )

100 raise ValueError(msg)

101 style = docstring.style

102 module = _STYLE_MAP[style]

103 return module.compose(docstring, rendering_style=rendering_style, indent=indent)