# Path: ellen/utils/process.py
# def git_with_repo(repository):
#     git_dir = repository.path
#     work_tree = repository.workdir
#     return git_with_path(git_dir, work_tree)
# 
# Path: ellen/utils/format.py
# def format_blame(text, repository):
#     RE_EMAIL = re.compile(r'<(?P<email>.*)>')
#     # FIXME: highlight_code
#     #def _blame_src_highlighted_lines(self, ref, path):
#     #    HIGHLIGHT_PATN = re.compile(
#     #        r'<a name="L-(\d+)"></a>(.*?)(?=<a name="L-(?:\d+)">)', re.DOTALL)
#     #    source_code = repository.show('%s:%s' % (ref, path))
#     #    source_code = source_code['data']
#     #    # TODO try to avoid having highlighted content here
#     #    hl_source_code = highlight_code(path, source_code)
#     #    hl_lines = dict(re.findall(HIGHLIGHT_PATN, hl_source_code))
#     #    return hl_lines
#     res = text
#     res = res.splitlines()
#     #hl_lines = _blame_src_highlighted_lines(ref, path)
#     hl_lines = {}
#     blame = []
#     rev_data = {}
#     new_block = True
#     for line in res:
#         if new_block:
#             sha, old_no, line_no = line.split()[:3]
#             if sha not in rev_data:
#                 rev_data[sha] = {}
#             rev_data[sha]['line_no'] = line_no
#             rev_data[sha]['old_no'] = old_no
#             new_block = False
#         elif line.startswith('author '):
#             _, _, author = line.partition(' ')
#             rev_data[sha]['author'] = author.strip()
#         elif line.startswith('author-time '):
#             _, _, time = line.partition(' ')
#             time = datetime.fromtimestamp(float(time)).strftime('%Y-%m-%d')
#             rev_data[sha]['time'] = time
#         elif line.startswith('author-mail '):
#             _, _, email = line.partition(' ')
#             email = RE_EMAIL.match(email).group('email')
#             rev_data[sha]['email'] = email
#         elif line.startswith('summary '):
#             _, _, summary = line.partition(' ')
#             rev_data[sha]['summary'] = summary.strip()
#             disp_summary = trunc_utf8(
#                 summary.encode('utf-8'), 20).decode('utf-8', 'ignore')
#             rev_data[sha]['disp_summary'] = disp_summary
#         elif line.startswith('filename'):
#             _, _, filename = line.partition(' ')
#             rev_data[sha]['filename'] = filename
#             filename = trunc_utf8(
#                 filename.strip().encode('utf-8'), 30).decode('utf-8', 'ignore')
#             rev_data[sha]['disp_name'] = filename
#         elif line.startswith('\t'):
#             # Try to get an highlighted line of source code
#             code_line = hl_lines.get(str(
#                 line_no), '').replace('\n', '').decode('utf-8', 'ignore')
#             if not code_line:
#                 code_line = line[1:]
#             blame.append((
#                 sha,
#                 rev_data[sha]['author'],
#                 rev_data[sha]['email'],
#                 rev_data[sha]['time'],
#                 rev_data[sha]['disp_summary'],
#                 rev_data[sha]['summary'],
#                 rev_data[sha]['line_no'],
#                 rev_data[sha]['old_no'],
#                 rev_data[sha]['filename'],
#                 rev_data[sha]['disp_name'],
#                 code_line,
#             ))
#             new_block = True
#     return blame
# 
# def format_blame_hunk(hunk, repository):
#     d = {}
#     d['lines_in_hunk'] = hunk.lines_in_hunk
#     d['final_commit_id'] = hunk.final_commit_id
#     d['final_start_line_number'] = hunk.final_start_line_number
#     d['final_committer'] = _format_pygit2_signature(hunk.final_committer)
#     d['orig_commit_id'] = hunk.orig_commit_id
#     d['orig_path'] = hunk.orig_path
#     d['orig_start_line_number'] = hunk.orig_start_line_number
#     d['orig_committer'] = _format_pygit2_signature(hunk.orig_committer)
#     d['boundary'] = hunk.boundary
#     return d
# 
# def format_blob(blob, repository):
#     d = {}
#     d['sha'] = str(blob.id)
#     d['type'] = 'blob'
#     d['data'] = blob.data
#     d['size'] = blob.size
#     d['binary'] = is_blob_binary(blob)
#     return d
# 
# def is_blob_binary(blob):
#     is_binary = blob.is_binary
#     if is_binary:
#         content_type = magic.from_buffer(blob.data[:1024], mime=True)
#         # FIXME: dirty hack for 'text/x-python'
#         if content_type and content_type.startswith('text/'):
#             is_binary = False
#         else:
#             plaintext = mime.Types[content_type] if content_type else None
#             text = plaintext[0] if plaintext else None
#             is_binary = text.is_binary if text else is_binary
#     return is_binary


from ellen.utils.process import git_with_repo
from ellen.utils.format import (format_blame,
                                format_blame_hunk,
                                format_blob,
                                is_blob_binary)
from pygit2 import (GIT_BLAME_TRACK_COPIES_SAME_COMMIT_MOVES,
                    GIT_BLAME_TRACK_COPIES_SAME_COMMIT_COPIES)
#!/usr/bin/env python
# -*- coding: utf-8 -*-



def blame_(repository, ref, path, lineno=None):
    """ git blame """
    git = git_with_repo(repository)
    if lineno:
        cmdstr = ('-L %s,%s --porcelain %s -- %s'
                  % (lineno, lineno, ref, path))  # start == end
    else:
        cmdstr = '-p -CM %s -- %s' % (ref, path)
    ret = git.blame.call(cmdstr)

