Skip to content

Commit

Permalink
GH-446: add black auto-formatter (#480)
Browse files Browse the repository at this point in the history
* initial commit for adding black autoformatter

* Accepting defeat on chaining style

* Line length issue

* Added checklist item for running make format
  • Loading branch information
Ross Mechanic authored Nov 9, 2018
1 parent cc3a2c1 commit 0f522f9
Show file tree
Hide file tree
Showing 40 changed files with 1,414 additions and 1,258 deletions.
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ charset = utf-8
indent_style = space
end_of_line = lf
insert_final_newline = true
max_line_length = 79
max_line_length = 88
trim_trailing_whitespace = true

[*.{py,rst,ini}]
Expand Down
2 changes: 2 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@ install:
- pip install -U coverage codecov
- pip install -U flake8==3.6.0
- pip install -U $DJANGO
- if [[ $TRAVIS_PYTHON_VERSION == '3.6' ]]; then pip install black; fi
- pip freeze

script:
- flake8 simple_history
- if [[ $TRAVIS_PYTHON_VERSION == '3.6' ]]; then black --check simple_history; fi
- coverage run setup.py test

matrix:
Expand Down
1 change: 1 addition & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ Authors
- Matheus Cansian (@mscansian)
- Jim Gomez
- Hanyin Zhang
- James Muranga (@jamesmura)

Background
==========
Expand Down
11 changes: 11 additions & 0 deletions CONTRIBUTING.rst
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,14 @@ To run tox and generate an HTML code coverage report (available in the
To quickly run the tests against a single version of Python and Django (note: you must ``pip install django`` beforehand)::

python setup.py test

Code Formatting
---------------
We make use of `black`_ for code formatting.

.. _black: https://black.readthedocs.io/en/stable/installation_and_usage.html

Once it is installed you can make sure the code is properly formatted by running::

make format

2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,5 @@ release: dist
gpg --detach-sign -a dist/*
twine upload dist/*

format:
black simple_history
2 changes: 1 addition & 1 deletion PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
## Checklist:
<!--- Go over all the following points, and put an `x` in all the boxes that apply. -->
<!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->
- [ ] My code follows the code style of this project.
- [ ] I have run the `make format` command to format my code
- [ ] My change requires a change to the documentation.
- [ ] I have updated the documentation accordingly.
- [ ] I have read the **CONTRIBUTING** document.
Expand Down
11 changes: 8 additions & 3 deletions simple_history/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
from __future__ import unicode_literals

__version__ = '2.5.1'
__version__ = "2.5.1"


def register(
model, app=None, manager_name='history', records_class=None,
table_name=None, **records_config):
model,
app=None,
manager_name="history",
records_class=None,
table_name=None,
**records_config
):
"""
Create historical model for `model` and attach history manager to `model`.
Expand Down
142 changes: 70 additions & 72 deletions simple_history/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,9 @@
from django.utils.text import capfirst
from django.utils.translation import ugettext as _

USER_NATURAL_KEY = tuple(
key.lower() for key in settings.AUTH_USER_MODEL.split('.', 1))
USER_NATURAL_KEY = tuple(key.lower() for key in settings.AUTH_USER_MODEL.split(".", 1))

SIMPLE_HISTORY_EDIT = getattr(settings, 'SIMPLE_HISTORY_EDIT', False)
SIMPLE_HISTORY_EDIT = getattr(settings, "SIMPLE_HISTORY_EDIT", False)


class SimpleHistoryAdmin(admin.ModelAdmin):
Expand All @@ -32,9 +31,11 @@ def get_urls(self):
opts = self.model._meta
info = opts.app_label, opts.model_name
history_urls = [
url("^([^/]+)/history/([^/]+)/$",
url(
"^([^/]+)/history/([^/]+)/$",
admin_site.admin_view(self.history_form_view),
name='%s_%s_simple_history' % info),
name="%s_%s_simple_history" % info,
)
]
return history_urls + urls

Expand All @@ -54,7 +55,7 @@ def history_view(self, request, object_id, extra_context=None):
obj = self.get_queryset(request).get(**{pk_name: object_id})
except model.DoesNotExist:
try:
obj = action_list.latest('history_date').instance
obj = action_list.latest("history_date").instance
except action_list.model.DoesNotExist:
raise http.Http404

Expand All @@ -66,57 +67,55 @@ def history_view(self, request, object_id, extra_context=None):
value_for_entry = getattr(self, history_list_entry, None)
if value_for_entry and callable(value_for_entry):
for list_entry in action_list:
setattr(list_entry, history_list_entry,
value_for_entry(list_entry))
setattr(list_entry, history_list_entry, value_for_entry(list_entry))

content_type = ContentType.objects.get_by_natural_key(
*USER_NATURAL_KEY)
admin_user_view = 'admin:%s_%s_change' % (content_type.app_label,
content_type.model)
content_type = ContentType.objects.get_by_natural_key(*USER_NATURAL_KEY)
admin_user_view = "admin:%s_%s_change" % (
content_type.app_label,
content_type.model,
)
context = {
'title': _('Change history: %s') % force_text(obj),
'action_list': action_list,
'module_name': capfirst(force_text(opts.verbose_name_plural)),
'object': obj,
'root_path': getattr(self.admin_site, 'root_path', None),
'app_label': app_label,
'opts': opts,
'admin_user_view': admin_user_view,
'history_list_display': history_list_display,
"title": _("Change history: %s") % force_text(obj),
"action_list": action_list,
"module_name": capfirst(force_text(opts.verbose_name_plural)),
"object": obj,
"root_path": getattr(self.admin_site, "root_path", None),
"app_label": app_label,
"opts": opts,
"admin_user_view": admin_user_view,
"history_list_display": history_list_display,
}
context.update(self.admin_site.each_context(request))
context.update(extra_context or {})
extra_kwargs = {}
return render(request, self.object_history_template, context,
**extra_kwargs)
return render(request, self.object_history_template, context, **extra_kwargs)

def response_change(self, request, obj):
if '_change_history' in request.POST and SIMPLE_HISTORY_EDIT:
if "_change_history" in request.POST and SIMPLE_HISTORY_EDIT:
verbose_name = obj._meta.verbose_name

msg = _('The %(name)s "%(obj)s" was changed successfully.') % {
'name': force_text(verbose_name),
'obj': force_text(obj)
"name": force_text(verbose_name),
"obj": force_text(obj),
}

self.message_user(
request, "%s - %s" % (msg, _("You may edit it again below")))
request, "%s - %s" % (msg, _("You may edit it again below"))
)

return http.HttpResponseRedirect(request.path)
else:
return super(SimpleHistoryAdmin, self).response_change(
request, obj)
return super(SimpleHistoryAdmin, self).response_change(request, obj)

def history_form_view(self, request, object_id, version_id):
request.current_app = self.admin_site.name
original_opts = self.model._meta
model = getattr(
self.model,
self.model._meta.simple_history_manager_attribute).model
obj = get_object_or_404(model, **{
original_opts.pk.attname: object_id,
'history_id': version_id,
}).instance
self.model, self.model._meta.simple_history_manager_attribute
).model
obj = get_object_or_404(
model, **{original_opts.pk.attname: object_id, "history_id": version_id}
).instance
obj._state.adding = False

if not self.has_change_permission(request, obj):
Expand All @@ -127,21 +126,23 @@ def history_form_view(self, request, object_id, version_id):
else:
change_history = False

if '_change_history' in request.POST and SIMPLE_HISTORY_EDIT:
if "_change_history" in request.POST and SIMPLE_HISTORY_EDIT:
obj = obj.history.get(pk=version_id).instance

formsets = []
form_class = self.get_form(request, obj)
if request.method == 'POST':
if request.method == "POST":
form = form_class(request.POST, request.FILES, instance=obj)
if form.is_valid():
new_object = self.save_form(request, form, change=True)
self.save_model(request, new_object, form, change=True)
form.save_m2m()

self.log_change(request, new_object,
self.construct_change_message(
request, form, formsets))
self.log_change(
request,
new_object,
self.construct_change_message(request, form, formsets),
)
return self.response_change(request, new_object)

else:
Expand All @@ -158,42 +159,39 @@ def history_form_view(self, request, object_id, version_id):
model_name = original_opts.model_name
url_triplet = self.admin_site.name, original_opts.app_label, model_name
context = {
'title': _('Revert %s') % force_text(obj),
'adminform': admin_form,
'object_id': object_id,
'original': obj,
'is_popup': False,
'media': mark_safe(self.media + admin_form.media),
'errors': helpers.AdminErrorList(form, formsets),
'app_label': original_opts.app_label,
'original_opts': original_opts,
'changelist_url': reverse('%s:%s_%s_changelist' % url_triplet),
'change_url': reverse('%s:%s_%s_change' % url_triplet,
args=(obj.pk,)),
'history_url': reverse('%s:%s_%s_history' % url_triplet,
args=(obj.pk,)),
'change_history': change_history,

"title": _("Revert %s") % force_text(obj),
"adminform": admin_form,
"object_id": object_id,
"original": obj,
"is_popup": False,
"media": mark_safe(self.media + admin_form.media),
"errors": helpers.AdminErrorList(form, formsets),
"app_label": original_opts.app_label,
"original_opts": original_opts,
"changelist_url": reverse("%s:%s_%s_changelist" % url_triplet),
"change_url": reverse("%s:%s_%s_change" % url_triplet, args=(obj.pk,)),
"history_url": reverse("%s:%s_%s_history" % url_triplet, args=(obj.pk,)),
"change_history": change_history,
# Context variables copied from render_change_form
'add': False,
'change': True,
'has_add_permission': self.has_add_permission(request),
'has_change_permission': self.has_change_permission(request, obj),
'has_delete_permission': self.has_delete_permission(request, obj),
'has_file_field': True,
'has_absolute_url': False,
'form_url': '',
'opts': model._meta,
'content_type_id': ContentType.objects.get_for_model(
self.model).id,
'save_as': self.save_as,
'save_on_top': self.save_on_top,
'root_path': getattr(self.admin_site, 'root_path', None),
"add": False,
"change": True,
"has_add_permission": self.has_add_permission(request),
"has_change_permission": self.has_change_permission(request, obj),
"has_delete_permission": self.has_delete_permission(request, obj),
"has_file_field": True,
"has_absolute_url": False,
"form_url": "",
"opts": model._meta,
"content_type_id": ContentType.objects.get_for_model(self.model).id,
"save_as": self.save_as,
"save_on_top": self.save_on_top,
"root_path": getattr(self.admin_site, "root_path", None),
}
context.update(self.admin_site.each_context(request))
extra_kwargs = {}
return render(request, self.object_history_form_template, context,
**extra_kwargs)
return render(
request, self.object_history_form_template, context, **extra_kwargs
)

def save_model(self, request, obj, form, change):
"""Set special model attribute to user for reference after save"""
Expand Down
2 changes: 2 additions & 0 deletions simple_history/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@

class MultipleRegistrationsError(Exception):
"""The model has been registered to have history tracking more than once"""

pass


class NotHistoricalModelError(TypeError):
"""No related history model found."""

pass
Loading

0 comments on commit 0f522f9

Please sign in to comment.