dronefly-core 0.5.0__tar.gz → 0.5.0.dev1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/PKG-INFO +1 -1
  2. dronefly_core-0.5.0.dev1/dronefly/core/__init__.py +1 -0
  3. dronefly_core-0.5.0/dronefly/core/commands/cli.py → dronefly_core-0.5.0.dev1/dronefly/core/commands/__init__.py +130 -5
  4. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/constants.py +4 -4
  5. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/formatters/generic.py +8 -1
  6. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/menus/taxon_list.py +24 -44
  7. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/query/query.py +2 -6
  8. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/query/taxon.py +1 -1
  9. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/pyproject.toml +1 -2
  10. dronefly_core-0.5.0/dronefly/core/__init__.py +0 -1
  11. dronefly_core-0.5.0/dronefly/core/commands/__init__.py +0 -4
  12. dronefly_core-0.5.0/dronefly/core/commands/base.py +0 -125
  13. dronefly_core-0.5.0/dronefly/core/commands/constants.py +0 -12
  14. dronefly_core-0.5.0/dronefly/core/commands/exceptions.py +0 -6
  15. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/LICENSE +0 -0
  16. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/README.md +0 -0
  17. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/clients/__init__.py +0 -0
  18. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/clients/inat.py +0 -0
  19. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/controllers/inat/__init__.py +0 -0
  20. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/controllers/inat/user_controller.py +0 -0
  21. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/formatters/__init__.py +0 -0
  22. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/formatters/constants.py +0 -0
  23. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/menus/__init__.py +0 -0
  24. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/menus/count.py +0 -0
  25. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/menus/counts.py +0 -0
  26. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/menus/menu.py +0 -0
  27. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/menus/source.py +0 -0
  28. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/menus/taxon.py +0 -0
  29. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/models/__init__.py +0 -0
  30. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/models/base_formatters.py +0 -0
  31. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/models/config.py +0 -0
  32. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/models/context.py +0 -0
  33. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/models/controlled_terms.py +0 -0
  34. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/models/place_count.py +0 -0
  35. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/models/taxon_list.py +0 -0
  36. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/models/user.py +0 -0
  37. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/paginator.py +0 -0
  38. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/parsers/__init__.py +0 -0
  39. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/parsers/constants.py +0 -0
  40. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/parsers/natural.py +0 -0
  41. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/parsers/unixlike.py +0 -0
  42. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/parsers/url.py +0 -0
  43. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/query/__init__.py +0 -0
  44. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/query/base.py +0 -0
  45. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/query/formatters.py +0 -0
  46. {dronefly_core-0.5.0 → dronefly_core-0.5.0.dev1}/dronefly/core/utils/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: dronefly-core
3
- Version: 0.5.0
3
+ Version: 0.5.0.dev1
4
4
  Summary: Core dronefly components
5
5
  License: AGPL-3.0-or-later
6
6
  Author: Ben Armstrong
@@ -0,0 +1 @@
1
+ from .commands import Commands, Format # noqa: F401
@@ -1,6 +1,14 @@
1
+ import asyncio
2
+ from enum import Enum
3
+ from inspect import signature
4
+ import re
5
+ from typing import Union
6
+
1
7
  from requests import HTTPError
8
+ from rich.markdown import Markdown
2
9
  from pyinaturalist import UserCount
3
10
 
