# bzr.py
#
# Copyright (C) 2014 Tim Marston <tim@edm.am>
#
# This file is part of stdhome (hereafter referred to as "this program").
# See http://ed.am/dev/stdhome for more information.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import subprocess, os, re, shutil
from subprocess import Popen
import StringIO
from vcs import Vcs
from stdhome import the


class BzrVcs( Vcs ):


	def __init__( self, dir ):
		"""Init class

		@param dir the fully-qualified directory to work in.
		"""
		self.dir = dir


	def init( self ):
		"""Create a new, empty branch
		"""

		# the directory shouldn't exist
		os.mkdir( self.dir )

		# bzr init
		try:
			self.run( [ 'bzr', 'init', '.' ] )
		except self.VcsError as e:

			# attempt to clean-up dir
			try:
				shutil.rmtree( self.dir )
			except OSError:
				pass

			raise


	def checkout( self, url ):
		"""Checkout a new copy of a remote branch.

		@param url the remote repository URL
		"""

		# the directory shouldn't exist
		os.mkdir( self.dir )

		# bzr co
		try:
			self.run( [ 'bzr', 'checkout', url, '.' ] )
		except self.VcsError as e:

			# attempt to clean-up dir
			try:
				shutil.rmtree( self.dir )
			except OSError:
				pass

			raise


	def get_revno( self ):
		"""Obtain some sort of revision identifier
		"""

		# bzr revert
		output = self.run( [ 'bzr', 'revno', '--tree' ] )

		# parse revno
		buf = StringIO.StringIO( output )
		return buf.readline().rstrip()


	def revert( self, revno = None ):
		"""Revert the branch so that there are no outstanding changes or unknown files.
		If a revno is supplied, then the repository is reverted to that
		revision.
		"""

		# bzr revert
		self.run( [ 'bzr', 'revert', '--no-backup' ] )

		# bzr st
		output = self.run( [ 'bzr', 'status' ] )
		files = self.parse_file_blocks( output )

		# remove unknown files
		if 'unknown' in files:
			for file in files[ 'unknown' ]:
				full_file = os.path.join( self.dir, file )
				if os.path.isfile( full_file ):
					os.unlink( full_file )
				elif os.full_file.isdir( full_file ):
					shutil.rmtree( full_file )
				else:
					raise RuntimeError( 'exotic file in repo: %s' % file )

		# if a revision identifyer has been given, update to that
		if revno is not None:

			# bzr update
			self.run( [ 'bzr', 'update', '-r', revno ] )


	def update( self ):
		"""Update the branch, pulling down any upstream changes and merging them.  This
		method returns a list of the files that were modified as part of this
		operation.
		"""

#		WARNING: the following might cause bzr to ask for your ssh password more than
#		once during an update!!!
#
#		# get revno
#		revno = self.get_revno()
#
#		# update to current revision (pull in history without updating tree)
#		self.run( [ 'bzr', 'update', '-r', revno ] )
#
#		# get log output
#		next_revno = str( int( revno ) + 1 )
#		output = self.run( [ 'bzr', 'log', '-r', next_revno + '..' ] )
#
#		# parse output
#		keep_files = list()
#		buf = StringIO.StringIO( output )
#		in_message = False
#		for line in buf:
#			line = line.rstrip( '\n' )
#			if line.lower() == 'message:':
#				in_message = True
#			elif in_message:
#				if line[ : 2 ] != '  ':
#					in_message = False
#				else:
#					line = line[ 2 : ]
#
#					# process directives
#					if line[ : 6 ].lower() == 'keep: ':
#						file = line[ 6 : ]
#						if file in rename_files: file = rename_files[ file ]
#						keep_files.append( file )
#					elif line[ : 8 ].lower() == 'rename: ':
#						rename_from = line[ 8 : ]
#					elif line[ : 4 ].lower() == 'to: ':
#						if rename_from in rename_files:
#							rename_from = rename_files[ rename_from ]
#						rename_files[ line[ 4 : ] ] = rename_from

		# bzr update properly
		output = self.run( [ 'bzr', 'update' ] )

		# parse output (see logic in report() in bzrlib/delta.py)
		files = list()
		buf = StringIO.StringIO( output )
		for line in buf:
			if not re.search( '^[-R+ ?][K NMD!][* ] ', line ): continue
			line = line.rstrip()
			if the.verbose > 1: print '  %s' % line

			# renames show before and after file names
			matches = re.search( '^R.. (.*?)[/@+]? => (.*?)[/@+]?$', line )
			if matches:
				files.append( matches.group( 1 ) )
				files.append( matches.group( 2 ) )
				continue

			# kind changes shows the same name twice
			matches = re.search( '^.K. (.*?)[/@+]? => (.*?)[/@+]?$', line )
			if matches:
				files.append( matches.group( 1 ) )
				continue

			# other entries have only one filename
			matches = re.search( '^... (.*?)[/@+]?$', line )
			if matches:
				files.append( matches.group( 1 ) )
				continue

			raise RuntimeError(
				'failed to parse bzr update output line:\n%' % line )

		return files


	def has_changes( self ):
		"""Check if the branch has any local modifications.
		"""

		# bzr status
		output = self.run( [ 'bzr', 'status', '--no-pending' ] )

		# parse output
		files = self.parse_file_blocks( output )
		return True if len( files ) else False


	def get_conflicts( self ):
		"""Return a list of files that have conflicts.
		"""

		# bzr status
		output = self.run( [ 'bzr', 'status', '--no-pending' ] )

		# parse output
		files = self.parse_file_blocks( output )
		return files['conflicts'] if 'conflicts' in files else None


	def run( self, cmd ):
		if the.verbose > 1: print 'exec: %s' % ' '.join( cmd )
		p = Popen( cmd, cwd = self.dir,
				   stdout = subprocess.PIPE, stderr = subprocess.STDOUT )
		output = p.communicate()[ 0 ]
		if p.returncode > 0:
			raise self.VcsError( ' '.join( cmd[ : 2 ] ), output )
		return output


	def parse_file_blocks( self, output ):
		res = dict()
		current = None
		buf = StringIO.StringIO( output )
		for line in buf:
			matches = re.search( '^([a-z ]+):$', line, re.I )
			if matches:
				current = matches.group( 1 )
				continue
			if current:
				matches = re.search( '^  ([^ ].*)$', line )
				if matches:
					if not current in res:
						res[ current ] = list()
					res[ current ].append( matches.group( 1 ) )
					continue
			if re.search( '^[0-9]+ shelf exists', line ): continue
			if re.search( '^working tree is out of date', line ): continue
			raise self.ParseError( "unrecognised line: %s" % line )
		return res


	class ParseError( Exception ):
		pass
