#!/usr/bin/env python
# -*- coding:utf-8 -*-

## Copyright (c) 2006, 2007, Joerg Zinke, Jonas Weismueller (team@petunial.com)
## All rights reserved.
##
## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions
## are met:
##
##  * Redistributions of source code must retain the above copyright
##    notice, this list of conditions and the following disclaimer.
##  * 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.
##  * Neither the name of the Petunial Team nor the names of its
##    contributors may be used to endorse or promote products derived
##    from this software without specific prior written permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
## "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
## COPYRIGHT OWNER OR CONTRIBUTORS 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.

"""

latua_propset

script for cleanup and propset svn files

"""

__version__ = "$Revision: 325 $"
# $URL: http://www.petunial.de/svn/latua/tags/0.2/scripts/latua_propset $

## standard modules
import os
import sys
import optparse
import fileinput
import subprocess

## latua modules
import latua

class _Propset(latua.Base):
    """Cleanup and propset svn files files."""
    def __init__(self):
        latua.Base.__init__(self)
        self.__system = latua.System()
        self.__version = latua.Version()

    def __cleanup(self, path):
        """Cleanup temporary files."""
        files = self.__system.files.search(path, "file", ".bak")
        print ">> removing .bak files:"
        for item in files:
            print item
            os.remove(item)
        files = self.__system.files.search(path, "file", ".pyc")
        print ">> removing .pyc files:"
        for item in files:
            print item
            os.remove(item)

    def __ignore(self, path):
        """Find all directories set them to ignore all pyc files."""
        directories = []
        result = self.__system.files.search(path, "directory")
        for item in result:
            if not self.platform.hidden(item):
                ## ignore hidden .svn
                directories.append(item)
        if len(directories) > 0:
            command = "svn propset svn:ignore \"*.pyc\" %s" % (" ".join(directories))
            print ">> running: %s" % (command)
            process = subprocess.Popen(command, shell=True,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.STDOUT,
                                       close_fds=True)
            print process.stdout.read()
        else:
            print ">> could not set ignore: no directories found"

    def __keywords(self, path):
        """Find all files and set keywords correct for them."""
        files = []
        result = self.__system.files.search(path, "file")
        for item in result:
            if not self.platform.hidden(item):
                ## ignore hidden files
                found = False
                for line in fileinput.input(item):
                    ## read files line by line
                    if line.find("$URL") > -1 or line.find("$Id") > -1 or line.find("$Author") > -1 or line.find("$Revision") > -1 or line.find("$Date") > -1:
                        ## found matching keywords
                        found = True
                if found == True:
                    files.append(item)
        if len(files) > 0:
            command = "svn propset svn:keywords \"Author Date Id Revision URL\" %s" % (" ".join(files))
            print ">> running: %s" % (command)
            process = subprocess.Popen(command, shell=True,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.STDOUT,
                                       close_fds=True)
            print process.stdout.read()
        else:
            print ">> could not set keywords: no files found"

    def run(self):
        """Main function."""
        ## create an command line option parser
        options_parser = optparse.OptionParser(usage="%prog [options] path",
                                               version="latua_propset latua v%s\n%s" %
                                               (self.__version.latua_version,
                                                self.__version.copyright))
        (options, arguments) = options_parser.parse_args()
        ## check given arguments
        if not len(arguments) == 1:
            options_parser.error("incorrect number of arguments")
        path = arguments[0]
        ## cleanup temporary files
        self.__cleanup(path)
        ## set ignore
        self.__ignore(path)
        ## set keywords
        self.__keywords(path)

## last line but first step
if __name__ == "__main__":
    _propset = _Propset()
    _propset.run()

