Skip to content

Commit

Permalink
clean: Use double-leading underscores to clean up class interfaces (#312
Browse files Browse the repository at this point in the history
)
  • Loading branch information
prcr authored Jan 9, 2024
1 parent 77f3e2f commit b8f019d
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 72 deletions.
58 changes: 29 additions & 29 deletions mkdocs_meta_descriptions_plugin/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,46 +5,46 @@

class Checker:
"""Checks meta descriptions against general SEO recommendations."""
_initialized = False
_check = False
_min_length = 50
_max_length = 160
_template_warning_missing = Template(
__initialized = False
__check = False
__min_length = 50
__max_length = 160
__template_warning_missing = Template(
"Meta description not found: $page")
_template_warning_length = Template(
__template_warning_length = Template(
"Meta description $character_count character$plural $comparative than $limit: $page")

def _check_length(self, page):
def __check_length(self, page):
length = len(page.meta.get("description", ""))
if length == 0:
logger.write(logger.Warning, self._template_warning_missing.substitute(page=page.file.src_path))
logger.write(logger.Warning, self.__template_warning_missing.substitute(page=page.file.src_path))
return # Skip length check
elif length < self._min_length:
diff = self._min_length - length
logger.write(logger.Warning, self._template_warning_length.substitute(character_count=diff,
plural="s"[:diff != 1],
comparative="shorter",
limit=self._min_length,
page=page.file.src_path))
elif length > self._max_length:
diff = length - self._max_length
logger.write(logger.Warning, self._template_warning_length.substitute(character_count=diff,
plural="s"[:diff != 1],
comparative="longer",
limit=self._max_length,
page=page.file.src_path))
elif length < self.__min_length:
diff = self.__min_length - length
logger.write(logger.Warning, self.__template_warning_length.substitute(character_count=diff,
plural="s"[:diff != 1],
comparative="shorter",
limit=self.__min_length,
page=page.file.src_path))
elif length > self.__max_length:
diff = length - self.__max_length
logger.write(logger.Warning, self.__template_warning_length.substitute(character_count=diff,
plural="s"[:diff != 1],
comparative="longer",
limit=self.__max_length,
page=page.file.src_path))

def initialize(self, config):
self._check = config.get("enable_checks")
self._min_length = config.get("min_length")
self._max_length = config.get("max_length")
self._initialized = True
self.__check = config.get("enable_checks")
self.__min_length = config.get("min_length")
self.__max_length = config.get("max_length")
self.__initialized = True

def check(self, page):
if not self._initialized:
if not self.__initialized:
logger.write(logger.Warning, "'LengthChecker' object not initialized yet, using default configurations")
if self._check:
self._check_length(page)
if self.__check:
self.__check_length(page)


checker = Checker()
34 changes: 17 additions & 17 deletions mkdocs_meta_descriptions_plugin/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,38 +11,38 @@


class Logger:
_initialized = False
__initialized = False
if MKDOCS_VERSION < MKDOCS_1_5_0:
_tag = "[meta-descriptions] "
_logger = getLogger("mkdocs.plugins." + __name__)
__tag = "[meta-descriptions] "
__logger = getLogger("mkdocs.plugins." + __name__)
else:
_tag = ""
_logger = get_plugin_logger("meta-descriptions")
_quiet = False
__tag = ""
__logger = get_plugin_logger("meta-descriptions")
__quiet = False

Debug, Info, Warning, Error = range(0, 4)

def initialize(self, config):
self._quiet = config.get("quiet")
self._initialized = True
self.__quiet = config.get("quiet")
self.__initialized = True

def write(self, log_level, message):
if not self._initialized:
self._logger.warning(self._tag + "'Logger' object not initialized yet, using default configurations")
if not self.__initialized:
self.__logger.warning(self.__tag + "'Logger' object not initialized yet, using default configurations")

message = self._tag + message
message = self.__tag + message
if log_level == self.Debug:
self._logger.debug(message)
self.__logger.debug(message)
elif log_level == self.Info:
# If quiet is True, print INFO messages as DEBUG
if self._quiet:
self._logger.debug(message)
if self.__quiet:
self.__logger.debug(message)
else:
self._logger.info(message)
self.__logger.info(message)
elif log_level == self.Warning:
self._logger.warning(message)
self.__logger.warning(message)
elif log_level == self.Error:
self._logger.error(message)
self.__logger.error(message)


logger = Logger()
20 changes: 10 additions & 10 deletions mkdocs_meta_descriptions_plugin/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,20 @@ class Export:
"""Read meta descriptions from the generated HTML and export them in a CSV file."""

def __init__(self, pages, config):
self._body_pattern = re.compile("<body", flags=re.IGNORECASE)
self._site_dir = config.get("site_dir")
self._site_url = config.get("site_url")
self._meta_descriptions = self._read_meta_descriptions(pages)
self.__body_pattern = re.compile("<body", flags=re.IGNORECASE)
self.__site_dir = config.get("site_dir")
self.__site_url = config.get("site_url")
self.__meta_descriptions = self.__read_meta_descriptions(pages)

def _read_meta_descriptions(self, pages):
def __read_meta_descriptions(self, pages):
count_missing = 0
meta_descriptions = {}
# Get meta descriptions only for Markdown documentation pages
for page in filter(lambda p: p.file.is_documentation_page(), pages):
with open(page.file.abs_dest_path) as page_file:
html = page_file.read()
# Strip page body to improve performance
html = re.split(self._body_pattern, html, maxsplit=1)[0]
html = re.split(self.__body_pattern, html, maxsplit=1)[0]
soup = BeautifulSoup(html, "html.parser")
meta_tag = soup.select_one('meta[name="description"]')
if meta_tag:
Expand All @@ -38,14 +38,14 @@ def _read_meta_descriptions(self, pages):
return meta_descriptions

def write_csv(self, output_file="meta-descriptions.csv"):
output_file_path = os.path.join(self._site_dir, output_file)
if self._meta_descriptions:
output_file_path = os.path.join(self.__site_dir, output_file)
if self.__meta_descriptions:
with open(output_file_path, "w") as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerow(["Page", "Meta description"])
for url_path, meta_description in self._meta_descriptions.items():
for url_path, meta_description in self.__meta_descriptions.items():
csv_writer.writerow(
[urljoin(self._site_url, url_path), meta_description]
[urljoin(self.__site_url, url_path), meta_description]
)
logger.write(logger.Info, f"Exported meta descriptions to {output_file_path}")
else:
Expand Down
32 changes: 16 additions & 16 deletions mkdocs_meta_descriptions_plugin/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,15 @@ class MetaDescription(BasePlugin):
)

def __init__(self):
self._headings_pattern = re.compile("<h[2-6]", flags=re.IGNORECASE)
self._pages = []
self._count_meta = 0 # Pages with meta descriptions defined on the page meta-data
self._count_first_paragraph = 0 # Pages with meta descriptions from the first paragraph
self._count_empty = 0 # Pages without meta descriptions
self.__headings_pattern = re.compile("<h[2-6]", flags=re.IGNORECASE)
self.__pages = []
self.__count_meta = 0 # Pages with meta descriptions defined on the page meta-data
self.__count_first_paragraph = 0 # Pages with meta descriptions from the first paragraph
self.__count_empty = 0 # Pages without meta descriptions

def _get_first_paragraph_text(self, html):
def __get_first_paragraph_text(self, html):
# Strip page subsections to improve performance
html = re.split(self._headings_pattern, html, maxsplit=1)[0]
html = re.split(self.__headings_pattern, html, maxsplit=1)[0]
# Select first paragraph directly under body
first_paragraph = BeautifulSoup(html, "html.parser").select_one("p:not(div.admonition > p)")
if first_paragraph is not None:
Expand All @@ -49,36 +49,36 @@ def on_config(self, config):
def on_page_content(self, html, page, config, files):
if page.meta.get("description", None):
# Skip pages that already have an explicit meta description
self._count_meta += 1
self.__count_meta += 1
logger.write(logger.Debug, f"Adding meta description from front matter: {page.file.src_path}")
else:
# Create meta description based on the first paragraph of the page
first_paragraph_text = self._get_first_paragraph_text(html)
first_paragraph_text = self.__get_first_paragraph_text(html)
if len(first_paragraph_text) > 0:
if self.config.get("trim"):
page.meta["description"] = shorten(first_paragraph_text, self.config.get("max_length"),
placeholder="")
else:
page.meta["description"] = first_paragraph_text
self._count_first_paragraph += 1
self.__count_first_paragraph += 1
logger.write(logger.Debug, f"Adding meta description from first paragraph: {page.file.src_path}")
else:
self._count_empty += 1
self.__count_empty += 1
logger.write(logger.Debug, f"Couldn't add meta description: {page.file.src_path}")
return html

def on_post_page(self, output, page, config):
if self.config.get("export_csv"):
# Collect pages to export meta descriptions to CSV file
self._pages.append(page)
self.__pages.append(page)
checker.check(page)
return output

def on_post_build(self, config):
count_meta = self._count_meta + self._count_first_paragraph
count_total = count_meta + self._count_empty
count_meta = self.__count_meta + self.__count_first_paragraph
count_total = count_meta + self.__count_empty
logger.write(logger.Info, f"Added meta descriptions to {count_meta} of {count_total} pages, "
f"{self._count_first_paragraph} using the first paragraph")
f"{self.__count_first_paragraph} using the first paragraph")
if self.config.get("export_csv"):
# Export meta descriptions to CSV file
Export(self._pages, config).write_csv()
Export(self.__pages, config).write_csv()

0 comments on commit b8f019d

Please sign in to comment.