Skip to content

Commit

Permalink
add pre-commit
Browse files Browse the repository at this point in the history
  • Loading branch information
saxix committed Oct 24, 2023
1 parent 5d73d33 commit 50acd00
Show file tree
Hide file tree
Showing 46 changed files with 450 additions and 839 deletions.
5 changes: 0 additions & 5 deletions .flake8

This file was deleted.

4 changes: 2 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ jobs:

- name: Install dependencies
run: |
python -m pip install --upgrade pip tox
python -m pip install --upgrade pip pre-commit
- name: Lint with flake8
run: |
tox -e lint
pre-commit run --all
test:
services:
Expand Down
14 changes: 0 additions & 14 deletions .isort.cfg

This file was deleted.

21 changes: 21 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
repos:
- repo: local
hooks:
# Configuration for black exists in pyproject.toml,
# but we let pre-commit take care of the file filtering.
- id: black
name: black
entry: black
language: system
types: [python]
require_serial: true
- id: isort
name: isort
entry: isort
language: system
types: [python]
- id: flake8
name: flake8
entry: flake8
language: system
types: [python]
124 changes: 66 additions & 58 deletions docs/source/_ext/djangodocs.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,49 +4,50 @@
import json
import os
import re
from docutils import nodes, transforms
from sphinx import __version__ as sphinx_ver, addnodes, roles

from sphinx import __version__ as sphinx_ver
from sphinx import addnodes
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.util.compat import Directive
from sphinx.util.console import bold
from sphinx.writers.html import SmartyPantsHTMLTranslator

# RE for option descriptions without a '--' prefix
simple_option_desc_re = re.compile(
r'([-_a-zA-Z0-9]+)(\s*.*?)(?=,\s+(?:/|-|--)|$)')
simple_option_desc_re = re.compile(r"([-_a-zA-Z0-9]+)(\s*.*?)(?=,\s+(?:/|-|--)|$)")


def setup(app):
app.add_crossref_type(
directivename = "setting",
rolename = "setting",
indextemplate = "pair: %s; setting",
directivename="setting",
rolename="setting",
indextemplate="pair: %s; setting",
)
app.add_crossref_type(
directivename = "templatetag",
rolename = "ttag",
indextemplate = "pair: %s; template tag"
directivename="templatetag",
rolename="ttag",
indextemplate="pair: %s; template tag",
)
app.add_crossref_type(
directivename = "templatefilter",
rolename = "tfilter",
indextemplate = "pair: %s; template filter"
directivename="templatefilter",
rolename="tfilter",
indextemplate="pair: %s; template filter",
)
app.add_crossref_type(
directivename = "fieldlookup",
rolename = "lookup",
indextemplate = "pair: %s; field lookup type",
directivename="fieldlookup",
rolename="lookup",
indextemplate="pair: %s; field lookup type",
)
app.add_description_unit(
directivename = "django-admin",
rolename = "djadmin",
indextemplate = "pair: %s; django-admin command",
parse_node = parse_django_admin_node,
directivename="django-admin",
rolename="djadmin",
indextemplate="pair: %s; django-admin command",
parse_node=parse_django_admin_node,
)
app.add_description_unit(
directivename = "django-admin-option",
rolename = "djadminopt",
indextemplate = "pair: %s; django-admin command-line option",
parse_node = parse_django_adminopt_node,
directivename="django-admin-option",
rolename="djadminopt",
indextemplate="pair: %s; django-admin command-line option",
parse_node=parse_django_adminopt_node,
)
# app.add_config_value('django_next_version', '0.0', True)
# app.add_directive('versionadded', VersionDirective)
Expand All @@ -67,17 +68,17 @@ def run(self):
node = addnodes.versionmodified()
ret.append(node)
if self.arguments[0] == env.config.django_next_version:
node['version'] = "Development version"
node["version"] = "Development version"
else:
node['version'] = self.arguments[0]
node['type'] = self.name
node["version"] = self.arguments[0]
node["type"] = self.name
if len(self.arguments) == 2:
inodes, messages = self.state.inline_text(self.arguments[1], self.lineno+1)
inodes, messages = self.state.inline_text(self.arguments[1], self.lineno + 1)
node.extend(inodes)
if self.content:
self.state.nested_parse(self.content, self.content_offset, node)
ret = ret + messages
env.note_versionchange(node['type'], node['version'], node, self.lineno)
env.note_versionchange(node["type"], node["version"], node, self.lineno)
return ret


