#! /usr/bin/python
# -*- coding: UTF-8 -*-
"""Push fixup.

This is a bzr plugin that fixes up the builtin 'push' command to revert the
remote branch after pushing (since for some insane reason push only pushes
the .bzr directory).
"""

__copyright__ = "Copyright (C) 2005 Colin Watson"
__author__    = "Colin Watson <cjwatson@flatline.org.uk>"

# 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 2 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


import re
import codecs
import subprocess
import bzrlib
import bzrlib.builtins
import bzrlib.commands
from bzrlib.branch import Branch
from bzrlib.errors import BzrCommandError


def metaquote(string):
    new_string = ''
    for char in string:
        if (not char.isalpha() and not char.isdigit() and
            char not in '+,-./=@^_'):
            new_string += '\\'
        new_string += char
    return new_string

class cmd_push_fix(bzrlib.builtins.cmd_push):
    """Push this branch into another branch, and then revert the remote
    branch to a sane state. Only works when pushing over sftp.

    See 'bzr help push' for further help.
    """

    def run(self, location=None, **kwargs):
        br_from = Branch.open_containing('.')[0]
        stored_loc = br_from.get_push_location()
        if location is None:
            if stored_loc is None:
                raise BzrCommandError("No push location known or specified.")
            else:
                location = stored_loc
        loc_match = re.match(r'^sftp://([^/]+)(/.*)$', location)
        if loc_match is None:
            raise BzrCommandError("push-fix only works over sftp.")
        super(cmd_push_fix, self).run(location, **kwargs)
        (server, path) = loc_match.groups()
        cmd = ['ssh', server, 'sh', '-c',
               metaquote('cd %s && bzr revert && find -name \*~ | xargs rm -f' % metaquote(path))]
        proc = subprocess.Popen(cmd)
        proc.wait()

bzrlib.commands.register_command(cmd_push_fix)
