Skip to content

Commit

Permalink
Merge pull request #503 from jeremycline/no-more-init-for-code
Browse files Browse the repository at this point in the history
Remove functions from __init__.py that don't belong there
  • Loading branch information
jeremycline committed Jul 18, 2017
2 parents 5c4a191 + 74bab64 commit b748561
Show file tree
Hide file tree
Showing 15 changed files with 643 additions and 598 deletions.
39 changes: 39 additions & 0 deletions CHANGELOG.rst
Expand Up @@ -4,6 +4,45 @@ Changes
dev (master)
------------

Backwards-incompatible API changes
----------------------------------

A number of functions that make up Anitya's Python API have been moved
(`#503 <https://github.com/release-monitoring/anitya/pull/503>`_). The full
list of functions are below. Note that no function signatures have changed.

* ``anitya.check_release`` is now ``anitya.lib.utilities.check_project_release``.

* ``anitya.fedmsg_publish`` is now ``anitya.lib.utilities.fedmsg_publish``.

* ``anitya.log`` is now ``anitya.lib.utilities.log``.

* ``anitya.lib.init`` is now ``anitya.lib.utilities.init``.

* ``anitya.lib.create_project`` is now ``anitya.lib.utilities.create_project``.

* ``anitya.lib.edit_project`` is now ``anitya.lib.utilities.edit_project``.

* ``anitya.lib.map_project`` is now ``anitya.lib.utilities.map_project``.

* ``anitya.lib.flag_project`` is now ``anitya.lib.utilities.flag_project``.

* ``anitya.lib.set_flag_state`` is now ``anitya.lib.utilities.set_flag_state``.

* ``anitya.lib.get_last_cron`` is now ``anitya.lib.utilities.get_last_cron``.


Features
--------


Bug fixes
---------


0.11.0 (Feb. 08, 2017)
----------------------