Expand All @@ -88,19 +89,19 @@ class DjangoHTMLTranslator(SmartyPantsHTMLTranslator):

# Don't use border=1, which docutils does by default.
def visit_table(self, node):
self._table_row_index = 0 # Needed by Sphinx
self.body.append(self.starttag(node, 'table', CLASS='docutils'))
self._table_row_index = 0 # Needed by Sphinx
self.body.append(self.starttag(node, "table", CLASS="docutils"))

# <big>? Really?
def visit_desc_parameterlist(self, node):
self.body.append('(')
self.body.append("(")
self.first_param = 1
self.param_separator = node.child_text_separator

def depart_desc_parameterlist(self, node):
self.body.append(')')
self.body.append(")")

if sphinx_ver < '1.0.8':
if sphinx_ver < "1.0.8":
#
# Don't apply smartypants to literal blocks
#
Expand All @@ -122,18 +123,16 @@ def depart_literal_block(self, node):
# that work.
#
version_text = {
'deprecated': 'Deprecated in Django %s',
'versionchanged': 'Changed in Django %s',
'versionadded': 'New in Django %s',
"deprecated": "Deprecated in Django %s",
"versionchanged": "Changed in Django %s",
"versionadded": "New in Django %s",
}

def visit_versionmodified(self, node):
self.body.append(
self.starttag(node, 'div', CLASS=node['type'])
)
self.body.append(self.starttag(node, "div", CLASS=node["type"]))
title = "%s%s" % (
self.version_text[node['type']] % node['version'],
len(node) and ":" or "."
self.version_text[node["type"]] % node["version"],
len(node) and ":" or ".",
)
self.body.append('<span class="title">%s</span> ' % title)

Expand All @@ -142,28 +141,31 @@ def depart_versionmodified(self, node):

# Give each section a unique ID -- nice for custom CSS hooks
def visit_section(self, node):
old_ids = node.get('ids', [])
node['ids'] = ['s-' + i for i in old_ids]
node['ids'].extend(old_ids)
old_ids = node.get("ids", [])
node["ids"] = ["s-" + i for i in old_ids]
node["ids"].extend(old_ids)
SmartyPantsHTMLTranslator.visit_section(self, node)
node['ids'] = old_ids
node["ids"] = old_ids


def parse_django_admin_node(env, sig, signode):
command = sig.split(' ')[0]
command = sig.split(" ")[0]
env._django_curr_admin_command = command
title = "django-admin.py %s" % sig
signode += addnodes.desc_name(title, title)
return sig


def parse_django_adminopt_node(env, sig, signode):
"""A copy of sphinx.directives.CmdoptionDesc.parse_signature()"""
from sphinx.domains.std import option_desc_re

