def open_repository(url, target_directory): """ Make a connection from a remote git repository into a local directory. Args: url(string): The remote github url of the repository target_directory(string): The local target directory Returns: pygit2.repo: The repository object created """ git_url = urlparse.urlparse(url) username = git_url.netloc.split('@')[0]\ if '@' in git_url.netloc else 'git' try: credentials = pygit2.credentials.KeypairFromAgent(username) except AttributeError as e: pygit2_parse_error(e) # If local directory exists, then make a connection to it # Otherwise, clone the remote repo into the new directory if os.path.isdir(target_directory): shaker.libs.logger.Logger().debug("open_repository: " "Opening url '%s' " "with existing local repository '%s'" % (url, target_directory)) repo = pygit2.Repository(target_directory) else: # Try to use pygit2 0.22 cloning try: shaker.libs.logger.Logger().debug("open_repository: " "Trying to open repository " "using pygit2 0.22 format") repo = pygit2.clone_repository(url, target_directory, credentials=credentials) except TypeError as e: shaker.libs.logger.Logger().debug("open_repository: " "Failed to detect pygit2 0.22") shaker.libs.logger.Logger().debug("open_repository: " "Trying to open repository " "using pygit2 0.23 format") # Try to use pygit2 0.23 cloning callbacks = pygit2.RemoteCallbacks(credentials) repo = pygit2.clone_repository(url, target_directory, callbacks=callbacks) shaker.libs.logger.Logger().debug(":open_repository: " "Cloning url '%s' into local repository '%s'" % (url, target_directory)) origin = filter(lambda x: x.name == 'origin', repo.remotes) if not origin: repo.create_remote('origin', url) origin = filter(lambda x: x.name == 'origin', repo.remotes) origin[0].credentials = credentials return repo
def test_pygit2_parse_error__preserves_backtrace(self): def sub_func(): x = {} x.i_should_throw() try: try: sub_func() except AttributeError as e: pygit2_utils.pygit2_parse_error(e) self.fail("Should have thrown an exception") except: tb = traceback.extract_tb(sys.exc_info()[2]) filename,lineno,method,code = tb[-1] self.assertEqual(method, "sub_func") self.assertEqual(code, "x.i_should_throw()")
def test_pygit2_parse_error__credentialserror(self): """ Test pygit2_parse_error raises correct exception on credentials error """ e = pygit2.GitError("Unsupported URL protocol") pygit2_utils.pygit2_parse_error(e)
def test_pygit2_parse_error__attributeerror(self): """ Test pygit2_parse_error raises correct exception on attribute error """ e = AttributeError("'module' object has no attribute 'KeypairFromAgent'") pygit2_utils.pygit2_parse_error(e)