11
+ from ..clients.inat import iNatClient
4
12
  from ..constants import (
5
13
  CONFIG_PATH,
6
14
  RANK_EQUIVALENTS,
@@ -8,6 +16,8 @@ from ..constants import (
8
16
  RANK_KEYWORDS,
9
17
  RANK_LEVELS,
10
18
  )
19
+
20
+ from ..parsers import NaturalParser
11
21
  from ..parsers.constants import VALID_OBS_SORT_BY
12
22
  from ..query import (
13
23
  get_place_count,
@@ -29,11 +39,26 @@ from ..formatters.generic import (
29
39
  )
30
40
  from ..menus.counts import CountsSource
31
41
  from ..menus.taxon_list import TaxonListSource
32
- from ..models import Context
42
+ from ..models import BaseFormatter, load_config, Context, ListFormatter
43
+
44
+
45
+ RICH_BQ_NEWLINE_PAT = re.compile(r"^(\> .*?)\n(?=\> )", re.MULTILINE)
46
+ RICH_BQ_END_PAT = re.compile(r"^((\> .*?\n)+)(?!> )", re.MULTILINE)
47
+ RICH_NO_BQ_NEWLINE_PAT = re.compile(r"^(?!\> )(.+?)(\n)(?!$|\> )", re.MULTILINE)
48
+ RICH_NEWLINE = " \\\n"
49
+
50
+
51
+ class ArgumentError(ValueError):
52
+ """Command arguments are not valid."""
53
+
54
+
55
+ class CommandError(NameError):
56
+ """Command is not known."""
57
+
33
58
 
34
- from .base import Commands
35
- from .constants import Format
36
- from .exceptions import ArgumentError, CommandError
59
+ class Format(Enum):
60
+ discord_markdown = 1
61
+ rich = 2
37
62
 
38
63
 
39
64
  def _check_obs_query_fields(query_response):
@@ -44,7 +69,107 @@ def _check_obs_query_fields(query_response):
44
69
  )
45
70
 
46
71
 
47
- class CLICommands(Commands):
72
+ # TODO: everything below needs to be broken down into different layers
73
+ # handling each thing:
74
+ # - Context
75
+ # - user, channel, etc.
76
+ # - affects which settings are passed to inat (e.g. home place for conservation status)
77
+ class Commands:
78
+ """A Dronefly command processor."""
79
+
80
+ def __init__(
81
+ self,
82
+ loop: asyncio.BaseEventLoop,
83
+ format: Format = Format.discord_markdown,
84
+ ):
85
+ self.loop = loop
86
+ # TODO: platform: dronefly.Platform
87
+ # - e.g. discord, commandline, web
88
+ self.format = format
89
+ self.inat_client = iNatClient(loop=loop)
90
+ self.parser = NaturalParser()
91
+ self.dronefly_config = load_config()
92
+
93
+ def _parse(self, query_str):
94
+ return self.parser.parse(query_str)
95
+
96
+ async def _get_formatted_page(
97
+ self,
98
+ formatter: Union[ListFormatter, BaseFormatter],
99
+ page_number: int = 0,
100
+ selected: int = 0,
101
+ header: str = None,
102
+ footer: str = None,
103
+ ):
104
+ source = getattr(formatter, "source", None)
105
+ if getattr(formatter, "format_page", None):
106
+ if source:
107
+ page = await source.get_page(page_number)
108
+ sig = signature(formatter.format_page)
109
+ if len(sig.parameters) == 3:
110
+ markdown_text = formatter.format_page(page, page_number, selected)
111
+ last_page = formatter.last_page()
112
+ else:
113
+ markdown_text = formatter.format_page(page)
114
+ last_page = 0
115
+ else:
116
+ markdown_text = formatter.format_page(page_number, selected)
117
+ last_page = formatter.last_page()
118
+ if last_page > 0:
119
+ markdown_text = "\n\n".join(
120
+ [markdown_text, f"Page {page_number + 1}/{last_page + 1}"]
121
+ )
122
+ else:
123
+ markdown_text = formatter.format()
124
+ if header or footer:
125
+ markdown_text = "\n\n".join(
126
+ [item for item in (header, markdown_text, footer) if item is not None]
127
+ )
128
+ return markdown_text
129
+
130
+ def _format_markdown(self, markdown_text: str):
131
+ """Format Rich vs. Discord markdown."""
132
+ if self.format == Format.rich:
133
+ # Richify the markdown:
134
+ # - In Discord markdown, all newlines are rendered as line breaks
135
+ # - In Rich:
136
+ # - Before every newline, emit " \" to force a line break, except
137
+ # for these exceptions to handle blockquotes:
138
+ # - Don't do this for a line preceding a blockquote
139
+ # - Also don't do this on the last line of a blockquote
140
+ # - Ensure the last line of each blockquote has two newlines to
141
+ # end it
142
+
143
+ # Replace all but last newline of blockquote with line break sequence:
144
+ rich_markdown = re.sub(RICH_BQ_NEWLINE_PAT, r"\1 \\\n", markdown_text)
145
+ # Add extra newline at end of blockquote so following text won't be
146
+ # tacked on:
147
+ rich_markdown = re.sub(RICH_BQ_END_PAT, r"\1\n\n", rich_markdown)
148
+ # Finally, on any line that isn't part of a blockquote, isn't empty,
149
+ # and isn't at the end of the string, emit a line break:
150
+ rich_markdown = re.sub(RICH_NO_BQ_NEWLINE_PAT, r"\1 \\\n", rich_markdown)
151
+ response = Markdown(rich_markdown)
152
+ else:
153
+ # Return the literal markdown for Discord to render
154
+ response = markdown_text
155
+ return response
156
+
157
+ def _simple_format_markdown(self, markdown_text: str):
158
+ """Simplified formatter for Rich vs. Discord markdown.
159
+
160
+ Discord vs. Rich linebreak rendering is harder than we thought, e.g.
161
+ `_format_markdown()` doesn't give correct results with point-form
162
+ or numbered lists. If special handling of newlines isn't needed, then
163
+ use this helper instead.
164
+ """
165
+ if self.format == Format.rich:
166
+ # Richify the markdown
167
+ response = Markdown(markdown_text)
168
+ else:
169
+ # Return the literal markdown for Discord to render
170
+ response = markdown_text
171
+ return response
172
+
48
173
  async def life(self, ctx: Context, *args):
49
174
  """List lifelist of taxa"""
50
175
  _args = " ".join(args) or "by me"
@@ -24,16 +24,16 @@ PLANTAE_ID = 47126
24
24
  TRACHEOPHYTA_ID = 211194
25
25
  RANK_KEYWORDS = tuple(RANK_LEVELS.keys()) + tuple(RANK_EQUIVALENTS.keys())
26
26
  RANK_LEVEL_NAMES = {}
27
- # TODO: import from pyinaturalist.constants instead of defining here:
28
- # - see https://github.com/pyinat/pyinaturalist/commit/82cee9d642538a8afb3add8809cca161345bdc68
29
- RANK_LEVEL_REPRESENTATIVE_RANKS = {
27
+ # For levels with multiple ranks, name the level after the most broadly used
28
+ # rank at that level:
29
+ RANK_LEVEL_TO_NAME = {
30
30
  5: "subspecies",
31
31
  10: "species",
32
32
  20: "genus",
33
33
  }
34
34
  RANKS_FOR_LEVEL = {}
35
35
  for (rank, level) in RANK_LEVELS.items():
36
- RANK_LEVEL_NAMES[level] = RANK_LEVEL_REPRESENTATIVE_RANKS.get(level) or rank
36
+ RANK_LEVEL_NAMES[level] = RANK_LEVEL_TO_NAME.get(level) or rank
37
37
  if level not in RANKS_FOR_LEVEL:
38
38
  RANKS_FOR_LEVEL[level] = [rank]
39
39
  else:
@@ -1305,4 +1305,11 @@ class UserFormatter(BaseFormatter):
1305
1305
  with_link: bool, optional
1306
1306
  Link to user's profile.
1307
1307
  """
1308
- return format_user_link(self.user) if with_link else format_user_name(self.user)
1308
+ name = self.user.name
1309
+ if name:
1310
+ name += f" ({self.user.login})"
1311
+ else:
1312
+ name = self.user.login
1313
+ if with_link:
1314
+ name = f"[{name}]({self.user.url})"
1315
+ return name
@@ -14,10 +14,7 @@ from pyinaturalist import (
14
14
  from .source import ListPageSource
15
15
  from .menu import BaseListMenu
16
16
  from ..models.taxon_list import TaxonListMetadata
17
- from ..constants import (
18
- RANKS_FOR_LEVEL,
19
- RANK_LEVEL_NAMES,
20
- )
17
+ from ..constants import RANKS_FOR_LEVEL, RANK_LEVEL_NAMES
21
18
  from ..formatters import TaxonListFormatter
22
19
  from ..query import QueryResponse
23
20
  from ..utils import included_ranks, lifelists_url_from_query_response
@@ -129,40 +126,6 @@ def taxa_per_rank(
129
126
  yield taxon
130
127
 
131
128
 
132
- def _get_normalized_ranks(per_rank: Union[list[str], str]):
133
- if isinstance(per_rank, str):
134
- per_ranks = [per_rank]
135
- else:
136
- per_ranks = per_rank
137
- rank_names = []
138
- normalized_ranks = []
139
- for rank in per_ranks:
140
- normalized_rank = RANK_EQUIVALENTS[rank] if rank in RANK_EQUIVALENTS else rank
141
- rank_level = RANK_LEVELS[normalized_rank]
142
- if normalized_rank not in normalized_ranks:
143
- # e.g. per_rank = 'species' | 'genus' | 'subspecies'
144
- representative_rank = RANK_LEVEL_NAMES[rank_level]
145
- if normalized_rank == representative_rank:
146
- # Add all ranks at the same level to the filter, described as
147
- # the representative rank at that level,
148
- # - e.g. "genus" =>
149
- # per_rank = ["genus", "genushybrid"]
150
- # described collectively as "genera"
151
- normalized_ranks += RANKS_FOR_LEVEL[rank_level]
152
- rank_name = p.plural_noun(representative_rank)
153
- else:
154
- # But for non-representative ranks, only include the
155
- # rank,
156
- # - e.g. "genushybrid" =>
157
- # per_rank = ["genushybrid"]
158
- # described collectively as "genushybrids"
159
- normalized_ranks.append(normalized_rank)
160
- rank_name = p.plural_noun(normalized_rank)
161
- rank_names.append(rank_name)
162
- ranks_description = "/".join(rank_names)
163
- return (ranks_description, normalized_ranks)
164
-
165
-
166
129
  def filter_taxon_list(
167
130
  taxon_list: list[Taxon],
168
131
  per_rank: Union[list[str], str],
@@ -197,7 +160,7 @@ def filter_taxon_list(
197
160
  was not indicated, otherwise reduce the root taxon to 0 and lower all
198
161
  taxa beneath it by the same amount.
199
162
  """
200
- ranks_description = None
163
+ ranks = None
201
164
  rank_totals = {}
202
165
  if per_rank in ("main", "any"):
203
166
  ranks_to_count = included_ranks(per_rank)
@@ -210,12 +173,12 @@ def filter_taxon_list(
210
173
  ranks_to_count.append(taxon.rank)
211
174
  else:
212
175
  ranks_to_count = ranks_to_count[: ranks_to_count.index(taxon.rank) + 1]
213
- ranks_description = "main ranks" if per_rank == "main" else "ranks"
176
+ ranks = "main ranks" if per_rank == "main" else "ranks"
214
177
  generate_taxa = taxa_per_rank(
215
178
  taxon_list, ranks_to_count, root_taxon_id, sort_by, order
216
179
  )
217
180
  elif per_rank in ("leaf", "child"):
218
- ranks_description = "leaf taxa" if per_rank == "leaf" else "child taxa"
181
+ ranks = "leaf taxa" if per_rank == "leaf" else "child taxa"
219
182
  if per_rank == "child" and not root_taxon_id:
220
183
  # `per child` is only meaningful when the taxon list is for a
221
184
  # single root taxon. Otherwise, default to the first taxon (usually
@@ -227,9 +190,26 @@ def filter_taxon_list(
227
190
  taxon_list, per_rank, _root_taxon_id, sort_by, order
228
191
  )
229
192
  else:
230
- (ranks_description, ranks_to_count) = _get_normalized_ranks(per_rank)
193
+ _per_rank = per_rank
194
+ _ranks = []
195
+ if isinstance(per_rank, str):
196
+ _per_rank = [per_rank]
197
+ per_rank = []
198
+ for _rank in _per_rank:
199
+ rank = RANK_EQUIVALENTS[_rank] if _rank in RANK_EQUIVALENTS else _rank
200
+ rank_name = p.plural_noun(RANK_LEVEL_NAMES[RANK_LEVELS[_rank]])
201
+ # Add all ranks at the same level to the filter, described as
202
+ # the most commonly used rank at that level,
203
+ # - e.g. "genus" =>
204
+ # per_rank = ["genus", "genushybrid"]
205
+ # described as "genera"
206
+ if rank not in per_rank:
207
+ per_rank += RANKS_FOR_LEVEL[RANK_LEVELS[_rank]]
208
+ _ranks.append(rank_name)
209
+ # List of arbitrary ranks (e.g. "subfamily/species"):
210
+ ranks = "/".join(_ranks)
231
211
  generate_taxa = taxa_per_rank(
232
- taxon_list, ranks_to_count, root_taxon_id, sort_by, order
212
+ taxon_list, per_rank, root_taxon_id, sort_by, order
233
213
  )
234
214
  # Count ranks, # of obs/spp, and adjust indent levels:
235
215
  counted_taxa = []
@@ -271,7 +251,7 @@ def filter_taxon_list(
271
251
  )
272
252
  counted_taxa.sort(key=sort_key)
273
253
  meta = TaxonListMetadata(
274
- ranks_description,
254
+ ranks,
275
255
  rank_totals,
276
256
  max_taxon_count_digits,
277
257
  max_direct_count_digits,
@@ -300,9 +300,7 @@ async def prepare_query_for_taxon(
300
300
  client: iNatClient, query: Query, scientific_name=False, locale=None
301
301
  ):
302
302
  check_query_taxon_list(query)
303
- if has_value(query.per):
304
- _query = query
305
- else:
303
+ if not has_value(query.per):
306
304
  _query = copy.copy(query)
307
305
  if has_value(query.user):
308
306
  per = "obs"
@@ -480,9 +478,7 @@ class QueryResponse:
480
478
  if self.added.d2:
481
479
  kwargs["created_d2"] = self.added.d2.isoformat()
482
480
  if self.sort_by:
483
- order_by = VALID_OBS_SORT_BY.get(str(self.sort_by))
484
- if order_by:
485
- kwargs["order_by"] = order_by
481
+ kwargs["order_by"] = VALID_OBS_SORT_BY.get(str(self.sort_by))
486
482
  if self.order:
487
483
  kwargs["order"] = str(self.order)
488
484
  return kwargs
@@ -229,7 +229,7 @@ async def get_taxon(client: iNatClient, taxon_id: int, **kwargs):
229
229
  return await anext(
230
230
  aiter(client.taxa.from_ids(taxon_id)),
231
231
  None,
232
- )
232
+ ).one()
233
233
 
234
234
 
235
235
  async def get_taxon_ancestor(client: iNatClient, taxon: Taxon, rank):
@@ -7,7 +7,7 @@ extend-ignore = "E203"
7
7
 
8
8
  [tool.poetry]
9
9
  name = "dronefly-core"
10
- version = "0.5.0"
10
+ version = "0.5.0.dev1"
11
11
  description = "Core dronefly components"
12
12
  authors = ["Ben Armstrong <synrg@debian.org>"]
13
13
  license = "AGPL-3.0-or-later"
@@ -31,7 +31,6 @@ pytest = "^7.2.1"
31
31
  pytest-mock = "^3.10.0"
32
32
  pylint = "^2.10.2"
33
33
  pytest-asyncio = "^0.20.3"
34
- flake8-pyproject = "^1.2.4"
35
34
 
36
35
  [build-system]
37
36
  requires = ["poetry-core"]
@@ -1 +0,0 @@
1
- from .commands import * # noqa: F401, F403
@@ -1,4 +0,0 @@
1
- from .base import * # noqa: F401, F403
2
- from .cli import * # noqa: F401, F403
3
- from .constants import * # noqa: F401, F403
4
- from .exceptions import * # noqa: F401, F403
@@ -1,125 +0,0 @@
1
- import asyncio
2
- from inspect import signature
3
- import re
4
- from typing import Union
5
-
6
- from rich.markdown import Markdown
7
- from ..parsers import NaturalParser
8
- from ..clients.inat import iNatClient
9
- from ..models import BaseFormatter, load_config, ListFormatter
10
- from .constants import (
11
- Format,
12
- RICH_BQ_END_PAT,
13
- RICH_BQ_NEWLINE_PAT,
14
- RICH_NO_BQ_NEWLINE_PAT,
15
- )
16
-
17
-
18
- class Command:
19
- def execute():
20
- pass
21
-
22
-
23
- class CommandResponse:
24
- def format_message():
25
- pass
26
-
27
- def start_menu():
28
- pass
29
-
30
-
31
- class Commands:
32
- """A Dronefly command processor."""
33
-
34
- def __init__(
35
- self,
36
- loop: asyncio.BaseEventLoop,
37
- format: Format = Format.discord_markdown,
38
- ):
39
- self.loop = loop
40
- # TODO: platform: dronefly.Platform
41
- # - e.g. discord, commandline, web
42
- self.format = format
43
- self.inat_client = iNatClient(loop=loop)
44
- self.parser = NaturalParser()
45
- self.dronefly_config = load_config()
46
-
47
- def _parse(self, query_str):
48
- return self.parser.parse(query_str)
49
-
50
- async def _get_formatted_page(
51
- self,
52
- formatter: Union[ListFormatter, BaseFormatter],
53
- page_number: int = 0,
54
- selected: int = 0,
55
- header: str = None,
56
- footer: str = None,
57
- ):
58
- source = getattr(formatter, "source", None)
59
- if getattr(formatter, "format_page", None):
60
- if source:
61
- page = await source.get_page(page_number)
62
- sig = signature(formatter.format_page)
63
- if len(sig.parameters) == 3:
64
- markdown_text = formatter.format_page(page, page_number, selected)
65
- last_page = formatter.last_page()
66
- else:
67
- markdown_text = formatter.format_page(page)
68
- last_page = 0
69
- else:
70
- markdown_text = formatter.format_page(page_number, selected)
71
- last_page = formatter.last_page()
72
- if last_page > 0:
73
- markdown_text = "\n\n".join(
74
- [markdown_text, f"Page {page_number + 1}/{last_page + 1}"]
75
- )
76
- else:
77
- markdown_text = formatter.format()
78
- if header or footer:
79
- markdown_text = "\n\n".join(
80
- [item for item in (header, markdown_text, footer) if item is not None]
81
- )
82
- return markdown_text
83
-
84
- def _format_markdown(self, markdown_text: str):
85
- """Format Rich vs. Discord markdown."""
86
- if self.format == Format.rich:
87
- # Richify the markdown:
88
- # - In Discord markdown, all newlines are rendered as line breaks
89
- # - In Rich:
90
- # - Before every newline, emit " \" to force a line break, except
91
- # for these exceptions to handle blockquotes:
92
- # - Don't do this for a line preceding a blockquote
93
- # - Also don't do this on the last line of a blockquote
94
- # - Ensure the last line of each blockquote has two newlines to
95
- # end it
96
-
97
- # Replace all but last newline of blockquote with line break sequence:
98
- rich_markdown = re.sub(RICH_BQ_NEWLINE_PAT, r"\1 \\\n", markdown_text)
99
- # Add extra newline at end of blockquote so following text won't be
100
- # tacked on:
101
- rich_markdown = re.sub(RICH_BQ_END_PAT, r"\1\n\n", rich_markdown)
102
- # Finally, on any line that isn't part of a blockquote, isn't empty,
103
- # and isn't at the end of the string, emit a line break:
104
- rich_markdown = re.sub(RICH_NO_BQ_NEWLINE_PAT, r"\1 \\\n", rich_markdown)
105
- response = Markdown(rich_markdown)
106
- else:
107
- # Return the literal markdown for Discord to render
108
- response = markdown_text
109
- return response
110
-
111
- def _simple_format_markdown(self, markdown_text: str):
112
- """Simplified formatter for Rich vs. Discord markdown.
113
-
114
- Discord vs. Rich linebreak rendering is harder than we thought, e.g.
115
- `_format_markdown()` doesn't give correct results with point-form
116
- or numbered lists. If special handling of newlines isn't needed, then
117
- use this helper instead.
118
- """
119
- if self.format == Format.rich:
120
- # Richify the markdown
121
- response = Markdown(markdown_text)
122
- else:
123
- # Return the literal markdown for Discord to render
124
- response = markdown_text
125
- return response
@@ -1,12 +0,0 @@
1
- from enum import Enum
2
- import re
3
-
4
- RICH_BQ_NEWLINE_PAT = re.compile(r"^(\> .*?)\n(?=\> )", re.MULTILINE)
5
- RICH_BQ_END_PAT = re.compile(r"^((\> .*?\n)+)(?!> )", re.MULTILINE)
6
- RICH_NO_BQ_NEWLINE_PAT = re.compile(r"^(?!\> )(.+?)(\n)(?!$|\> )", re.MULTILINE)
7
- RICH_NEWLINE = " \\\n"
8
-
9
-
10
- class Format(Enum):
11
- discord_markdown = 1
12
- rich = 2
@@ -1,6 +0,0 @@
1
- class ArgumentError(ValueError):
2
- """Command arguments are not valid."""
3
-
4
-
5
- class CommandError(NameError):
6
- """Command is not known."""