# Path: ellen/utils/process.py
# def git_with_repo(repository):
#     git_dir = repository.path
#     work_tree = repository.workdir
#     return git_with_path(git_dir, work_tree)
# 
# Path: ellen/utils/format.py
# def format_blame(text, repository):
#     RE_EMAIL = re.compile(r'<(?P<email>.*)>')
#     # FIXME: highlight_code
#     #def _blame_src_highlighted_lines(self, ref, path):
#     #    HIGHLIGHT_PATN = re.compile(
#     #        r'<a name="L-(\d+)"></a>(.*?)(?=<a name="L-(?:\d+)">)', re.DOTALL)
#     #    source_code = repository.show('%s:%s' % (ref, path))
#     #    source_code = source_code['data']
#     #    # TODO try to avoid having highlighted content here
#     #    hl_source_code = highlight_code(path, source_code)
#     #    hl_lines = dict(re.findall(HIGHLIGHT_PATN, hl_source_code))
#     #    return hl_lines
#     res = text
#     res = res.splitlines()
#     #hl_lines = _blame_src_highlighted_lines(ref, path)
#     hl_lines = {}
#     blame = []
#     rev_data = {}
#     new_block = True
#     for line in res:
#         if new_block:
#             sha, old_no, line_no = line.split()[:3]
#             if sha not in rev_data:
#                 rev_data[sha] = {}
#             rev_data[sha]['line_no'] = line_no
#             rev_data[sha]['old_no'] = old_no
#             new_block = False
#         elif line.startswith('author '):
#             _, _, author = line.partition(' ')
#             rev_data[sha]['author'] = author.strip()
#         elif line.startswith('author-time '):
#             _, _, time = line.partition(' ')
#             time = datetime.fromtimestamp(float(time)).strftime('%Y-%m-%d')
#             rev_data[sha]['time'] = time
#         elif line.startswith('author-mail '):
#             _, _, email = line.partition(' ')
#             email = RE_EMAIL.match(email).group('email')
#             rev_data[sha]['email'] = email
#         elif line.startswith('summary '):
#             _, _, summary = line.partition(' ')
#             rev_data[sha]['summary'] = summary.strip()
#             disp_summary = trunc_utf8(
#                 summary.encode('utf-8'), 20).decode('utf-8', 'ignore')
#             rev_data[sha]['disp_summary'] = disp_summary
#         elif line.startswith('filename'):
#             _, _, filename = line.partition(' ')
#             rev_data[sha]['filename'] = filename
#             filename = trunc_utf8(
#                 filename.strip().encode('utf-8'), 30).decode('utf-8', 'ignore')
#             rev_data[sha]['disp_name'] = filename
#         elif line.startswith('\t'):
#             # Try to get an highlighted line of source code
#             code_line = hl_lines.get(str(
#                 line_no), '').replace('\n', '').decode('utf-8', 'ignore')
#             if not code_line:
#                 code_line = line[1:]
#             blame.append((
#                 sha,
#                 rev_data[sha]['author'],
#                 rev_data[sha]['email'],
#                 rev_data[sha]['time'],
#                 rev_data[sha]['disp_summary'],
#                 rev_data[sha]['summary'],
#                 rev_data[sha]['line_no'],
#                 rev_data[sha]['old_no'],
#                 rev_data[sha]['filename'],
#                 rev_data[sha]['disp_name'],
#                 code_line,
#             ))
#             new_block = True
#     return blame
# 
# def format_blame_hunk(hunk, repository):
#     d = {}
#     d['lines_in_hunk'] = hunk.lines_in_hunk
#     d['final_commit_id'] = hunk.final_commit_id
#     d['final_start_line_number'] = hunk.final_start_line_number
#     d['final_committer'] = _format_pygit2_signature(hunk.final_committer)
#     d['orig_commit_id'] = hunk.orig_commit_id
#     d['orig_path'] = hunk.orig_path
#     d['orig_start_line_number'] = hunk.orig_start_line_number
#     d['orig_committer'] = _format_pygit2_signature(hunk.orig_committer)
#     d['boundary'] = hunk.boundary
#     return d
# 
# def format_blob(blob, repository):
#     d = {}
#     d['sha'] = str(blob.id)
#     d['type'] = 'blob'
#     d['data'] = blob.data
#     d['size'] = blob.size
#     d['binary'] = is_blob_binary(blob)
#     return d
# 
# def is_blob_binary(blob):
#     is_binary = blob.is_binary
#     if is_binary:
#         content_type = magic.from_buffer(blob.data[:1024], mime=True)
#         # FIXME: dirty hack for 'text/x-python'
#         if content_type and content_type.startswith('text/'):
#             is_binary = False
#         else:
#             plaintext = mime.Types[content_type] if content_type else None
#             text = plaintext[0] if plaintext else None
#             is_binary = text.is_binary if text else is_binary
#     return is_binary


# Path: ellen/git/blame.py
from ellen.utils.process import git_with_repo
from ellen.utils.format import (format_blame,
                                format_blame_hunk,
                                format_blob,
                                is_blob_binary)
from pygit2 import (GIT_BLAME_TRACK_COPIES_SAME_COMMIT_MOVES,
                    GIT_BLAME_TRACK_COPIES_SAME_COMMIT_COPIES)

#!/usr/bin/env python
# -*- coding: utf-8 -*-



def blame_(repository, ref, path, lineno=None):
    """ git blame """
    git = git_with_repo(repository)
    if lineno:
        cmdstr = ('-L %s,%s --porcelain %s -- %s'
                  % (lineno, lineno, ref, path))  # start == end
    else:
        cmdstr = '-p -CM %s -- %s' % (ref, path)
    ret = git.blame.call(cmdstr)

    result = format_blame(ret['stdout'], repository)