mod_hg.py

Sun, 16 Aug 2015 19:27:14 +0300

author
Teemu Piippo <crimsondusk64@gmail.com>
date
Sun, 16 Aug 2015 19:27:14 +0300
changeset 153
497b7290977d
parent 152
1b734faab67a
child 155
5a9b5065f53f
permissions
-rw-r--r--

More Python 3 rework

'''
	Copyright 2014-2015 Teemu Piippo
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions
	are met:

	1. Redistributions of source code must retain the above copyright
	   notice, this list of conditions and the following disclaimer.
	2. Redistributions in binary form must reproduce the above copyright
	   notice, this list of conditions and the following disclaimer in the
	   documentation and/or other materials provided with the distribution.
	3. The name of the author may not be used to endorse or promote products
	   derived from this software without specific prior written permission.

	THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
	IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
	OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
	IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
	INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
	NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
	DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
	THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
	(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
	THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''

from __future__ import print_function
from datetime import datetime
import hgpoll
import re
import subprocess
from configfile import Config
from modulecore import command_error
from hgdb import HgCommitsDatabase

ModuleData = {
	'commands':
	[
		{
			'name': 'checkhg',
			'description': 'Polls the zandronum repositories for updates',
			'args': None,
			'level': 'admin',
		},

		{
			'name': 'cset',
			'description': 'Yields changeset information (use a hash or date as key)',
			'args': '<key>',
			'level': 'normal',
		},

		{
			'name': 'resolves',
			'description': '''Manually cause a ticket to be resolved by a changeset''',
			'args': '<ticket> <changeset>',
			'level': 'admin', # TODO
		},
	]
}

def plural (a):
	return '' if a == 1 else 's'

def cmd_checkhg (bot, **rest):
	hgpoll.force_poll()

def is_dateversion (key):
	try:
		datetime.strptime (key, '%y%m%d-%H%M')
		return True
	except ValueError:
		return False

def resolve_node (node):
	repo = None
	db = HgCommitsDatabase()

	if '/' in node:
		reponame, node = node.split ('/')[:2]
		
		try:
			repo = hgpoll.RepositoriesByName[reponame]
		except KeyError:
			command_error ('''unknown repository %s''' % reponame)

	# Possibly we're passed a date version instead. Try find the node for this.
	if is_dateversion (node):
		node = db.find_commit_by_dateversion (node)

		if node == None:
			command_error ('''couldn't find changeset for date %s''' % node)
			return

		node = node[0:7]

	noderepos = db.get_commit_repos (node)

	if repo == None:
		if not noderepos:
			command_error ('''couldn't find changeset %s''' % node)

		repo = noderepos[0]

	return (node, repo)

def get_version_string (repo, node):
	try:
		data = repo.hg ('cat', '--rev', node, 'src/version.h')

		regexps = [ \
			re.compile (r'#define\s+GAMEVER_STRING\s+"([^"]+)"'), \
			re.compile (r'#define\s+DOTVERSIONSTR_NOREV\s+"([^"]+)"'), \
			re.compile (r'#define\s+DOTVERSIONSTR\s+"([^"]+)"')]
	except subprocess.CalledProcessError:
		try:
			data = repo.hg ('cat', '--rev', node, 'src/core/versiondefs.h')
			regexps = [re.compile (r'#define\s+VERSION_STRING\s+"([^"]+)"')]
		except subprocess.CalledProcessError:
			return ''

	for line in data.splitlines():
		for rex in regexps:
			match = rex.match (line)

			if match:
				return match.group (1)

def cmd_cset (bot, args, reply, **rest):
	node, repo = resolve_node (args['key'])
	commit = repo.get_commit_data (rev=node,
		node='node|short',
		message='desc',
		author='author',
		diffstat='diffstat',
		time='date|hgdate',
		bookmarks='bookmarks',
		latesttagdistance='latesttagdistance',
		latesttag='latesttag',
		email='author|email')

	del node
	commit['date'] = datetime.utcfromtimestamp (int (commit['time'].split (' ')[0]))
	commit['latesttagdistance'] = int (commit['latesttagdistance'])
	commit['bookmarks'] = hgpoll.prettify_bookmarks (commit['bookmarks'])

	# Find out the version string of this changeset
	versionstring = get_version_string (repo, commit['node'])
	username = Config.find_developer_by_email (commit['email'])

	if username:
		commit['author'] = username

	# Try prettify the diffstat
	match = re.match (r'^([0-9]+): \+([0-9]+)/-([0-9]+)$', commit['diffstat'])

	if match:
		commit['diffstat'] = "%s\003:\0033 +%s\003/\0034-%s\003" % \
			(match.group (1), match.group (2), match.group (3))

	delta = datetime.utcnow() - commit['date']
	if delta.days < 4:
		if delta.days == 0:
			if delta.seconds < 60:
				datestring = 'just now'
			elif delta.seconds < 3600:
				minutes = delta.seconds / 60
				datestring = '%d minute%s ago' % (minutes, plural (minutes))
			else:
				hours = delta.seconds / 3600
				datestring = '%d hour%s ago' % (hours, plural (hours))
		else:
			datestring = '%d day%s ago' % (delta.days, plural (delta.days))
	else:
		datestring = 'on %s' % (str (commit['date']))

	if commit['latesttagdistance'] != 0:
		versionblurb = ""

		if versionstring:
			versionblurb = versionstring + ' '

		versionblurb += '%s, %d hops from %s' % (commit['date'].strftime ('%y%m%d-%H%M'),
			commit['latesttagdistance'], commit['latesttag'])
	else:
		versionblurb = latesttag

	reply ('changeset\0035 %s%s\003 (%s)\003: committed by\0032 %s\003 %s,\0032 %s' % \
		(commit['node'], commit['bookmarks'], versionblurb, commit['author'], datestring,
		commit['diffstat']))

	for line in commit['message'].split ('\n'):
		reply ('    ' + line)

	reply ('url: %s/commits/%s' % (repo.url, commit['node']))

def cmd_resolves (bot, args, **rest):
	hgpoll.announce_ticket_resolved (args['ticket'], args['changeset'])

mercurial