from myprocess import process,PIPE
import re
import os

logline = re.compile("([^\t]+)\t([^\t]+)\t(.*)")

def extensionof(s):
    return s.rsplit('.',1)[-1]

def log(when=None):
    args = ['git','log',"--numstat","--pretty=format:%at"]
    if when is not None:
        args.insert(3,when)

    with process(*args,stdout=PIPE) as proc:
        t = io.TextIOWrapper(proc.stdout)
        modified = None
        for line in t:
            m = logline.match(line)
            if not m:
                try: modified = int(line)
                except ValueError: pass
                continue
            path = m.group(2)
            path,ext = os.path.splitext(path)
            if not ext in {'txt','markdown'}: continue

            location, name = os.path.split(path)
            if name[:17] != '/chapters/Chapter': continue
            chapter = int(name[17:])
            
            yield modified, chapter, location, ext