* Return 4XX codes in error cases for /projects/new rather than 200 (Issue #246)

* Allow projecst using the "folder" backend to make insecure HTTPS requests
Expand Down
168 changes: 0 additions & 168 deletions anitya/__init__.py
@@ -1,172 +1,4 @@
# -*- coding: utf-8 -*-

import logging

import anitya.lib.plugins
import anitya.lib.exceptions


__api_version__ = '1.0'


_log = logging.getLogger(__name__)


def fedmsg_publish(*args, **kwargs): # pragma: no cover
''' Try to publish a message on the fedmsg bus. '''
# We catch Exception if we want :-p
# pylint: disable=W0703
# Ignore message about fedmsg import
# pylint: disable=F0401
kwargs['modname'] = 'anitya'
kwargs['cert_prefix'] = 'anitya'
kwargs['name'] = 'relay_inbound'
kwargs['active'] = True
try:
import fedmsg
fedmsg.publish(*args, **kwargs)
except Exception as err:
_log.error(str(err))


def check_release(project, session, test=False):
''' Check if the provided project has a new release available or not.
:arg package: a Package object has defined in anitya.lib.model.Project
'''
backend = anitya.lib.plugins.get_plugin(project.backend)
if not backend:
raise anitya.lib.exceptions.AnityaException(
'No backend was found for "%s"' % project.backend)

publish = False
up_version = None
max_version = None

try:
up_version = backend.get_version(project)
except anitya.lib.exceptions.AnityaPluginException as err:
_log.exception("AnityaError catched:")
project.logs = str(err)
session.add(project)
session.commit()
raise

if test:
return up_version

p_version = project.latest_version or ''

if up_version:
project.logs = 'Version retrieved correctly'

if up_version and up_version not in project.versions:
publish = True
project.versions_obj.append(
anitya.lib.model.ProjectVersion(
project_id=project.id,
version=up_version
)
)

odd_change = False
if up_version and up_version != p_version:
version_class = project.get_version_class()
max_version = max(up_version, p_version, key=version_class)
if project.latest_version and max_version != up_version:
odd_change = True
project.logs = 'Something strange occured, we found that this '\
'project has released a version "%s" while we had the latest '\
'version at "%s"' % (up_version, project.latest_version)
else:
project.latest_version = up_version

if publish:
anitya.log(
session,
project=project,
topic="project.version.update",
message=dict(
project=project.__json__(),
upstream_version=up_version,
old_version=p_version,
packages=[pkg.__json__() for pkg in project.packages],
versions=project.versions,
agent='anitya',
odd_change=odd_change,
),
)

session.add(project)
session.commit()


def _construct_substitutions(msg):
""" Convert a fedmsg message into a dict of substitutions. """
subs = {}
for key1 in msg:
if isinstance(msg[key1], dict):
subs.update(dict([
('.'.join([key1, key2]), val2)
for key2, val2 in _construct_substitutions(msg[key1]).items()
]))

subs[key1] = msg[key1]

return subs


def log(session, project=None, distro=None, topic=None, message=None):
""" Take a partial fedmsg topic and message.
Publish the message and log it in the db.
"""

# To avoid a circular import.
import anitya.lib.model as model

# A big lookup of fedmsg topics to model.Log template strings.
templates = {
'distro.add': '%(agent)s added the distro named: %(distro)s',
'distro.edit': '%(agent)s edited distro name from: %(old)s to: '
'%(new)s',
'distro.remove': '%(agent)s deleted the distro named: %(distro)s',
'project.add': '%(agent)s added project: %(project)s',
'project.add.tried': '%(agent)s tried to add an already existing '
'project: %(project)s',
'project.edit': '%(agent)s edited the project: %(project)s fields: '
'%(changes)s',
'project.flag': '%(agent)s flagged the project: %(project)s with '
'reason: %(reason)s',
'project.flag.set': '%(agent)s set flag %(flag)s to %(state)s',
'project.remove': '%(agent)s removed the project: %(project)s',
'project.map.new': '%(agent)s mapped the name of %(project)s in '
'%(distro)s as %(new)s',
'project.map.update': '%(agent)s update the name of %(project)s in '
'%(distro)s from: %(prev)s to: %(new)s',
'project.map.remove': '%(agent)s removed the mapping of %(project)s '
'in %(distro)s',
'project.version.remove': '%(agent)s removed the version %(version)s '
'of %(project)s ',
'project.version.update': 'new version: %(upstream_version)s found'
' for project %(project.name)s '
'(project id: %(project.id)s).',
}
substitutions = _construct_substitutions(message)
final_msg = templates[topic] % substitutions

fedmsg_publish(topic=topic, msg=dict(
project=project,
distro=distro,
message=message,
))

model.Log.insert(
session,
user=message['agent'],
project=project,
distro=distro,
description=final_msg)

return final_msg
15 changes: 8 additions & 7 deletions anitya/admin.py
Expand Up @@ -7,6 +7,7 @@
import flask
from sqlalchemy.exc import SQLAlchemyError

from anitya.lib import utilities
import anitya
import anitya.forms
import anitya.lib.model
Expand All @@ -31,7 +32,7 @@ def add_distro():

distro = anitya.lib.model.Distro(name)

anitya.log(
utilities.log(
SESSION,
distro=distro,
topic='distro.add',
Expand Down Expand Up @@ -76,7 +77,7 @@ def edit_distro(distro_name):
name = form.name.data

if name != distro.name:
anitya.log(
utilities.log(
SESSION,
distro=distro,
topic='distro.edit',
Expand Down Expand Up @@ -119,7 +120,7 @@ def delete_distro(distro_name):
form = anitya.forms.ConfirmationForm()

if form.validate_on_submit():
anitya.log(
utilities.log(
SESSION,
distro=distro,
topic='distro.remove',
Expand Down Expand Up @@ -159,7 +160,7 @@ def delete_project(project_id):

if form.validate_on_submit():
if confirm:
anitya.log(
utilities.log(
SESSION,
project=project,
topic='project.remove',
Expand Down Expand Up @@ -214,7 +215,7 @@ def delete_project_mapping(project_id, distro_name, pkg_name):

if form.validate_on_submit():
if confirm:
anitya.log(
utilities.log(
SESSION,
project=project,
topic='project.map.remove',
Expand Down Expand Up @@ -269,7 +270,7 @@ def delete_project_version(project_id, version):

if form.validate_on_submit():
if confirm:
anitya.log(
utilities.log(
SESSION,
project=project,
topic='project.version.remove',
Expand Down Expand Up @@ -484,7 +485,7 @@ def set_flag_state(flag_id, state):

if form.validate_on_submit():
try:
anitya.lib.set_flag_state(
utilities.set_flag_state(
SESSION,
flag=flag,
state=state,
Expand Down
3 changes: 2 additions & 1 deletion anitya/api.py
Expand Up @@ -23,6 +23,7 @@
import flask

from anitya.app import APP, SESSION
from anitya.lib import utilities
import anitya
import anitya.lib.plugins
import anitya.lib.model
Expand Down Expand Up @@ -398,7 +399,7 @@ def api_get_version():
httpcode = 404
else:
try:
version = anitya.check_release(project, SESSION, test=test)
version = utilities.check_project_release(project, SESSION, test=test)
if version:
output = {'version': version}
else:
Expand Down
15 changes: 7 additions & 8 deletions anitya/api_v2.py
Expand Up @@ -10,11 +10,10 @@
from flask import jsonify
from flask_restful import Resource, reqparse

from anitya import authentication
from anitya.app import APP, SESSION
from anitya.lib import utilities, model
from anitya.lib.exceptions import ProjectExists
import anitya
import anitya.lib.model
import anitya.authentication

_BASE_ARG_PARSER = reqparse.RequestParser(trim=True, bundle_errors=True)
_BASE_ARG_PARSER.add_argument('access_token', type=str)
Expand Down Expand Up @@ -69,7 +68,7 @@ class ProjectsResource(Resource):
The ``api/v2/projects/`` API endpoint.
"""

@anitya.authentication.parse_api_token
@authentication.parse_api_token
def get(self):
"""
Lists all projects.
Expand Down Expand Up @@ -137,11 +136,11 @@ def get(self):
parser.add_argument('items_per_page', type=_items_per_page_validator, location='args')
args = parser.parse_args(strict=True)
args.pop('access_token')
projects_page = anitya.lib.model.Project.query.paginate(
order_by=anitya.lib.model.Project.name, **args)
projects_page = model.Project.query.paginate(
order_by=model.Project.name, **args)
return projects_page.as_dict()

@anitya.authentication.require_api_token("upstream")
@authentication.require_api_token("upstream")
def post(self):
"""
Create a new project.
Expand Down Expand Up @@ -245,7 +244,7 @@ def post(self):
access_token = args.pop('access_token')

try:
project = anitya.lib.create_project(
project = utilities.create_project(
SESSION,
user_id=APP.oidc.user_getfield('email', access_token),
**args
Expand Down
3 changes: 2 additions & 1 deletion anitya/app.py
Expand Up @@ -20,6 +20,7 @@
from flask_restful import Api

from anitya.config import config as anitya_config
from anitya.lib import utilities
from anitya.lib.model import Session as SESSION, initialize as initialize_db
import anitya.lib
import anitya.authentication
Expand Down Expand Up @@ -157,7 +158,7 @@ def inject_variable():
if justedit: # pragma: no cover
flask.session['justedit'] = None

cron_status = anitya.lib.get_last_cron(SESSION)
cron_status = utilities.get_last_cron(SESSION)

return dict(
version=__version__,
Expand Down

0 comments on commit b748561

Please sign in to comment.