# Path: nappingcat/exceptions.py
# class NappingCatRejected(NappingCatException):
#     pass
# 
# class NappingCatException(Exception):
#     pass
# 
# Path: nappingcat/contrib/git/exceptions.py
# class KittyGitUnauthorized(NappingCatRejected):
#     pass
# 
# Path: nappingcat/contrib/git/utils.py
# def get_full_repo_dir(settings, user, repo):
#     return os.path.expanduser(
#         '/'.join([settings.get('repo_dir', '~/repos'), user, repo+'.git'])
#     )
# 
# def get_clone_base_url(settings):
#     login, hostname = settings.get('user', None), settings.get('host', socket.gethostname()+'.local')
#     try:
#         login = os.getlogin() if login is None else login
#     except OSError:
#         login = DEFAULT_USER_NAME
#     return '%s@%s' % (login, hostname)
# 
# Path: nappingcat/contrib/git/operations.py
# def fork_repository(git, stdin, stdout, stderr, from_directory, to_directory):
# def create_repository(git, stdin, stdout, stderr, directory, template_dir=None, bare=True):
# def git_shell(git, stdin, stdout, stderr, action, directory):
# 
# Path: nappingcat/response.py
# def Success(content, response_type=Response):
#     return response_type(200, content)
# 
# class TextResponse(Response):
#     def __init__(self, status_code, content):
#         super(TextResponse, self).__init__(status_code, content)
# 
#     def __str__(self):
#         color = 32 if 300 > self.status_code > 199 else 31
#         return "\033[0;%dm%s\033[0m\n" % (color, self.content)
# 
# Path: nappingcat/decorators.py
# def discoverable(params, help_text):
#     def inner(func):
#         return DiscoverableEndpoint(func.__name__, params, help_text, func)
#     return inner 


from nappingcat.exceptions import NappingCatRejected, NappingCatException
from nappingcat.contrib.git.exceptions import KittyGitUnauthorized
from nappingcat.contrib.git.utils import get_full_repo_dir, get_clone_base_url
from nappingcat.contrib.git import operations
from nappingcat.response import Success, TextResponse 
from nappingcat.decorators import discoverable
import socket
import os
import subprocess
import sys
import glob
import shutil
delete_repo <repo_name>
""".strip())
def delete_repo(request, repo_name):
    if request.auth_backend.has_permission(request.user, ('kittygit', 'write', repo_name)):
        full_directory = os.path.expanduser(os.path.join(dict(request.settings.items('kittygit'))['repo_dir'], repo_name + '.git'))
        if os.path.isdir(full_directory):
            try:
                shutil.rmtree(full_directory)
                return Success({
                    'message':"Successfully deleted repository '%s'" % repo_name
                })
            except OSError:
                raise NappingCatRejected("Could not remove that path.")
    raise KittyGitUnauthorized("You don't have permission to remove '%s'" % repo_name)

@discoverable({'username':'string'},"""
list_repos
""".strip())
def list_repos(request, username):
    path = os.path.expanduser(os.path.join(dict(request.settings.items('kittygit'))['repo_dir'], username)) 
    output = []
    for file in glob.glob('%s/*.git' % path):
        repo = file.rsplit('/', 1)[-1][:-4]
        full_repo_name = '%s/%s' % (username, repo)
        if request.auth_backend.has_permission(request.user, ('kittygit', 'read', full_repo_name)):
            output.append(full_repo_name)
    return Success({
        'message':"You have access to the following repositories:\n\t%s" % "\n\t".join(output)
    })


# Path: nappingcat/exceptions.py
# class NappingCatRejected(NappingCatException):
#     pass
# 
# class NappingCatException(Exception):
#     pass
# 
# Path: nappingcat/contrib/git/exceptions.py
# class KittyGitUnauthorized(NappingCatRejected):
#     pass
# 
# Path: nappingcat/contrib/git/utils.py
# def get_full_repo_dir(settings, user, repo):
#     return os.path.expanduser(
#         '/'.join([settings.get('repo_dir', '~/repos'), user, repo+'.git'])
#     )
# 
# def get_clone_base_url(settings):
#     login, hostname = settings.get('user', None), settings.get('host', socket.gethostname()+'.local')
#     try:
#         login = os.getlogin() if login is None else login
#     except OSError:
#         login = DEFAULT_USER_NAME
#     return '%s@%s' % (login, hostname)
# 
# Path: nappingcat/contrib/git/operations.py
# def fork_repository(git, stdin, stdout, stderr, from_directory, to_directory):
# def create_repository(git, stdin, stdout, stderr, directory, template_dir=None, bare=True):
# def git_shell(git, stdin, stdout, stderr, action, directory):
# 
# Path: nappingcat/response.py
# def Success(content, response_type=Response):
#     return response_type(200, content)
# 
# class TextResponse(Response):
#     def __init__(self, status_code, content):
#         super(TextResponse, self).__init__(status_code, content)
# 
#     def __str__(self):
#         color = 32 if 300 > self.status_code > 199 else 31
#         return "\033[0;%dm%s\033[0m\n" % (color, self.content)
# 
# Path: nappingcat/decorators.py
# def discoverable(params, help_text):
#     def inner(func):
#         return DiscoverableEndpoint(func.__name__, params, help_text, func)
#     return inner 


# Path: nappingcat/contrib/git/handlers.py
from nappingcat.exceptions import NappingCatRejected, NappingCatException
from nappingcat.contrib.git.exceptions import KittyGitUnauthorized
from nappingcat.contrib.git.utils import get_full_repo_dir, get_clone_base_url
from nappingcat.contrib.git import operations
from nappingcat.response import Success, TextResponse 
from nappingcat.decorators import discoverable
import socket
import os
import subprocess
import sys
import glob
import shutil

delete_repo <repo_name>
""".strip())
def delete_repo(request, repo_name):
    if request.auth_backend.has_permission(request.user, ('kittygit', 'write', repo_name)):
        full_directory = os.path.expanduser(os.path.join(dict(request.settings.items('kittygit'))['repo_dir'], repo_name + '.git'))
        if os.path.isdir(full_directory):
            try:
                shutil.rmtree(full_directory)
                return Success({
                    'message':"Successfully deleted repository '%s'" % repo_name
                })
            except OSError:
                raise NappingCatRejected("Could not remove that path.")
    raise KittyGitUnauthorized("You don't have permission to remove '%s'" % repo_name)

@discoverable({'username':'string'},"""
list_repos
""".strip())
def list_repos(request, username):
    path = os.path.expanduser(os.path.join(dict(request.settings.items('kittygit'))['repo_dir'], username)) 
    output = []
    for file in glob.glob('%s/*.git' % path):
        repo = file.rsplit('/', 1)[-1][:-4]
        full_repo_name = '%s/%s' % (username, repo)
        if request.auth_backend.has_permission(request.user, ('kittygit', 'read', full_repo_name)):
            output.append(full_repo_name)
    return Success({
        'message':"You have access to the following repositories:\n\t%s" % "\n\t".join(output)
    })


@discoverable({'repo':'string'},"""