count = 0
firstname = ''
firstname = ""
for m in option_desc_re.finditer(sig):
optname, args = m.groups()
if count:
signode += addnodes.desc_addname(', ', ', ')
signode += addnodes.desc_addname(", ", ", ")
signode += addnodes.desc_name(optname, optname)
signode += addnodes.desc_addname(args, args)
if not count:
Expand All @@ -173,7 +175,7 @@ def parse_django_adminopt_node(env, sig, signode):
for m in simple_option_desc_re.finditer(sig):
optname, args = m.groups()
if count:
signode += addnodes.desc_addname(', ', ', ')
signode += addnodes.desc_addname(", ", ", ")
signode += addnodes.desc_name(optname, optname)
signode += addnodes.desc_addname(args, args)
if not count:
Expand All @@ -189,20 +191,26 @@ class DjangoStandaloneHTMLBuilder(StandaloneHTMLBuilder):
Subclass to add some extra things we need.
"""

name = 'djangohtml'
name = "djangohtml"

def finish(self):
super().finish()
self.info(bold("writing templatebuiltins.js..."))
xrefs = self.env.domaindata["std"]["objects"]
templatebuiltins = {
"ttags": [n for ((t, n), (l, a)) in xrefs.items()
if t == "templatetag" and l == "ref/templates/builtins"],
"tfilters": [n for ((t, n), (l, a)) in xrefs.items()
if t == "templatefilter" and l == "ref/templates/builtins"],
"ttags": [
n
for ((t, n), (l, a)) in xrefs.items()
if t == "templatetag" and l == "ref/templates/builtins"
],
"tfilters": [
n
for ((t, n), (l, a)) in xrefs.items()
if t == "templatefilter" and l == "ref/templates/builtins"
],
}
outfilename = os.path.join(self.outdir, "templatebuiltins.js")
with open(outfilename, 'wb') as fp:
fp.write('var django_template_builtins = ')
with open(outfilename, "wb") as fp:
fp.write("var django_template_builtins = ")
json.dump(templatebuiltins, fp)
fp.write(';\n')
fp.write(";\n")
55 changes: 28 additions & 27 deletions docs/source/_ext/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,18 +35,17 @@ def make_link_node(rawtext, app, type, slug, options):
base = app.config.github_project_url
if not base:
raise AttributeError
if not base.endswith('/'):
base += '/'
if not base.endswith("/"):
base += "/"
except AttributeError as err:
raise ValueError('github_project_url configuration value is not set (%s)' % str(err))
raise ValueError("github_project_url configuration value is not set (%s)" % str(err))

ref = base + type + '/' + slug + '/'
ref = base + type + "/" + slug + "/"
set_classes(options)
prefix = "#"
if type == 'pull':
if type == "pull":
prefix = "PR " + prefix
node = nodes.reference(rawtext, prefix + utils.unescape(slug), refuri=ref,
**options)
node = nodes.reference(rawtext, prefix + utils.unescape(slug), refuri=ref, **options)
return node


Expand All @@ -72,20 +71,22 @@ def ghissue_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
raise ValueError
except ValueError:
msg = inliner.reporter.error(
'GitHub issue number must be a number greater than or equal to 1; '
'"%s" is invalid.' % text, line=lineno)
"GitHub issue number must be a number greater than or equal to 1; " '"%s" is invalid.' % text,
line=lineno,
)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
app = inliner.document.settings.env.app
#app.info('issue %r' % text)
if 'pull' in name.lower():
category = 'pull'
elif 'issue' in name.lower():
category = 'issues'
# app.info('issue %r' % text)
if "pull" in name.lower():
category = "pull"
elif "issue" in name.lower():
category = "issues"
else:
msg = inliner.reporter.error(
'GitHub roles include "ghpull" and "ghissue", '
'"%s" is invalid.' % name, line=lineno)
'GitHub roles include "ghpull" and "ghissue", ' '"%s" is invalid.' % name,
line=lineno,
)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
node = make_link_node(rawtext, app, category, str(issue_num), options)
Expand All @@ -108,8 +109,8 @@ def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
:param content: The directive content for customization.
"""
# app = inliner.document.settings.env.app
#app.info('user link %r' % text)
ref = 'https://www.github.com/' + text
# app.info('user link %r' % text)
ref = "https://www.github.com/" + text
node = nodes.reference(rawtext, text, refuri=ref, **options)
return [node], []

Expand All @@ -130,15 +131,15 @@ def ghcommit_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
:param content: The directive content for customization.
"""
app = inliner.document.settings.env.app
#app.info('user link %r' % text)
# app.info('user link %r' % text)
try:
base = app.config.github_project_url
if not base:
raise AttributeError
if not base.endswith('/'):
base += '/'
if not base.endswith("/"):
base += "/"
except AttributeError as err:
raise ValueError('github_project_url configuration value is not set (%s)' % str(err))
raise ValueError("github_project_url configuration value is not set (%s)" % str(err))

ref = base + text
node = nodes.reference(rawtext, text[:6], refuri=ref, **options)
Expand All @@ -150,9 +151,9 @@ def setup(app):
:param app: Sphinx application context.
"""
app.add_role('ghissue', ghissue_role)
app.add_role('ghpull', ghissue_role)
app.add_role('ghuser', ghuser_role)
app.add_role('ghcommit', ghcommit_role)
app.add_config_value('github_project_url', None, 'env')
app.add_role("ghissue", ghissue_role)
app.add_role("ghpull", ghissue_role)
app.add_role("ghuser", ghuser_role)
app.add_role("ghcommit", ghcommit_role)
app.add_config_value("github_project_url", None, "env")
return
Loading

0 comments on commit 50acd00

Please sign in to comment.