#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# [The "New BSD" license]
# Copyright (c) 2014 The Board of Trustees of The University of Alabama
# All rights reserved.
#
# See LICENSE for details.

from __future__ import print_function

import logging
logger = logging.getLogger('cfl.main')

import sys
import os.path
import csv
from collections import namedtuple

import dulwich
import dulwich.porcelain

import utils

def cli():
    print("test")
    logger.info("test")

    name = sys.argv[1]
    WORKING_DIR = 'working'

    project = None

    with open("projects.csv", 'r') as f:
        reader = csv.reader(f)
        header = next(reader)
        Project = namedtuple('Project',  ' '.join(header))

        # figure out which column index contains the project name
        name_idx = header.index("name")

        # find the project in the csv, adding it's info to config
        for row in reader:
            if name == row[name_idx]:
                # 🎶  do you believe in magicccccc
                # in a young girl's heart? 🎶
                project = Project(*row)
                break

        # we can access project info by:
        #    project.name => "Blah Name"
        #    project.version => "0.22"

        if project is None:
            error("Could not find '%s' in 'projects.csv'!" % name)

    # reading in repos
    repos = list()
    with open(os.path.join('data', project.name, 'repos.txt')) as f:
        for line in f:
            repos.append(line.strip())

    print(project)
    print(repos)
    repos_base = 'gits'
    if not os.path.exists(repos_base):
        utils.mkdir(repos_base)

    for url in repos:
        target = os.path.join(repos_base, url.split('/')[-1])
        print(target)
        try:
            dulwich.porcelain.clone(url, target, bare=True)
        except OSError:
            pass

@@ -389,25 +389,42 @@
 dulwich.
-porcelain
+client%0Aimport dulwich.repo
 %0A%0Aimport
@@ -511,36 +511,8 @@
 v%5B1%5D
-%0A    WORKING_DIR = 'working'
 %0A%0A  
@@ -1746,26 +1746,8 @@
     
-dulwich.porcelain.
 clon
@@ -1812,9 +1812,623 @@
     pass
+%0A%0Adef clone(source, target, bare=False):%0A    client, host_path = dulwich.client.get_transport_and_path(source)%0A%0A    if target is None:%0A        target = host_path.split(%22/%22)%5B-1%5D%0A%0A    if not os.path.exists(target):%0A        os.mkdir(target)%0A%0A    if bare:%0A        r = dulwich.repo.Repo.init_bare(target)%0A    else:%0A        r = dulwich.repo.Repo.init(target)%0A%0A    remote_refs = client.fetch(host_path, r,%0A                               determine_wants=r.object_store.determine_wants_all)%0A%0A    r%5B%22HEAD%22%5D = remote_refs%5B%22HEAD%22%5D%0A%0A    for key, val in remote_refs.iteritems():%0A        r.refs.add_if_new(key, val)%0A%0A    return r
 %0A

Create own cloning function since dulwich.porcelain is dopey and doesn't copy the refs