#!/usr/bin/env python

import os
import optparse
import sre
from os.path import join
from subprocess import Popen, PIPE
import inspect
import sys

def logall(start, xtra_args=None, verbose=False, dry_run=False):
    paths = []    
    
    svn = Popen(['svn', 'info', start], stdout=PIPE)
    url_p = sre.compile(r'^URL: (.*)')
    url = None
    for line in svn.stdout:
        m = url_p.match(line)
        if m:
            url = m.group(1)
    assert url is not None, "svn info: could not find URL:"
    
    paths = []
    svn = Popen(['svn', 'list', '--recursive', url], stdout=PIPE)
    [paths.append(L.strip()) for L in svn.stdout]
    r = svn.wait()
    if r != 0:
        print "\n".join(paths)
        sys.exit(r)
    
    cmd = ['svn']
    if xtra_args:
        cmd.extend(xtra_args)
    cmd.extend( ['log', url] )
    cmd.extend(paths)
    
    if verbose or dry_run:
        print ' '.join(cmd)
    if dry_run:
        sys.exit(0)
        
    svn = Popen(cmd, stdout=PIPE)
    for line in svn.stdout:
        print line,

def main():
    """recursively prints ALL unique revisions in a checkout 
    directory by looking up the URL with svn info then passing all 
    its relative paths to svn log
    """
    parser = optparse.OptionParser(usage=('%prog [options]' + "\n\n" + 
                                            inspect.getdoc(main)))
    parser.add_option('-d','--start_dir', default=os.getcwd(),
                        help=(  'root directory to start logging; '
                                'defaults to cwd'))
    parser.add_option('--stop-on-copy', action="store_true",
                        help="see svn help log")
    parser.add_option('-x','--xarg', action='append', default=[],
                        help=(  'append this argument to the command '
                                '(-x is chainable)'))
    parser.add_option('--verbose', action='store_true',
                        help='print command sent to svn')
    parser.add_option('--dry_run', action='store_true',
                        help="show command to sent to svn and exit")
    (options, args) = parser.parse_args()
    if len(args):
        options.start_dir = args[0]
    
    if options.stop_on_copy:
        options.xarg.append('--stop-on-copy')
    logall(options.start_dir, xtra_args = options.xarg, 
            verbose = options.verbose, dry_run = options.dry_run)

if __name__ == '__main__':
    main()