# 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

    fork another user's repository to which you have read access.
    repository is given in the form <username>/<repo_name>.

""".strip())
def fork_repo(request, repo):
    settings = get_settings(request)
    auth = request.auth_backend
    username, repo_name = repo.split('/', 1)
    if auth.has_permission(request.user, ('kittygit', 'read', '%s/%s' % (username, repo_name))):

        to_repo_dir = get_full_repo_dir(settings, request.user, repo_name)
        from_repo_dir = get_full_repo_dir(settings, username, repo_name)
        success = operations.fork_repository(
            settings.get('git', 'git'),
            request.stdin,
            request.stdout,
            request.stderr,
            from_repo_dir,
            to_repo_dir
        )
        if success:
            auth.add_permission(request.user, ('kittygit', 'write', '%s/%s' % (request.user, repo_name)))
            auth.add_permission(request.user, ('kittygit', 'read', '%s/%s' % (request.user, repo_name)))
            auth.add_permission(username, ('kittygit', 'read', '%s/%s' % (request.user, repo_name)))
            clone_base = get_clone_base_url(settings)
            return Success({'message':"Repository '%s' successfully forked.\nClone it at '%s:%s/%s.git'" % (repo, clone_base, request.user, repo_name)})
        else:
            raise NappingCatException('Fork failed.')
    else:

# 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


    fork another user's repository to which you have read access.
    repository is given in the form <username>/<repo_name>.

""".strip())
def fork_repo(request, repo):
    settings = get_settings(request)
    auth = request.auth_backend
    username, repo_name = repo.split('/', 1)
    if auth.has_permission(request.user, ('kittygit', 'read', '%s/%s' % (username, repo_name))):

        to_repo_dir = get_full_repo_dir(settings, request.user, repo_name)
        from_repo_dir = get_full_repo_dir(settings, username, repo_name)
        success = operations.fork_repository(
            settings.get('git', 'git'),
            request.stdin,
            request.stdout,
            request.stderr,
            from_repo_dir,
            to_repo_dir
        )
        if success:
            auth.add_permission(request.user, ('kittygit', 'write', '%s/%s' % (request.user, repo_name)))
            auth.add_permission(request.user, ('kittygit', 'read', '%s/%s' % (request.user, repo_name)))
            auth.add_permission(username, ('kittygit', 'read', '%s/%s' % (request.user, repo_name)))
            clone_base = get_clone_base_url(settings)
            return Success({'message':"Repository '%s' successfully forked.\nClone it at '%s:%s/%s.git'" % (repo, clone_base, request.user, repo_name)})
        else:
            raise NappingCatException('Fork failed.')
    else:

        raise KittyGitUnauthorized("You don't have permission to read %s.git. Sorry!" % repo)