mod_hg.py

Tue, 18 Aug 2015 14:38:54 +0300

author
Teemu Piippo <crimsondusk64@gmail.com>
date
Tue, 18 Aug 2015 14:38:54 +0300
changeset 156
5747c959c293
parent 155
5a9b5065f53f
permissions
-rw-r--r--

Use python3 in the shebang

'''
	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
import modulecore
from hgdb import HgCommitsDatabase

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

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:
			modulecore.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:
			modulecore.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:
			modulecore.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)

@modulecore.irc_command (level='admin')
def checkhg (bot, **rest):
	'''Polls the zandronum repositories for updates'''
	hgpoll.force_poll()

@modulecore.irc_command (args='<key>')
def 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']))

@modulecore.irc_command (args='<ticket> <changeset>', level='admin')
def resolves (bot, args, **rest):
	hgpoll.announce_ticket_resolved (args['ticket'], args['changeset'], HgCommitsDatabase())

mercurial