#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Discover the type of directory given on the command line.
Copyright © 2011 Michael B. Trausch <mike@trausch.us>

-----------
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.,
51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
-----------

This module's purpose is to look at a directory and determine if it
is:

 * A plain directory (e.g., nothing to do with bzr at all),
 * A branch, or
 * A shared repository.

The return value will be 0 if it finds a branch or a shared
repository, or 1 if it is neither.  To learn more, the standard output
stream must be read and parsed.  For a branch it will appear thus:

path: /path/to/dirname
type: branch

For a shared repository it will appear thus:

path: /path/to/dirname
type: shared-repository
branches:
  /path/to/branch1
  /path/to/branch2
  /path/to/branch3

(That is, with two spaces before the path to the branch.)
'''
import sys

import bzrlib
import bzrlib.branch as bz_b
import bzrlib.repository as bz_r

def bzr_dirtype(path):
    try:
        r = bz_r.Repository.open(path)
        return ('shared-repository', r)
    except:
        pass

    try:
        b = bz_b.Branch.open(path)
        return ('branch', b)
    except:
        pass

    return (None, None)

p = sys.argv[1]
dtype, dobj = bzr_dirtype(p)

if dtype is None:
    sys.exit(1)
else:
    print 'path: {0}'.format(p)
    print 'type: {0}'.format(dtype)

    if dtype == 'shared-repository':
        print 'branches:'
        for branch in dobj.find_branches(True):
            print '  {0}'.format(branch.user_url[7:])
