def init(req): print "args:", req.args, req.args.path repo_path = os.path.join(req.args.path,'.git') if not os.path.isdir(repo_path): raise Abort("no repository found in '%s' (.git not found)!" % (os.path.abspath(req.args.path))) repo = Repository(req.args.path) print "repo references:", repo.listall_references() xxl_path = os.path.join(req.args.path,'.gitxxl') if os.path.exists(xxl_path): print "reinitializing existing XXL repo" else: print "initialiling XXL repo" os.mkdir(xxl_path) #install commit hooks dst = os.path.join(repo_path,"hooks","pre-commit") if not os.path.isfile(dst): src = os.path.join(sys.exec_prefix,"dist","hooks","pre-commit") print "installing pre-commit hook from:", src shutil.copyfile(src, dst) perm = os.stat(dst) os.chmod(dst,perm.st_mode | stat.S_IXUSR) dst = os.path.join(repo_path,"hooks","post-commit") if not os.path.isfile(dst): src = os.path.join(sys.exec_prefix,"dist","hooks","post-commit") print "installing post-commit hook from:", src shutil.copyfile(src, dst) perm = os.stat(dst) os.chmod(dst,perm.st_mode | stat.S_IXUSR)
def git_is_clean(srcdir, project): repo = Repository(os.path.join(srcdir, project.workspace_path, ".git")) for _, b in iteritems(repo.status()): if b != GIT_STATUS_IGNORED and b != GIT_STATUS_CURRENT: return False, "has uncommitted changes" if repo.head_is_detached: return False, "has detached HEAD" origin = get_origin(repo, project) if not origin: return False, "has no upstream remote" remote_refs = [] local_refs = {} for refname in repo.listall_references(): if refname.startswith("refs/remotes/%s/" % origin.name): ref = repo.lookup_reference(refname) if ref.type == GIT_REF_OID: remote_refs.append(ref.target) elif not refname.startswith("refs/remotes/"): ref = repo.lookup_reference(refname) if ref.type == GIT_REF_OID: local_refs[ref.peel().id] = refname if not remote_refs: return False, "has no upstream remote branches" if not local_refs: return False, "has no local branches" if not repo.lookup_branch("%s/%s" % (origin.name, project.master_branch), GIT_BRANCH_REMOTE): return False, "has no upstream master branch" for remote_ref in remote_refs: for commit in repo.walk(remote_ref): if commit.id in local_refs: del local_refs[commit.id] if local_refs: return False, "has local commits: %s" % ", ".join(["'%s'" % name for _, name in iteritems(local_refs)]) return True, ""
def init_repo(repo_path, clone_from=None, clone_refs=False, alternate_repo_paths=None, is_bare=True): """Initialise a new git repository or clone from existing.""" assert is_valid_new_path(repo_path) init_repository(repo_path, is_bare) if clone_from: # The clone_from's objects and refs are in fact cloned into a # subordinate tree that's then set as an alternate for the real # repo. This lets git-receive-pack expose available commits as # extra haves without polluting refs in the real repo. sub_path = os.path.join(repo_path, 'turnip-subordinate') clone_repository(clone_from, sub_path, True) assert is_bare alt_path = os.path.join(repo_path, 'objects/info/alternates') with open(alt_path, 'w') as f: f.write('../turnip-subordinate/objects\n') if clone_refs: # With the objects all accessible via the subordinate, we # can just copy all refs from the origin. Unlike # pygit2.clone_repository, this won't set up a remote. # TODO: Filter out internal (eg. MP) refs. from_repo = Repository(clone_from) to_repo = Repository(repo_path) for ref in from_repo.listall_references(): to_repo.create_reference( ref, from_repo.lookup_reference(ref).target) if alternate_repo_paths: write_alternates(repo_path, alternate_repo_paths) ensure_config(repo_path) # set repository configuration defaults return repo_path
class Git(object): r""" Interact with a git repository. """ def __init__(self, gitdir): r""" Take a path to the git repository. Other methods interact with this git repository. """ self.repo = Repository(gitdir) def branches(self): r""" Return the list of a branch name and its last commit id. """ return self._refs('heads') def tags(self): r""" Return the list of a tag name and its last commit id. """ return self._refs('tags') def _refs(self, type): refs = {} pattern = re.compile(r'refs/%s/(.*)$' % type) for ref in self.repo.listall_references(): m = pattern.match(ref) if m: reference = self.repo.lookup_reference(ref) refs[m.group(1)] = reference.hex return refs def create_branch(self, name, target): r""" Create new branch. """ if not is_valid_value(name): raise InvalidParamException("name is required") if not is_valid_hex(target): raise InvalidParamException("target is required") target = sha_hex2bin(target) try: self.repo.create_reference('refs/heads/%s' % name, target) except Exception, e: raise InvalidParamException(str(e)) return True
def git_is_clean(srcdir, project): repo = Repository(os.path.join(srcdir, project.workspace_path, ".git")) for _, b in iteritems(repo.status()): if b != GIT_STATUS_IGNORED and b != GIT_STATUS_CURRENT: return False, "has uncommitted changes" if repo.head_is_detached: return False, "has detached HEAD" origin = get_origin(repo, project) if not origin: return False, "has no upstream remote" remote_refs = [] local_refs = {} for refname in repo.listall_references(): if refname.startswith("refs/remotes/%s/" % origin.name): ref = repo.lookup_reference(refname) if ref.type == GIT_REF_OID: remote_refs.append(ref.target) elif not refname.startswith("refs/remotes/"): ref = repo.lookup_reference(refname) if ref.type == GIT_REF_OID: local_refs[ref.peel().id] = refname if not remote_refs: return False, "has no upstream remote branches" if not local_refs: return False, "has no local branches" if not repo.lookup_branch("%s/%s" % (origin.name, project.master_branch), GIT_BRANCH_REMOTE): return False, "has no upstream master branch" for remote_ref in remote_refs: for commit in repo.walk(remote_ref): if commit.id in local_refs: del local_refs[commit.id] if local_refs: return False, "has local commits: %s" % ", ".join( ["'%s'" % name for _, name in iteritems(local_refs)]) return True, ""
class GitMiner(BaseMiner): Id_Name_Login = namedtuple("Id_Name_Login", ["id", "name", "login"]) Code_Change = namedtuple("Code_Change", ["commit_id", "filename"]) def __init__(self, args): super().__init__(args) self._initialise_db() if args.dbms == "sqlite": self._conn.execute("PRAGMA foreign_keys=ON") self.email_map = {} self.commit_id = {} self.id_commit = {} self.code_change_map = {} self.__init_user_emails() self._dump_repository() self.aio = args.aio if self.aio: self._create_loop() self.repo = Repository(args.path) self._fetch_references() self._dump_tags() self._fetch_commit_ids() def _create_loop(self): self.loop = asyncio.new_event_loop() def load_from_file(self, file): pass def dump_to_file(self, path): pass def __init_user_emails(self): res = self.execute_query( """ SELECT email, id, login, name FROM contributors WHERE email IS NOT NULL """ ).fetchall() for row in res: self.email_map[row[0]] = self.Id_Name_Login(id=row[1], name=row[2], login=row[3]) def __init_code_change(self): res = self.execute_query( """ SELECT id, commit_id, filename FROM code_change """ ).fetchall() for row in res: self.code_change_map[self.Code_Change(commit_id=row[1], filename=row[2])] = row[0] def _dump_repository(self): logger.info("Dumping Repository...") res = self.execute_query( f""" SELECT repo_id FROM repository WHERE name="{self.repo_name}" and owner="{self.repo_owner}" """ ).fetchone() if res: self._set_repo_id(res[0]) else: repo = RepositoryStruct( name=self.repo_name, owner=self.repo_owner ).process() obj = self.db_schema.repository_object( name=self.repo_name, owner=self.repo_owner, created_at=repo.created_at, updated_at=repo.updated_at, description=repo.description, disk_usage=repo.disk_usage, fork_count=repo.fork_count, url=repo.url, homepage_url=repo.homepage_url, primary_language=repo.primary_language, total_stargazers=repo.stargazer_count, total_watchers=repo.watcher_count, forked_from=repo.forked_from ) self._insert(self.db_schema.repository.insert(), obj) self._set_repo_id() def _fetch_references(self): self.tags, self.branches = [], {} for reference in self.repo.listall_references(): if 'refs/tags' in reference: self.tags.append(reference) else: self.branches[reference] = self.repo.lookup_reference(reference).peel().oid def _dump_tags(self): objects = [] for tag in self.tags: ref = self.repo.lookup_reference(tag) tag_obj = self.repo[ref.target.hex] if isinstance(tag_obj, Tag): name = tag_obj.name msg = tag_obj.message tagged_object = tag_obj.hex tagger = self.__get_user_id(name=tag_obj.tagger.name, email=tag_obj.tagger.email, oid=tagged_object, is_author=False, is_tagger=True) else: name = tag.split('/')[-1] msg = tag_obj.message tagged_object = tag_obj.hex tagger = self.__get_user_id(name=tag_obj.author.name, email=tag_obj.author.email, oid=tagged_object, is_author=True, is_tagger=False) obj = self.db_schema.tags_object( name=name, tagged_object=tagged_object, message=msg, tagger=tagger ) objects.append(obj) self._insert(object_=self.db_schema.tags.insert(), param=objects) @staticmethod def __get_status(status): if status == 1: return 'ADDED' elif status == 2: return 'DELETED' elif status == 3: return 'MODIFIED' elif status == 4: return 'RENAMED' elif status == 5: return 'COPIED' elif status == 6: return 'IGNORED' elif status == 7: return 'UNTRACKED' elif status == 8: return 'TYPECHANGED' else: return None def __init_commits(self, inverse=False): if not inverse: res = self.execute_query( f""" SELECT oid, id FROM commits WHERE repo_id={self.repo_id} """ ).fetchall() for row in res: self.commit_id[row[0]] = row[1] else: res = self._conn.execute( f""" SELECT id, oid FROM commits WHERE repo_id={self.repo_id} """ ).fetchall() for row in res: self.id_commit[row[0]] = row[1] def __get_commit_id(self, oid, pk=None): if not pk: try: return self.commit_id[oid] except KeyError: return None else: try: return self.id_commit[pk] except KeyError: self.__init_commits(inverse=True) res = self.__get_commit_id(oid=None, pk=pk) if not res: raise Exception(f"GitMiner => __get_commit_id: Pk {pk} does not exist!") else: return res def __check_user_id(self, email): try: map_ = self.email_map[email] return [map_.id, map_.login, map_.name] except KeyError: res = self.execute_query( f""" SELECT id, login, name FROM contributors WHERE email="{email}" """ ).fetchone() if res: self.email_map[email] = self.Id_Name_Login(id=res[0], login=res[1], name=res[2]) return res def __update_contributor(self, name, id_, login, email): name = name.replace('"', '""') self.execute_query( f""" UPDATE contributors SET name="{name}" WHERE id={id_} """ ) self.email_map[email] = self.Id_Name_Login(id=id_, login=login, name=name) def __get_user_id(self, name, email, oid, is_author, is_tagger): if not email: email = None if not name: name = None res = self.__check_user_id(email) if not res: user = CommitUserStruct( oid=oid, repo_name=self.repo_name, repo_owner=self.repo_owner, name=name, email=email, is_author=is_author, is_tagger=is_tagger ).process() if user is None: self._dump_anon_user_object(name=name, email=email, object_=self.db_schema.contributors.insert(), locked_insert=LOCKED) else: self._dump_user_object(login=None, user_object=user, object_=self.db_schema.contributors.insert(), locked_insert=LOCKED) return self.__get_user_id(name=name, email=email, oid=oid, is_author=is_author, is_tagger=is_tagger) else: if name == res[2]: return res[0] elif name == res[1]: return res[0] else: self.__update_contributor(name=name, id_=res[0], login=res[1], email=email) return res[0] def _dump_code_change(self, oid): commit = self.repo.get(oid) commit_id = self.__get_commit_id(oid) logger.debug(f"Dumping Code Change for commit_id -> {commit_id}...") code_change = [] if commit: if not commit.parents: diffs = [self.repo.diff("4b825dc642cb6eb9a060e54bf8d69288fbee4904", commit)] else: diffs = [self.repo.diff(i, commit) for i in commit.parents] total_diffs = len(diffs) for diff in diffs: logger.debug(f"Remaining: {total_diffs}") total_diffs -= 1 for patch in diff: obj = self.db_schema.code_change_object( repo_id=self.repo_id, commit_id=commit_id, filename=patch.delta.new_file.path, additions=patch.line_stats[1], deletions=patch.line_stats[2], changes=patch.line_stats[1] + patch.line_stats[2], change_type=self.__get_status(patch.delta.status) ) code_change.append(obj) self._insert(object_=self.db_schema.code_change.insert(), param=code_change) logger.debug(f"Successfully dumped code change for {oid}!") def __get_code_change_id(self, commit_id, filename): try: return self.code_change_map[self.Code_Change(commit_id=commit_id, filename=filename)] except KeyError: return Exception(f"GitMiner => __get_code_change_id: Object does not exist! commit_id={commit_id}, " f"filename:{filename}") def _dump_patches(self, oid): commit = self.repo.get(oid) commit_id = self.__get_commit_id(oid) logger.debug(f"Dumping Patch for commit_id -> {commit_id}...") patches = [] if not commit.parents: diffs = [self.repo.diff("4b825dc642cb6eb9a060e54bf8d69288fbee4904", commit)] else: diffs = [self.repo.diff(i, commit) for i in commit.parents] total_diffs = len(diffs) for diff in diffs: logger.debug(f"Remaining: {total_diffs}") total_diffs -= 1 for patch in diff: obj = self.db_schema.patches_object( code_change_id=self.__get_code_change_id(commit_id, patch.delta.new_file.path), patch=patch.patch ) patches.append(obj) self._insert(object_=self.db_schema.patches.insert(), param=patches) logger.debug(f"Successfully dumped patch for {oid}!") def _dump_commit(self, oid): logger.debug(f"Inserting for commit: {oid}...") commit = self.repo.get(oid) if not commit.parents: diffs = [self.repo.diff("4b825dc642cb6eb9a060e54bf8d69288fbee4904", commit)] else: diffs = [self.repo.diff(i, commit) for i in commit.parents] num_files_changed = 0 additions, deletions = 0, 0 for diff in diffs: num_files_changed += diff.stats.files_changed additions += diff.stats.insertions deletions += diff.stats.deletions author_name = commit.author.name author_email = commit.author.email author_id = self.__get_user_id(name=author_name, email=author_email, oid=oid.hex, is_author=True, is_tagger=False) if \ author_email.strip() else None authored_date = datetime.fromtimestamp(commit.author.time) committer_name = commit.committer.name committer_email = commit.committer.email if committer_email == "*****@*****.**": committer_id = author_id else: committer_id = self.__get_user_id(name=committer_name, email=committer_email, oid=oid.hex, is_author=False, is_tagger=False) if committer_email.strip() else None committed_date = datetime.fromtimestamp(commit.commit_time) message = commit.message if len(commit.parents) > 1: is_merge = 1 else: is_merge = 0 obj = self.db_schema.commits_object( repo_id=self.repo_id, oid=oid.hex, additions=additions, deletions=deletions, author_id=author_id, authored_date=authored_date, committer_id=committer_id, committer_date=committed_date, message=message, num_files_changed=num_files_changed, is_merge=is_merge ) self._insert(object_=self.db_schema.commits.insert(), param=obj) logger.debug(f"Successfully dumped commit: {oid.hex}") def __fetch_branch_commits(self, branch_target): logger.info(f"Ongoing Branch {branch_target[0]}...") for commit in self.repo.walk(branch_target[1], GIT_SORT_TOPOLOGICAL | GIT_SORT_TIME): if commit.oid not in self.commits: self.commits.add(commit.oid) else: break def _fetch_commit_ids(self): try: with open(f"{ROOT}/.gras-cache/{self.repo_name}_commits.txt", "rb") as fp: self.commits = pickle.load(fp) self.commits = [Oid(hex=x) for x in self.commits] logger.info(f"TOTAL COMMITS: {len(self.commits)}") return self.commits except FileNotFoundError: logger.error("Commits file not present, dumping...") self.commits = set() with concurrent.futures.ThreadPoolExecutor(max_workers=THREADS) as executor: process = {executor.submit(self.__fetch_branch_commits, branch_target): branch_target for branch_target in self.branches.items()} for future in concurrent.futures.as_completed(process): branch_target = process[future] logger.info(f"Fetched for {branch_target[0]}, Total: {len(self.commits)}") logger.info(f"TOTAL COMMITS: {len(self.commits)}") with open(f"{ROOT}/.gras-cache/{self.repo_name}_commits.txt", "wb") as fp: temp = [x.hex for x in self.commits] pickle.dump(temp, fp) del temp @timing(name="commits", is_stage=True) def _parse_commits(self): res = self.execute_query( f""" SELECT DISTINCT oid FROM commits """ ).fetchall() dumped_commits = [x[0] for x in res] del res commits = list(self.commits) for i in range(0, len(commits), THREADS): proc = [mp.Process(target=self._dump_commit, args=(oid,)) for oid in commits[i:i + THREADS] if oid.hex not in dumped_commits] for p in proc: p.start() while any([p.is_alive() for p in proc]): continue @timing(name="code change", is_stage=True) def _parse_code_change(self): id_oid = self.execute_query( f""" SELECT id, oid FROM commits """ ).fetchall() dumped_ids = self.execute_query( f""" SELECT DISTINCT commit_id FROM code_change """ ).fetchall() dumped_ids = [x[0] for x in dumped_ids] not_dumped_commits = [x[1] for x in id_oid if x[0] not in dumped_ids] del dumped_ids del id_oid for i in range(0, len(not_dumped_commits), THREADS): proc = [mp.Process(target=self._dump_code_change, args=(oid,)) for oid in not_dumped_commits[i: i + THREADS]] for p in proc: p.start() while any([x.is_alive() for x in proc]): continue @timing(name="patches", is_stage=True) def _parse_patches(self): self.__init_commits(inverse=True) res = self.execute_query( f""" SELECT id, commit_id FROM code_change """ ).fetchall() cc_commit = {} for row in res: cc_commit[row[0]] = row[1] res = self.execute_query( """ SELECT code_change_id FROM patches """ ) not_dumped_commits = set(cc_commit.values()).difference({cc_commit[x[0]] for x in res}) not_dumped_commits = sorted([self.id_commit[id_] for id_ in not_dumped_commits]) del cc_commit for i in range(0, len(not_dumped_commits), THREADS): proc = [mp.Process(target=self._dump_code_change, args=(oid,)) for oid in not_dumped_commits[i: i + THREADS]] for p in proc: p.start() while any([x.is_alive() for x in proc]): continue @timing(name="async -> commits", is_stage=True) async def _async_parse_commits(self): loop = asyncio.get_event_loop() tasks = [loop.run_in_executor(self.executor, self._dump_commit, oid) for oid in self.commits] completed, _ = await asyncio.wait(tasks) for t in completed: logger.info(f"Dumped commit: {t.result()}") @timing(name="async -> code change", is_stage=True) async def _async_parse_code_change(self): loop = asyncio.get_event_loop() tasks = [loop.run_in_executor(self.executor, self._dump_code_change, oid) for oid in self.commits] completed, _ = await asyncio.wait(tasks) for t in completed: logger.info(f"Dumped Code Change for commit: {t.result()}") def process(self): if self.aio: self.loop.run_until_complete(self._parse_commits()) self.loop.run_until_complete(self._parse_code_change()) else: # self._parse_commits() self.__init_commits() self._parse_code_change() # self._parse_patches() def __del__(self): if self.aio: self.loop.close()
class GitStorage(BaseStorage): _backend = None def __init__(self, context, repo_path=None): self.context = context rp = IStorageInfo(context).path try: self.repo = Repository(discover_repository(rp)) except KeyError: # discover_repository may have failed. raise PathNotFoundError('repository does not exist at path') self.checkout() # defaults to HEAD. @property def empty_root(self): return {'': '_empty_root'} def _get_empty_root(self): return self.empty_root def _get_obj(self, path, cls=None): if path == '' and self._commit is None: # special case return self._get_empty_root() if self._commit is None: raise PathNotFoundError('repository is empty') root = self._commit.tree try: breadcrumbs = [] fragments = list(reversed(path.split('/'))) node = root oid = None while fragments: fragment = fragments.pop() if not fragment == '': # no empty string entries, also skips over '//' and # leaves the final node (if directory) as the tree. oid = node[fragment].oid node = self.repo.get(oid) breadcrumbs.append(fragment) if node is None: # strange. Looks like it's either submodules only # have entry nodes or pygit2 doesn't fully support # this. Try to manually resolve the .gitmodules # file. if cls is None: # Only return this if a specific type was not # expected. submods = parse_gitmodules(self.repo.get( root[GIT_MODULE_FILE].oid).data) submod = submods.get('/'.join(breadcrumbs)) if submod: fragments.reverse() return { '': '_subrepo', 'location': submod, 'path': '/'.join(fragments), 'rev': oid.hex, } if node and (cls is None or isinstance(node, cls)): return node except KeyError: # can't find what is needed in repo, raised by pygit2 raise PathNotFoundError('path not found') # not what we were looking for. if cls == Tree: raise PathNotDirError('path not dir') elif cls == Blob: raise PathNotFileError('path not file') raise PathNotFoundError('path not found') @property def _commit(self): return self.__commit @property def rev(self): if self.__commit: return self.__commit.hex return None @property def shortrev(self): # TODO this is an interim solution. if self.rev: return self.rev[:12] def basename(self, name): return name.split('/')[-1] def checkout(self, rev=None): # None maps to the default revision. if rev is None: rev = 'HEAD' try: self.__commit = self.repo.revparse_single(rev) except KeyError: if rev == 'HEAD': # probably a new repo. self.__commit = None return raise RevisionNotFoundError('revision %s not found' % rev) # otherwise a RevisionNotFoundError should be raised. def files(self): def _files(tree, current_path=None): results = [] for node in tree: if current_path: name = '/'.join([current_path, node.name]) else: name = node.name obj = self.repo.get(node.oid) if isinstance(obj, Blob): results.append(name) elif isinstance(obj, Tree): results.extend(_files(obj, name)) return results if not self._commit: return [] results = _files(self._commit.tree) return results def file(self, path): return self._get_obj(path, Blob).data def listdir(self, path): if path: tree = self._get_obj(path, Tree) else: if self._commit is None: return [] tree = self._commit.tree return [entry.name for entry in tree] def format(self, **kw): # XXX backwards compatibility?? return kw def log(self, start, count, branch=None, shortlog=False): """ start and branch are literally the same thing. """ def _log(iterator): for pos, commit in iterator: if pos == count: raise StopIteration yield { 'author': commit.committer.name, 'email': self._commit.committer.email, 'date': self.strftime(committer_dt(commit.committer)), 'node': commit.hex, 'rev': commit.hex, 'desc': commit.message } if start is None: # assumption. start = 'HEAD' try: self.repo.revparse_single(start) except KeyError: return [] try: rev = self.repo.revparse_single(start).hex except KeyError: raise RevisionNotFoundError('revision %s not found' % start) iterator = enumerate(self.repo.walk(rev, GIT_SORT_TIME)) return list(_log(iterator)) def pathinfo(self, path): obj = self._get_obj(path) if isinstance(obj, Blob): return self.format(**{ 'type': 'file', 'basename': self.basename(path), 'size': obj.size, 'date': self.strftime(committer_dt(self._commit.committer)), }) elif isinstance(obj, dict): # special cases are represented as dict. if obj[''] == '_subrepo': return self.format(**{ 'type': 'subrepo', 'date': '', 'size': 0, 'basename': self.basename(path), # extra field. 'obj': obj, }) elif obj[''] == '_empty_root': return self.format(**{ 'type': 'folder', 'date': '', 'size': 0, 'basename': self.basename(path), }) # Assume this is a Tree. return self.format(**{ 'basename': self.basename(path), 'size': 0, 'type': 'folder', 'date': '', }) def branches(self): return tuple( (b, self.repo.lookup_branch(b).target.hex) for b in self.repo.listall_branches() ) def tags(self): return tuple( (b[10:], self.repo.lookup_reference(b).target.hex) for b in self.repo.listall_references() if b.startswith('refs/tags') )
class CollectGit(object): """ Small Helper class for small repositories. This does not scale because we hold a lot of data in memory. """ _regex_comment = re.compile( r"(//[^\"\n\r]*(?:\"[^\"\n\r]*\"[^\"\n\r]*)*[\r\n]|/\*([^*]|\*(?!/))*?\*/)(?=[^\"]*(?:\"[^\"]*\"[^\"]*)*$)" ) _regex_jdoc_line = re.compile(r"(- |\+)\s*(\*|/\*).*") def __init__(self, path): if not path.endswith('.git'): if not path.endswith('/'): path += '/' path += '.git' self._log = logging.getLogger(self.__class__.__name__) self._path = path self._repo = Repository(self._path) self._hunks = {} self._file_actions = {} self._bugfix = {} self._msgs = {} self._days = {} self._cdays = {} self._branches = {} self._tags = {} self._dopts = GIT_DIFF_FIND_RENAMES | GIT_DIFF_FIND_COPIES self._SIMILARITY_THRESHOLD = 50 self._graph = nx.DiGraph() @classmethod def clone_repo(cls, uri, local_path): project_name = uri.split('/')[-1].split('.git')[0] repo_path = local_path + '/' + project_name + '/' if os.path.isdir(repo_path): c = subprocess.run(['git', 'fetch'], cwd=repo_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if c.returncode != 0: err = 'Error pulling repository {} to {}'.format( uri, repo_path) raise Exception(err) else: os.mkdir(repo_path) c = subprocess.run(['git', 'clone', uri, repo_path], cwd=repo_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if c.returncode != 0: err = 'Error cloning repository {} to {}'.format( uri, repo_path) raise Exception(err) return repo_path def _changed_lines(self, hunk): added_lines = [] deleted_lines = [] del_line = hunk['old_start'] add_line = hunk['new_start'] for line in hunk['content'].split('\n'): tmp = line[1:].strip() # is_comment = tmp.startswith('//') or tmp.startswith('/*') or tmp.startswith('*') if line.startswith('+'): added_lines.append((add_line, tmp)) del_line -= 1 if line.startswith('-'): deleted_lines.append((del_line, tmp)) add_line -= 1 del_line += 1 add_line += 1 return added_lines, deleted_lines def _comment_only_change(self, content): content = content + '\n' # required for regex to drop comments content = re.sub(self._regex_comment, "", content) removed = '' added = '' for line in content.split('\n'): line = re.sub( r"\s+", " ", line, flags=re.UNICODE ) # replace all kinds of whitespaces (also multiple) with sińgle whitespace if not re.match(self._regex_jdoc_line, line): if line.startswith('-'): removed += line[1:].strip() elif line.startswith('+'): added += line[1:].strip() return removed == added def _blame_lines(self, revision_hash, filepath, strategy, ignore_lines=False, validated_bugfix_lines=False): """We want to find changed lines for one file in one commit (from the previous commit). For this we are iterating over the diff and counting the lines that are deleted (changed) from the original file. We ignore all added lines. ignore_lines is already specific to all changed hunks of the file for which blame_lines is called """ c = self._repo.revparse_single('{}'.format(revision_hash)) self._hunks[revision_hash] = self._get_hunks(c) changed_lines = [] if revision_hash not in self._hunks.keys( ) or not self._hunks[revision_hash]: return changed_lines for h in self._hunks[revision_hash]: if h['new_file'] != filepath: continue # only whitespace or comment changes in the hunk, ignore if strategy == 'code_only' and self._comment_only_change( h['content']): self._log.debug( 'detected whitepace or comment only change in {} for {}'. format(revision_hash, filepath)) continue added, deleted = self._changed_lines(h) for dt in deleted: if dt not in changed_lines and dt[1]: if strategy == 'code_only' and dt[1].startswith( ('//', '/*', '*')): continue # we may only want validated lines if validated_bugfix_lines is not False: if dt[0] not in validated_bugfix_lines: continue # we may ignore lines, e.g., refactorings if ignore_lines: ignore = False for start_line, end_line in ignore_lines: if start_line <= dt[0] <= end_line: ignore = True break # if we hit the line in our ignore list we continue to the next if ignore: # self._log.warn('ignore line {} in file {} in commit {} because of refactoring detection'.format(dt[0], filepath, revision_hash)) continue changed_lines.append(dt) return changed_lines def blame(self, revision_hash, filepath, strategy='code_only', ignore_lines=False, validated_bugfix_lines=False): """Collect a list of commits where the given revision and file were last changed. Uses git blame. :param str revision_hash: Commit for which we want to collect blame commits. :param str filepath: File for which we want to collect blame commits. :rtype: list :returns: A list of tuples of blame commits and the original file for the given parameters. """ commits = [] # - ignore if commit is not in graph if revision_hash not in self._graph: return [] # # - ignore package-info.java # if strategy == 'code_only' and filepath.lower().endswith('package-info.java'): # self._log.debug('skipping blame on revision: {} for file {} because it is package-info.java'.format(revision_hash, filepath)) # return [] # # - ignore test/ /test/ example/ examples/ # if strategy == 'code_only' and re.match(self._regex_test_example, filepath): # self._log.debug('skipping blame on revision: {} for file {} because it is a test or an example'.format(revision_hash, filepath)) # return [] # bail on multiple parents parents = list(self._graph.predecessors(revision_hash)) if len(parents) > 1: self._log.debug( 'skipping blame on revision: {} because it is a merge commit'. format(revision_hash)) return [] changed_lines = self._blame_lines(revision_hash, filepath, strategy, ignore_lines, validated_bugfix_lines) parent_commit = self._repo.revparse_single('{}^'.format(revision_hash)) blame = self._repo.blame(filepath, flags=GIT_BLAME_TRACK_COPIES_SAME_FILE, newest_commit=parent_commit.hex) for lineno, line in changed_lines: # returns blamehunk for specific line try: bh = blame.for_line(lineno) except IndexError as e: # this happens when we have the wrong parent node bla = 'tried to get file: {}, line: {}, revision: {}, blame commit: {}'.format( filepath, lineno, revision_hash, str(bh.orig_commit_id)) self._log.error(bla) raise # this is critical inducing_commit = self._repo.revparse_single(str( bh.orig_commit_id)) # start = bh.orig_start_line_number # lines = bh.lines_in_hunk # final_start = bh.final_start_line_number # print(revision_hash, '->', inducing_commit.hex) # print('original: {}: {}'.format(lineno, line)) # print('{},{}: {},{}'.format(start, lines, final_start, lines)) # blame_lines = [] # for hunk in self._hunks[inducing_commit.hex]: # if hunk['new_file'] != bh.orig_path: # continue # ls = final_start # for i, blame_line in enumerate(hunk['content'].split('\n')): # if blame_line[1:].strip() and line[1:].strip() and blame_line[1:] == line[1:]: # print('blame: {}:{}'.format(ls, blame_line)) # ls += 1 commits.append((inducing_commit.hex, bh.orig_path)) # make unique return list(set(commits)) def commit_information(self, revision_hash): obj = self._repo.get(revision_hash) return { 'author_name': obj.author.name, 'author_email': obj.author.email, 'committer_name': obj.committer.name, 'committer_email': obj.committer.email, 'committer_date_utc': datetime.fromtimestamp(obj.commit_time, tz=timezone.utc), 'committer_date': obj.commit_time, 'committer_date_offset': obj.commit_time_offset, 'message': obj.message, 'file_actions': self._file_actions[revision_hash] } def file_actions(self, revision_hash): return self._file_actions[revision_hash] def all_files(self, revision_hash): # 1. checkout repo self._checkout_revision(revision_hash) # 2. list files return self._list_files() def first_occurence(self, filename): # file rename tracking is not possible currently in libgit, see: # https://github.com/libgit2/libgit2/issues/3041 # find first occurence of file with git cli # git log --follow --diff-filter=A --find-renames=40% foo.js path = self._path.replace('.git', '') c = subprocess.run([ 'git', 'log', '--all', '--pretty=tformat:"%H %ci"', '--follow', '--diff-filter=A', '--find-renames=80%', '--', filename ], cwd=path, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if c.returncode != 0: err = 'Error finding first occurrence of file: {}'.format(filename) self._log.error(err) self._log.error(c.stderr) raise Exception(err) full = c.stdout.decode('utf-8') try: first_line = full.split('\n')[-2] except IndexError: if not full: print('no git log for file {}'.format(filename)) print(full) raise first_date = ' '.join(first_line.split(' ')[1:]).replace('"', '') dt = datetime.strptime( first_date, '%Y-%m-%d %H:%M:%S %z' ) # we can do this here because we control the input format, %z does not cover +01:00 just +100 (at least in 3.6) return dt def tags(self): regex = re.compile('^refs/tags') ret = [] for tagref in filter(lambda r: regex.match(r), self._repo.listall_references()): tag = self._repo.lookup_reference(tagref) target = self._repo.lookup_reference(tagref).peel() ret.append({ 'name': tag.name.replace('refs/tags/', ''), 'revision_hash': target.id }) return ret def _checkout_revision(self, revision): """Checkout via shell, we ignore stdout output.""" path = self._path.replace('.git', '') c = subprocess.run(['git', 'checkout', '-q', '-f', revision], cwd=path, stdout=subprocess.PIPE) return c.returncode == 0 def _list_files(self): """The slower list_files""" path = self._path.replace('.git', '') ret = [] for root, dirs, files in os.walk(path): for file in files: filepath = os.path.join(root, file) relative_filepath = filepath.replace(path, '') ret.append(relative_filepath) return ret def _list_files2(self): """The faster list_files (relies on find command)""" path = self._path.replace('.git', '') lines = subprocess.check_output(['find', '.', '-iname', '*.java'], cwd=path) files = [] for f in lines.decode('utf-8').split('\n'): if f.lower().endswith('.java'): files.append(f.replace('./', '')) return files def _get_hunks(self, commit): diffs = [] hunks = [] # for initial commit (or orphan commits) pygit2 needs some special attention initial = False if not commit.parents: initial = True diffs.append((None, commit.tree.diff_to_tree(context_lines=0, interhunk_lines=1))) # we may have multiple parents (merge commit) for parent in commit.parents: # we need all information from each parent because in a merge each parent may add different files tmp = self._repo.diff(parent, commit, context_lines=0, interhunk_lines=1) tmp.find_similar(self._dopts, self._SIMILARITY_THRESHOLD, self._SIMILARITY_THRESHOLD) diffs.append((parent.hex, tmp)) for parent, diff in diffs: checked_paths = set() for patch in diff: if patch.delta.new_file.path in checked_paths: self._log.warn('already have {} in checked_paths'.format( patch.delta.new_file.path)) continue mode = 'X' if patch.delta.status == 1: mode = 'A' elif patch.delta.status == 2: mode = 'D' elif patch.delta.status == 3: mode = 'M' elif patch.delta.status == 4: mode = 'R' elif patch.delta.status == 5: mode = 'C' elif patch.delta.status == 6: mode = 'I' elif patch.delta.status == 7: mode = 'U' elif patch.delta.status == 8: mode = 'T' # diff to tree gives D for inital commit otherwise if initial: mode = 'A' # we may have hunks to add if patch.hunks and commit.hex not in self._hunks.keys(): self._hunks[commit.hex] = [] # add hunks for hunk in patch.hunks: # initial is special case if initial: content = ''.join( ['+' + l.content for l in hunk.lines]) hunks.append({ 'header': hunk.header, 'new_file': patch.delta.new_file.path, 'new_start': hunk.old_start, 'new_lines': hunk.old_lines, 'old_start': hunk.new_start, 'old_lines': hunk.new_lines, 'content': content }) else: content = ''.join( [l.origin + l.content for l in hunk.lines]) hunks.append({ 'header': hunk.header, 'new_file': patch.delta.new_file.path, 'new_start': hunk.new_start, 'new_lines': hunk.new_lines, 'old_start': hunk.old_start, 'old_lines': hunk.old_lines, 'content': content }) return hunks def _changed_files(self, commit): changed_files = [] diffs = [] # for initial commit (or orphan commits) pygit2 needs some special attention initial = False if not commit.parents: initial = True diffs.append((None, commit.tree.diff_to_tree(context_lines=0, interhunk_lines=1))) # we may have multiple parents (merge commit) for parent in commit.parents: # we need all information from each parent because in a merge each parent may add different files tmp = self._repo.diff(parent, commit, context_lines=0, interhunk_lines=1) tmp.find_similar(self._dopts, self._SIMILARITY_THRESHOLD, self._SIMILARITY_THRESHOLD) diffs.append((parent.hex, tmp)) for parent, diff in diffs: checked_paths = set() for patch in diff: if patch.delta.new_file.path in checked_paths: self._log.warn('already have {} in checked_paths'.format( patch.delta.new_file.path)) continue mode = 'X' if patch.delta.status == 1: mode = 'A' elif patch.delta.status == 2: mode = 'D' elif patch.delta.status == 3: mode = 'M' elif patch.delta.status == 4: mode = 'R' elif patch.delta.status == 5: mode = 'C' elif patch.delta.status == 6: mode = 'I' elif patch.delta.status == 7: mode = 'U' elif patch.delta.status == 8: mode = 'T' # diff to tree gives D for inital commit otherwise if initial: mode = 'A' # we may have hunks to add if patch.hunks and commit.hex not in self._hunks.keys(): self._hunks[commit.hex] = [] # add hunks for hunk in patch.hunks: # initial is special case if initial: content = ''.join( ['+' + l.content for l in hunk.lines]) self._hunks[commit.hex].append({ 'header': hunk.header, 'new_file': patch.delta.new_file.path, 'new_start': hunk.old_start, 'new_lines': hunk.old_lines, 'old_start': hunk.new_start, 'old_lines': hunk.new_lines, 'content': content }) else: content = ''.join( [l.origin + l.content for l in hunk.lines]) self._hunks[commit.hex].append({ 'header': hunk.header, 'new_file': patch.delta.new_file.path, 'new_start': hunk.new_start, 'new_lines': hunk.new_lines, 'old_start': hunk.old_start, 'old_lines': hunk.old_lines, 'content': content }) # collect line stats if initial: fa = { 'lines_added': patch.line_stats[2], 'lines_deleted': patch.line_stats[1], 'changeset_size': len(diff), 'parent': None } else: fa = { 'lines_added': patch.line_stats[1], 'lines_deleted': patch.line_stats[2], 'changeset_size': len(diff), 'parent': parent } #if mode == 'R': # print('R {} -> {}, sim: {}'.format(patch.delta.old_file.path, patch.delta.new_file.path, patch.delta.similarity)) if mode in ['C', 'R']: changed_file = [ mode, patch.delta.new_file.path, patch.delta.old_file.path, fa ] else: changed_file = [mode, patch.delta.new_file.path, None, fa] checked_paths.add(patch.delta.new_file.path) changed_files.append(changed_file) return changed_files def collect(self): # list all branches for branch in list(self._repo.branches): self._collect_branch(branch) # list all tags for obj in self._repo: tag = self._repo[obj] if tag.type == GIT_OBJ_TAG: self._collect_branch(tag, is_tag=True) return self._graph def _collect_branch(self, branch, is_tag=False): if type(branch) == str: branch = self._repo.branches[branch] # add nodes to graph try: for c in self._repo.walk(branch.target): self._graph.add_node(c.hex) # branch stuff, used for traversing backwards for tags in svn->git conversions # if c.hex not in self._branches.keys(): # self._branches[c.hex] = [] # what about tags which are also on branches? # if is_tag: # self._tags[c.hex] = branch.name # else: # self._branches[c.hex].append(branch.branch_name) # add msg # self._msgs[c.hex] = c.message # add days, we use this later for lookup # day = str(datetime.fromtimestamp(c.commit_time, tz=timezone.utc).date()) # if day not in self._days.keys(): # self._days[day] = [] # self._days[day].append(c.hex) # add for convenience for OntdekBaanBfs # self._cdays[c.hex] = day # add changed files per node # if c.hex not in self._file_actions.keys(): # self._file_actions[c.hex] = self._changed_files(c) # still too expensive # self._create_hunks(c) # add edges to graph for c in self._repo.walk(branch.target): for p in c.parents: self._graph.add_edge(p.hex, c.hex) except ValueError as e: pass
class GitRepo(object): ''' git repo class ''' def __init__(self, path): try: self.__repo = Repository(path) except Exception as e: self.__repo = None print(e) def get_info(self): if not self.__repo: return None signature = self.__repo.default_signature result = { 'path': self.__repo.path, 'workdir': self.__repo.workdir, 'bare': self.__repo.is_bare, 'empty': self.__repo.is_empty, 'name': signature.name, 'email': signature.email, 'time': signature.time, 'offset': signature.offset, } return result def get_all_references(self): return self.__repo.listall_references() def get_reference(self, name): if not self.__repo: return None ref = None try: ref = self.__repo.lookup_reference(name) except Exception as e: print(e) return ref def get_all_branches(self, branch_type=None): if not self.__repo: return None if branch_type: return self.__repo.listall_branches(branch_type) r = self.__repo.listall_branches(GIT_BRANCH_LOCAL | GIT_BRANCH_REMOTE) return r def get_branch(self, name, branch_type=GIT_BRANCH_LOCAL): if not self.__repo: return None return self.__repo.lookup_branch(name, branch_type) def check_branch(self, name, branch_type=None): if not branch_type: if '/' in name: branch_type = GIT_BRANCH_REMOTE else: branch_type = GIT_BRANCH_LOCAL try: result = self.get_branch(name, branch_type) return result except Exception as e: print(e) return False def get_current_commit(self): if not self.__repo: return None commit = self.__repo.revparse_single('HEAD') return self.get_commit(commit) def get_commit_by_branch(self, branch): if not self.__repo: return None query = 'refs/' if hasattr(branch, 'remote_name'): query += 'remotes/' else: query += 'heads/' query += branch.branch_name try: ref = self.get_reference(query) commit = ref.target return self.get_commit(commit) except Exception as e: print(e) return None def get_commit_by_tag(self, tag): if self.__repo is None: return None if tag: commit = tag.get_object() return self.get_commit(commit) return None def get_commit(self, oid_or_commit): ''' return a commit w/ json ''' if not self.__repo or not oid_or_commit: return None try: commit = oid_or_commit if not isinstance(oid_or_commit, Commit): commit = self.__repo.get(oid_or_commit) if commit and commit.type == GIT_OBJ_COMMIT: # t1 = self.__repo.revparse_single('HEAD^') # t2 = self.__repo.revparse_single('HEAD^^') # patches = self.__repo.diff(t1, t2) # for p in patches: # print(p.new_file_path) result = { 'id': str(commit.id), 'author': commit.author.name, 'commiter': commit.committer.name, 'message': commit.message, 'message_encoding': commit.message_encoding, 'tree': str(commit.tree_id), 'parent': [str(pid) for pid in commit.parent_ids], 'time': str(commit.commit_time), 'time_offset': str(commit.commit_time_offset), } return result except Exception as e: print(e) return None def get_commits(self, depth=10, oid_or_commit=None): result = [] if depth == 0: return result if oid_or_commit: commit = self.get_commit(oid_or_commit) else: commit = self.get_current_commit() if not commit: return result # TODO: starting from a commit or its parent # TODO: author result.append(commit) depth -= 1 if commit and commit['parent']: for parent in commit['parent']: result.extend(self.get_commits(depth, parent)) return result def get_commits_by_branch(self, name, path=None): if not self.__repo: return None if self.check_branch(name): ref = self.get_reference('refs/heads/' + name) if ref: commit = ref.target commits = self.get_commits(commit) result = {} for key, val in commits.items(): if self.check_commit_by_path(val, path): result[key] = val return result return None def check_tag(self, name): try: ref = self.get_reference('refs/tags/' + name) return ref except Exception: return False def get_commits_by_tag(self, tag, path=None): if not self.__repo: return None if tag: commit = tag.target commits = self.get_commits(commit) result = {} for key, val in commits.items(): if self.check_commit_by_path(val, path): result[key] = val return result return None def check_commit_by_path(self, commit, path): if not commit: return False if path is None or len(path) == 0: return True result = self.get_tree(commit['tree']) if not isinstance(path, list): path = path.strip().split('/') for name in path: name = name.strip() if name in result: oid = result[name] result = self.get_tree(oid) if not result: result = self.get_blob(oid) return result is not None def get_tree(self, oid, ppath=None): if not self.__repo: return None try: tree = self.__repo.get(oid) if tree and tree.type == GIT_OBJ_TREE: result = {} for entry in tree: item = { 'id': str(entry.id) } obj = self.__repo.get(entry.id) if obj.type == GIT_OBJ_BLOB: item['type'] = 'blob' elif obj.type == GIT_OBJ_TREE: item['type'] = 'tree' item['ppath'] = ppath result[entry.name] = item return result except Exception as e: print(e) return None def get_tree_by_commit(self, commit, path=None): if not commit: return None result = self.get_tree(commit['tree']) if not path: return result # if not isinstance(path, list): # path = path.strip().split('/') try: for name in path: oid = result[name]['id'] p = result[name]['ppath'] p = name if not p else p + '/' + name result = self.get_tree(oid, p) if not result: break except Exception as e: print(e) result = None return result def get_current_root(self): tree = self.get_current_commit() if tree: return self.get_tree(tree['tree']) return None def get_whole_tree(self, oid): ''' tree w/ json ''' if not self.__repo: return None result = tree_walker(self.__repo, oid) return result def get_blob(self, oid): ''' blob w/ json ''' if not self.__repo or not oid: return None try: blob = self.__repo.get(oid) if blob and blob.type == GIT_OBJ_BLOB: content = blob.is_binary and None or blob.data.decode( 'utf8', 'ignore') result = { 'id': str(blob.id), 'content': content, 'size': blob.size, } return result except Exception as e: print(e) return None def get_blob_by_commit(self, commit, path=None): try: tree = self.get_tree_by_commit(commit, path[:-1]) oid = tree[path[-1]]['id'] result = self.get_blob(oid) return result except Exception as e: print(e) return None def get_tag(self, oid): ''' blob w/ json ''' if not self.__repo or not oid: return None try: tag = self.__repo.get(oid) if tag and tag.type == GIT_OBJ_TAG: result = { 'id': str(oid), 'name': tag.name, 'target': str(tag.target.id), 'tagger': tag.tagger, 'message': tag.message, } return result except Exception as e: print(e) return None def get_patches(self, a=None, b=None): try: if not a: a = 'HEAD' if not b: b = a + '^' t1 = self.__repo.revparse_single(a) t2 = self.__repo.revparse_single(b) patches = self.__repo.diff(t1, t2) result = [] for patch in patches: p = { 'old_file_path': patch.old_file_path, 'new_file_path': patch.new_file_path, 'old_oid': str(patch.old_oid), 'new_oid': str(patch.new_oid), 'status': patch.status, 'similarity': patch.similarity, 'additions': patch.additions, 'deletions': patch.deletions, 'binary': patch.is_binary, 'hunks': [], } for hunk in patch.hunks: h = { 'old_start': hunk.old_start, 'old_lines': hunk.old_lines, 'new_start': hunk.new_start, 'new_lines': hunk.new_lines, 'lines': hunk.lines, } p['hunks'].append(h) result.append(p) return result except Exception as e: print(e) return None
class Document(object): ''' Class representing a document, interacts with the git database ''' def __init__( self, name, create=False, rootPath=None ): ''' Constructor Args: name The name of the document create If true, will create a document rootPath The rootPath to use (if not supplied, uses default) Exceptions: RepoNotFound if repository isn't found ''' if not rootPath: rootPath = DEFAULT_ROOT_PATH targetDir = os.path.join( rootPath, name + '.git' ) if create: # Create a bare repository self.repo = init_repository( targetDir, True ) self._CreateMasterBranch() else: try: self.repo = Repository( targetDir ) except KeyError: raise RepoNotFound() def _CreateMasterBranch( self ): ''' Creates the master branch on the repo w/ default file. For now this is just a file named layout ''' commitId = CommitBlob( self.repo, '', SECTION_INDEX_FILENAME, 'Initial commit' ) self.repo.create_reference( MASTER_REF, commitId ) @staticmethod def _IsSectionRef( refName ): ''' Checks if a refererence name refers to a section Args: refName: The reference name Returns: A boolean ''' return refName.startswith( SECTION_REF_PREFIX ) @staticmethod def _RefNameToSectionName( refName ): ''' Converts a reference name to a section name Args: ref: The reference name ''' return refName[ len(SECTION_REF_PREFIX) : ] def _SectionRefs( self ): ''' Gets an iterator over the section refs ''' return ( ( self._RefNameToSectionName( ref ), self.repo.lookup_reference( ref ), ) for ref in self.repo.listall_references() if self._IsSectionRef( ref ) ) def Sections( self ): ''' Gets an iterator over all the sections ''' return ( Section( name, self.repo[ref.oid], self.repo ) for name, ref in self._SectionRefs() ) def CurrentSections( self ): ''' Gets the current sections with their positions Returns: A list of tuples ( position, section ) ''' return enumerate( self._CurrentSections() ) def _CurrentSections( self ): ''' Internal method to get the current sections in order, without position numbers Returns: An iterator over the sections ''' index = SectionIndex(self.repo) for s in index.CurrentSections(): yield self.FindSection(s.name) def FindSection( self, name ): ''' Finds a section by name Args: name The name of the section to find Returns: The section if found Exceptions: SectionNotFound if section not found ''' try: ref = self.repo.lookup_reference( SECTION_REF_PREFIX + name ) except KeyError: raise SectionNotFound() return Section( name, self.repo[ref.oid], self.repo ) def AddSection( self, name, content='' ): ''' Creates a new section Args: name The name of the section content The optional initial content of the section Returns: The new Section object ''' # TODO: Should probably make # sure no such section exists commitId = CommitBlob( self.repo, content, name, 'Created section ' + name ) ref = self.repo.create_reference( SECTION_REF_PREFIX + name, commitId ) index = SectionIndex(self.repo) index.AddSection( name ) index.Save( self.repo ) return Section( name, self.repo[ ref.oid ], self.repo ) def RemoveSection( self, name ): ''' Removes a section. This function does not actually delete the data associated with a section, it just removes it from the index. Args: name The name of the section to remove ''' index = SectionIndex( self.repo ) index.RemoveSection( name ) index.Save( self.repo )
testrepo = None repo.addfile(file.name) testrepo = Repository(dir.name) index = testrepo.index index.read() repo = GitRepo(dir.name) testrepo = Repository(dir.name) # print('Commitloglänge', len(testrepo.walk(testrepo.head.target)), 0) testrepo = None # Commit 1 repo.commit() testrepo = Repository(dir.name) all_refs = testrepo.listall_references() print('Refs', all_refs) commits = testrepo.walk(testrepo.head.target) print('Commitloglänge', len(list(testrepo.walk(testrepo.head.target))), 1) testrepo = None # Commit 2 testrepo = Repository(dir.name) # print('Commitloglänge', len(testrepo.walk(testrepo.head.target)), 0) testrepo = None file.write(b'Test2\n') file.write(b'Test3\n') f = open(file.name, 'w') f.write('Test2') f.write('Test3')
class GitMixin(object): tag_or_remote_regex = re.compile('^refs/(tags|remotes)/(.*)') def __init__(self): where = GitOperations.get_repository_location(self.user, self.name) self.ondisk = Repository(where) def refresh(self): creds = GitOperations.get_credentials(self.git_user, self.user) for remote in self.ondisk.remotes: remote.credentials = creds remote.fetch() # update current reference master_ref = self.ondisk.lookup_reference('refs/heads/master') remote_ref = self.ondisk.lookup_reference('refs/remotes/origin/master') master_ref.set_target(remote_ref.target) def filter_references(self, regex): return [ref for ref in self.ondisk.listall_references() if regex.match(ref)] def get_commit_time(self, name): ref = self.ondisk.revparse_single(name) if isinstance(ref, Tag): return ref.get_object().commit_time if isinstance(ref, Commit): return ref.commit_time raise GitException('invalid reference: commit time could not be found.') # pragma: no cover def get_latest_refs(self, count=None): info = self.filter_references(GitMixin.tag_or_remote_regex) refs = list(zip(info, map(self.get_commit_time, info))) refs.sort(key=itemgetter(1), reverse=True) def ref_info(info): (ref, commit_time) = info what, name = GitMixin.tag_or_remote_regex.findall(ref)[0] return (what, name, commit_time) refs = map(ref_info, refs) if not count: return refs return islice(refs, count) def filter_commits(self, flags=0): all_commits = self.ondisk.walk(self.ondisk.head.target, flags) emails = [ue.email for ue in self.user.emails.all()] return filter(lambda commit: commit.author.email in emails, all_commits) def get_commits(self, count=None): all_commits = self.filter_commits(GIT_SORT_TOPOLOGICAL) if not count: return all_commits return islice(all_commits, count) def get_commit_count(self): return len(list(self.filter_commits())) def get_shorthand_of_branch(self, branch): commit = self.ondisk.lookup_branch(branch) if commit: return commit.shorthand return '(none)' def get_sha1_of_branch(self, branch): commit = self.ondisk.lookup_branch(branch) if commit: return str(commit.get_object().id)[:6] return '(none)' def get_numstat(self, commit): diff = None try: previous_commit = self.ondisk.revparse_single(str(commit.id) + '^') diff = self.ondisk.diff(previous_commit, commit) except KeyError: # likely we hit the very first commit. diff = commit.tree.diff_to_tree(swap=True) additions, deletions = 0, 0 for patch in diff: additions += patch.additions deletions += patch.deletions return (len(diff), additions, deletions) def get_first_updated(self): all_commits = self.ondisk.walk(self.ondisk.head.target, GIT_SORT_TIME | GIT_SORT_REVERSE) first_commit = next(all_commits) return first_commit.commit_time def get_last_updated(self): all_commits = self.ondisk.walk(self.ondisk.head.target, GIT_SORT_TIME) last_commit = next(all_commits) return last_commit.commit_time def get_file_count(self): diff = self.ondisk.head.get_object().tree.diff_to_tree() return len([patch.old_file_path for patch in diff]) def get_line_count(self): diff = self.ondisk.head.get_object().tree.diff_to_tree() return sum([patch.deletions for patch in diff]) def get_author_count(self): commits = self.filter_commits() return len(set([commit.author.email for commit in commits])) def commits_between(self, start, end): all_commits = self.filter_commits(GIT_SORT_TIME | GIT_SORT_REVERSE) starting = dropwhile(lambda obj: obj.commit_time < start, all_commits) return takewhile(lambda obj: obj.commit_time <= end, starting) @staticmethod def by_day(obj): # we want to group our commit times by the day. so convert # timestamp -> date -> timestamp new_date = date.fromtimestamp(obj.commit_time) new_date += timedelta(days=1) return timegm(new_date.timetuple()) @staticmethod def group_by(series): result = groupby(series, GitMixin.by_day) return [{'date': commit_date, 'value': len(list(commits))} for commit_date, commits in result] def histogram(self, start, end): series = self.commits_between(start, end) return GitMixin.group_by(series)