def init_test_repo(): """ Create a test repo, change to directory """ mkdir(config.TEST_REPO) Repo.init(config.TEST_REPO) chdir(config.TEST_REPO)
def init(cls, path='.'): """Initialise a new git-papers repo at the given path and commit the basic directory structure.""" # TODO: do we need seperate .db directory? try: Repo(path) except NotGitRepository: pass else: raise RepoInitialised() Repo.init(path) app = cls(path) emptyfiles = ['.index', '.tags', '.toread'] for path in emptyfiles: try: with open(path, 'w'): pass except (IOError, OSError) as e: from shutil import rmtree # TODO: remove created emptyfiles rmtree(osp.join(path, '.git')) raise FileCreationFailed(e.message) app.commit(emptyfiles, INIT) return app
def new(self, path, desc=None, bare=True): """ Create a new bare repo.Local instance. :param path: Path to new repo. :param desc: Repo description. :param bare: Create as bare repo. :returns: New repo.Local instance. """ if os.path.exists(path): raise RepoError('Path already exists: %s' % path) try: os.mkdir(path) if bare: Repo.init_bare(path) else: Repo.init(path) repo = Local(path) if desc: repo.setDescription(desc) version = repo.addVersion() version.save('Box Initialization') return repo except Exception, e: traceback.print_exc() raise RepoError('Error creating repo')
def do_import(commits, repo_loc, overwrite = True, author_="Règlement général <*****@*****.**>"): if exists(repo_loc): if overwrite: print("Deleting existing output directory: %s" % repo_loc) shutil.rmtree(repo_loc) os.mkdir(repo_loc) repo = Repo.init(repo_loc) else: repo = Repo(repo_loc) else: os.mkdir(repo_loc) repo = Repo.init(repo_loc) print("Importing %d commit(s)" % len(commits)) for i, commit in enumerate(commits): date = commit[0] print("Commit %d dated %s, %d items" % (i, str(date), len(commit[1]))) print(" authored by %s" % author_) paths_added, paths_removed = create_tree(commit, repo_loc, readme=False, main=commit[2] if len(commit) == 3 else {}) repo.stage([path.encode(sys.getfilesystemencoding()) for path in set(paths_added)]) index = repo.open_index() print(" Removing %d files" % len(paths_removed)) for p in paths_removed: del index[p.encode(sys.getfilesystemencoding())] index.write() author = bytes(author_, "UTF-8") repo.do_commit( bytes("Version du %s" % date.strftime(FMT), "UTF-8"), committer=author, commit_timestamp=date.timestamp(), commit_timezone=int(TZ_PARIS.localize(date).strftime("%z")) * 36) ## create tag tag_name = bytes(date.strftime(ISO_8601), "UTF-8") object = parse_object(repo, "HEAD") tag = Tag() tag.tagger = author tag.name = tag_name tag.message = b'' tag.object = (type(object), object.id) tag.tag_time = int(time.time()) tag.tag_timezone = int(TZ_PARIS.localize(date).strftime("%z")) * 36 repo.object_store.add_object(tag) tag_id = tag.id repo.refs[b'refs/tags/' + tag_name] = tag_id repo.close()
def init_tmp_repo(): """ Create a test repo, change to directory """ log.info(__name__ + ':: Creating test repo.') if exists(config['deploy.test_repo']): rmtree(config['deploy.test_repo']) mkdir(config['deploy.test_repo']) Repo.init(config['deploy.test_repo']) chdir(config['deploy.test_repo'])
def test_load_ignore(self): tmp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) repo = Repo.init(tmp_dir) with open(os.path.join(repo.path, '.gitignore'), 'wb') as f: f.write(b'/foo/bar\n') f.write(b'/dir2\n') f.write(b'/dir3/\n') os.mkdir(os.path.join(repo.path, 'dir')) with open(os.path.join(repo.path, 'dir', '.gitignore'), 'wb') as f: f.write(b'/blie\n') with open(os.path.join(repo.path, 'dir', 'blie'), 'wb') as f: f.write(b'IGNORED') p = os.path.join(repo.controldir(), 'info', 'exclude') with open(p, 'wb') as f: f.write(b'/excluded\n') m = IgnoreFilterManager.from_repo(repo) self.assertTrue(m.is_ignored('dir/blie')) self.assertIs(None, m.is_ignored(os.path.join('dir', 'bloe'))) self.assertIs(None, m.is_ignored('dir')) self.assertTrue(m.is_ignored(os.path.join('foo', 'bar'))) self.assertTrue(m.is_ignored(os.path.join('excluded'))) self.assertTrue(m.is_ignored(os.path.join( 'dir2', 'fileinignoreddir'))) self.assertFalse(m.is_ignored('dir3')) self.assertTrue(m.is_ignored('dir3/')) self.assertTrue(m.is_ignored('dir3/bla'))
def TestRepo(): checkout = Repo.init(tempfile.mkdtemp()) with open(os.path.join(checkout.path, 'foo'), 'w') as fp: fp.write('monty') with open(os.path.join(checkout.path, 'bar'), 'w') as fp: fp.write('python') sub_path = os.path.join(checkout.path, 'sub') os.mkdir(sub_path) with open(os.path.join(sub_path, 'foo'), 'w') as fp: fp.write('sub_monty') with open(os.path.join(sub_path, 'bar'), 'w') as fp: fp.write('sub_python') checkout.stage(['foo', 'bar', os.path.join('sub', 'foo'), os.path.join('sub', 'bar')]) checkout.do_commit( 'The first commit', committer='John Doe <*****@*****.**>' ) bare = Repo.init_bare(tempfile.mkdtemp()) client, host_path = get_transport_and_path(checkout.path) refs = client.fetch( host_path, bare, determine_wants=bare.object_store.determine_wants_all, ) bare["HEAD"] = refs["HEAD"] bare["refs/heads/master"] = refs["refs/heads/master"] return bare, checkout
def setUp(self): self.config = testing.setUp() self.config.add_route('view_wiki', '/wiki/{project}/{page:.*}') self.config.add_route('edit', "/edit/{project}/{page:.*}") #create an empty repository self.tmpdir = tempfile.mkdtemp() self.repo = Repo.init(self.tmpdir) #populate with a new home page: with open("%s/%s"%(self.tmpdir, "Home.md"), "w") as f: f.write("hello wiki") #create a page in a subdirectory as well mkdir_p("%s/%s"%(self.tmpdir, "testsubdir")) home_md = open("%s/%s"%(self.tmpdir, "testsubdir/subdirfile.md"), "w") home_md.write("hello subdir file") #add this new page to the revision history: self.repo.stage(["Home.md"]) self.repo.do_commit("first revision", committer="john doe <*****@*****.**>") request = testing.DummyRequest() self.root = os.path.split(self.tmpdir)[0] self.projectname = os.path.split(self.tmpdir)[1] request.registry.settings['wiki.root'] = self.root request.matchdict['page'] = "Home" request.matchdict['project'] = self.projectname self.request = request
def test_commit_merge_heads_file(self): tmp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) r = Repo.init(tmp_dir) with open(os.path.join(r.path, 'a'), 'w') as f: f.write('initial text') c1 = r.do_commit( b'initial commit', committer=b'Test Committer <*****@*****.**>', author=b'Test Author <*****@*****.**>', commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0) with open(os.path.join(r.path, 'a'), 'w') as f: f.write('merged text') with open(os.path.join(r.path, '.git', 'MERGE_HEADS'), 'w') as f: f.write('c27a2d21dd136312d7fa9e8baabb82561a1727d0\n') r.stage(['a']) commit_sha = r.do_commit( b'deleted a', committer=b'Test Committer <*****@*****.**>', author=b'Test Author <*****@*****.**>', commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0) self.assertEqual([ c1, b'c27a2d21dd136312d7fa9e8baabb82561a1727d0'], r[commit_sha].parents)
def setUp(self): super(CompatPatchTestCase, self).setUp() self.test_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.test_dir) self.repo_path = os.path.join(self.test_dir, 'repo') self.repo = Repo.init(self.repo_path, mkdir=True) self.addCleanup(self.repo.close)
def initialise_repository(proj_folder, repo_folder): """Create a git repository for matador to use.""" config_file = Path(repo_folder, '.git', 'config') config = ConfigParser() repo = Repo.init(str(repo_folder)) config.read(str(config_file)) config['core']['sparsecheckout'] = 'true' config['remote "origin"'] = { 'url': proj_folder, 'fetch': '+refs/heads/*:refs/remotes/origin/*' } with config_file.open('w') as f: config.write(f) f.close() sparse_checkout_file = Path( repo_folder, '.git', 'info', 'sparse-checkout') with sparse_checkout_file.open('a') as f: f.write('/src\n') f.write('/deploy\n') f.close() return repo
def clone(source, target=None, bare=False, checkout=None, outstream=sys.stdout): """Clone a local or remote git repository. :param source: Path or URL for source repository :param target: Path to target repository (optional) :param bare: Whether or not to create a bare repository :param outstream: Optional stream to write progress to :return: The new repository """ if checkout is None: checkout = (not bare) if checkout and bare: raise ValueError("checkout and bare are incompatible") client, host_path = get_transport_and_path(source) if target is None: target = host_path.split("/")[-1] if not os.path.exists(target): os.mkdir(target) if bare: r = Repo.init_bare(target) else: r = Repo.init(target) remote_refs = client.fetch(host_path, r, determine_wants=r.object_store.determine_wants_all, progress=outstream.write) r["HEAD"] = remote_refs["HEAD"] if checkout: outstream.write('Checking out HEAD') index.build_index_from_tree(r.path, r.index_path(), r.object_store, r["HEAD"].tree) return r
def initialize_repo(path, state): log = logging.getLogger('INIT_REPO') if not exists(path): log.critical("%r doesn't exist!", path) raise ValueError("%r doesn't exist!" % (path,)) try: Repo(path) except NotGitRepository: # Good! That's what we expect. repo = Repo.init(path) log.info('%r created.', repo) else: # No good! We are an initialize function, nothing else. log.critical('Repository already exists at %r', path) raise ValueError('Repository already exists at %r' % (path,)) system_pickle_file_name = join(path, SYSTEM_PICKLE) pickle.dump(state, open(system_pickle_file_name, 'wb')) log.info('%s written.', system_pickle_file_name) repo.stage([SYSTEM_PICKLE]) staged = list(repo.open_index()) log.info('Files staged: ' + ', '.join(['%s'] * len(staged)), *staged) commit = repo.do_commit('Initial commit.') log.info('Initial commit done. %s', commit)
def __init_code__(): # initialize the repo if it doesn't exists, or load it if it does if not path.exists(LOGS_PATH): print "creating folder "+ LOGS_PATH mkdir(LOGS_PATH) repo = Repo.init(LOGS_PATH) blob = Blob.from_string("data") tree =Tree() tree.add(0100644, "initfile", blob.id) c = Commit() c.tree = tree.id author = "Writer [email protected]" c.author=c.committer=author c.commit_time=c.author_time=int(time()) tz = parse_timezone('+0200') c.commit_timezone=c.author_timezone=tz c.encoding="UTF-8" c.message="initial commit" store = repo.object_store store.add_object(blob) store.add_object(tree) store.add_object(c) repo.refs['refs/heads/master'] = c.id repo.refs['HEAD'] = 'ref: refs/heads/master' print "success!" else: #this is how to create a Repo object from an existing repository from dulwich.errors import NotGitRepository try: repo = Repo(LOGS_PATH) except NotGitRepository as e: raise GitFileError("Error: the path %s exists but is not a git repository."%LOGS_PATH) return repo
def test_git_dir(self): repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Populate repo filea = Blob.from_string(b'file a') filee = Blob.from_string(b'd') tree = Tree() tree[b'.git/a'] = (stat.S_IFREG | 0o644, filea.id) tree[b'c/e'] = (stat.S_IFREG | 0o644, filee.id) repo.object_store.add_objects([(o, None) for o in [filea, filee, tree]]) build_index_from_tree(repo.path, repo.index_path(), repo.object_store, tree.id) # Verify index entries index = repo.open_index() self.assertEqual(len(index), 1) # filea apath = os.path.join(repo.path, '.git', 'a') self.assertFalse(os.path.exists(apath)) # filee epath = os.path.join(repo.path, 'c', 'e') self.assertTrue(os.path.exists(epath)) self.assertReasonableIndexEntry(index[b'c/e'], stat.S_IFREG | 0o644, 1, filee.id) self.assertFileContents(epath, b'd')
def clone(repo_url, ref=None, folder=None, rep=None): if ref is None: ref = 'refs/heads/master' logger.debug("clone repo_url={0}, ref={1}".format(repo_url, ref)) if not rep: if folder is None: folder = tempfile.mkdtemp() else: os.mkdir(folder) logger.debug("folder = {0}".format(folder)) rep = Repo.init(folder) client, relative_path = get_transport_and_path(repo_url) logger.debug("client={0}".format(client)) remote_refs = client.fetch(relative_path, rep) for k, v in remote_refs.iteritems(): try: rep.refs.add_if_new(k, v) except: pass if ref.startswith('refs/tags'): ref = rep.ref(ref) if isinstance(rep[ref], Tag): rep['HEAD'] = rep[ref].object[1] else: rep['HEAD'] = rep[ref] indexfile = rep.index_path() tree = rep["HEAD"].tree index.build_index_from_tree(rep.path, indexfile, rep.object_store, tree) logger.debug("done") return rep, folder
def test_git_dir(self): if os.name != "posix": self.skipTest("test depends on POSIX shell") repo_dir = tempfile.mkdtemp() repo = Repo.init(repo_dir) self.addCleanup(shutil.rmtree, repo_dir) # Populate repo filea = Blob.from_string("file a") filee = Blob.from_string("d") tree = Tree() tree[".git/a"] = (stat.S_IFREG | 0o644, filea.id) tree["c/e"] = (stat.S_IFREG | 0o644, filee.id) repo.object_store.add_objects([(o, None) for o in [filea, filee, tree]]) build_index_from_tree(repo.path, repo.index_path(), repo.object_store, tree.id) # Verify index entries index = repo.open_index() self.assertEqual(len(index), 1) # filea apath = os.path.join(repo.path, ".git", "a") self.assertFalse(os.path.exists(apath)) # filee epath = os.path.join(repo.path, "c", "e") self.assertTrue(os.path.exists(epath)) self.assertReasonableIndexEntry(index["c/e"], stat.S_IFREG | 0o644, 1, filee.id) self.assertFileContents(epath, "d")
def setUp(self): super(BuildRepoTests, self).setUp() self._repo_dir = os.path.join(tempfile.mkdtemp(), "test") os.makedirs(self._repo_dir) r = self._repo = Repo.init(self._repo_dir) self.assertFalse(r.bare) self.assertEqual("ref: refs/heads/master", r.refs.read_ref("HEAD")) self.assertRaises(KeyError, lambda: r.refs["refs/heads/master"]) f = open(os.path.join(r.path, "a"), "wb") try: f.write("file contents") finally: f.close() r.stage(["a"]) commit_sha = r.do_commit( "msg", committer="Test Committer <*****@*****.**>", author="Test Author <*****@*****.**>", commit_timestamp=12345, commit_timezone=0, author_timestamp=12345, author_timezone=0, ) self.assertEqual([], r[commit_sha].parents) self._root_commit = commit_sha
def test_get_unstaged_changes(self): """Unit test for get_unstaged_changes.""" repo_dir = tempfile.mkdtemp() repo = Repo.init(repo_dir) self.addCleanup(shutil.rmtree, repo_dir) # Commit a dummy file then modify it foo1_fullpath = os.path.join(repo_dir, "foo1") with open(foo1_fullpath, "w") as f: f.write("origstuff") foo2_fullpath = os.path.join(repo_dir, "foo2") with open(foo2_fullpath, "w") as f: f.write("origstuff") repo.stage(["foo1", "foo2"]) repo.do_commit("test status", author="", committer="") with open(foo1_fullpath, "w") as f: f.write("newstuff") # modify access and modify time of path os.utime(foo1_fullpath, (0, 0)) changes = get_unstaged_changes(repo.open_index(), repo_dir) self.assertEqual(list(changes), ["foo1"])
def clone(repo_url, ref=None, folder=None): is_commit = False if ref is None: ref = "refs/heads/master" elif not ref.startswith("refs/"): is_commit = True logger.debug("clone repo_url={0}, ref={1}".format(repo_url, ref)) if folder is None: folder = tempfile.mkdtemp() logger.debug("folder = {0}".format(folder)) rep = Repo.init(folder) client, relative_path = get_transport_and_path(repo_url) logger.debug("client={0}".format(client)) remote_refs = client.fetch(relative_path, rep) for k, v in remote_refs.iteritems(): try: rep.refs.add_if_new(k, v) except: pass if is_commit: rep["HEAD"] = rep.commit(ref) else: rep["HEAD"] = remote_refs[ref] indexfile = rep.index_path() tree = rep["HEAD"].tree index.build_index_from_tree(rep.path, indexfile, rep.object_store, tree) logger.debug("done") return rep, folder
def repo(tmpdir, request): repo_folder = Path(str(tmpdir), project) try: repo = Repo(str(repo_folder)) except NotGitRepository: repo = Repo.init(str(repo_folder), mkdir=True) return repo
def clone(source, target=None, bare=False, outstream=sys.stdout): """Clone a local or remote git repository. :param source: Path or URL for source repository :param target: Path to target repository (optional) :param bare: Whether or not to create a bare repository :param outstream: Optional stream to write progress to :return: The new repository """ client, host_path = get_transport_and_path(source) if target is None: target = host_path.split("/")[-1] if not os.path.exists(target): os.mkdir(target) if bare: r = Repo.init_bare(target) else: r = Repo.init(target) remote_refs = client.fetch(host_path, r, determine_wants=r.object_store.determine_wants_all, progress=outstream.write) r["HEAD"] = remote_refs["HEAD"] return r
def test_symlink(self): repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Populate repo filed = Blob.from_string(b'file d') filee = Blob.from_string(b'd') tree = Tree() tree[b'c/d'] = (stat.S_IFREG | 0o644, filed.id) tree[b'c/e'] = (stat.S_IFLNK, filee.id) # symlink repo.object_store.add_objects([(o, None) for o in [filed, filee, tree]]) build_index_from_tree(repo.path, repo.index_path(), repo.object_store, tree.id) # Verify index entries index = repo.open_index() # symlink to d epath = os.path.join(repo.path, 'c', 'e') self.assertTrue(os.path.exists(epath)) self.assertReasonableIndexEntry( index[b'c/e'], stat.S_IFLNK, 0 if sys.platform == 'win32' else 1, filee.id) self.assertFileContents(epath, 'd', symlink=True)
def test_create_disk_non_bare_mkdir(self): tmp_dir = tempfile.mkdtemp() target_dir = os.path.join(tmp_dir, "target") self.addCleanup(shutil.rmtree, tmp_dir) repo = Repo.init(target_dir, mkdir=True) self.assertEqual(os.path.join(target_dir, '.git'), repo._controldir) self._check_repo_contents(repo, False)
def setUpClass(cls): cls.projdir = tempfile.mkdtemp() # temporary project directory cls.repo = Repo.init(cls.projdir) # test repo obj_store = cls.repo.object_store # test repo object store # commit 1 ('2017-01-19T01:06:43') cls.c1 = make_commit( id=cls.tag_test_data[cls.test_tags[0]][1], commit_time=cls.tag_test_data[cls.test_tags[0]][0], message=b'unannotated tag', author=cls.committer ) obj_store.add_object(cls.c1) # tag 1: unannotated cls.t1 = cls.test_tags[0] cls.repo[b'refs/tags/' + cls.t1] = cls.c1.id # add unannotated tag # commit 2 ('2017-01-19T01:11:54') cls.c2 = make_commit( id=cls.tag_test_data[cls.test_tags[1]][1], commit_time=cls.tag_test_data[cls.test_tags[1]][0], message=b'annotated tag', parents=[cls.c1.id], author=cls.committer ) obj_store.add_object(cls.c2) # tag 2: annotated ('2017-01-19T01:13:21') cls.t2 = make_tag( cls.c2, id=cls.tag_test_data[cls.test_tags[1]][2][1], name=cls.test_tags[1], tag_time=cls.tag_test_data[cls.test_tags[1]][2][0] ) obj_store.add_object(cls.t2) cls.repo[b'refs/heads/master'] = cls.c2.id cls.repo[b'refs/tags/' + cls.t2.name] = cls.t2.id # add annotated tag
def init_the_git(config): path = config.get('Local', 'path') repo = Repo.init(path) blob = Blob.from_string(open(os.path.join(path, '.git-dropbox.cnf')).read()) tree = Tree() tree.add(".git-dropbox.cnf", 0100644, blob.id) commit = Commit() commit.tree = tree.id commit.author = config.get('Local', 'user') commit.committer = 'Git-dropbox' commit.commit_time = int(time()) commit.author_time = os.path.getctime(os.path.join(path, '.git-dropbox.cnf')) commit.commit_timezone = commit.author_timezone = parse_timezone('-0200')[0] commit.encoding = 'UTF-8' commit.message = 'Initial commit' object_store = repo.object_store object_store.add_object(blob) object_store.add_object(tree) object_store.add_object(commit) repo.refs['refs/heads/master'] = commit.id
def test_get_unstaged_changes(self): """Unit test for get_unstaged_changes.""" repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Commit a dummy file then modify it foo1_fullpath = os.path.join(repo_dir, 'foo1') with open(foo1_fullpath, 'wb') as f: f.write(b'origstuff') foo2_fullpath = os.path.join(repo_dir, 'foo2') with open(foo2_fullpath, 'wb') as f: f.write(b'origstuff') repo.stage(['foo1', 'foo2']) repo.do_commit(b'test status', author=b'', committer=b'') with open(foo1_fullpath, 'wb') as f: f.write(b'newstuff') # modify access and modify time of path os.utime(foo1_fullpath, (0, 0)) changes = get_unstaged_changes(repo.open_index(), repo_dir) self.assertEqual(list(changes), [b'foo1'])
def test_working_tree(self): temp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, temp_dir) worktree_temp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, worktree_temp_dir) r = Repo.init(temp_dir) root_sha = r.do_commit( b'empty commit', committer=b'Test Committer <*****@*****.**>', author=b'Test Author <*****@*****.**>', commit_timestamp=12345, commit_timezone=0, author_timestamp=12345, author_timezone=0) r.refs[b'refs/heads/master'] = root_sha w = Repo._init_new_working_directory(worktree_temp_dir, r) new_sha = w.do_commit( b'new commit', committer=b'Test Committer <*****@*****.**>', author=b'Test Author <*****@*****.**>', commit_timestamp=12345, commit_timezone=0, author_timestamp=12345, author_timezone=0) w.refs[b'HEAD'] = new_sha self.assertEqual(os.path.abspath(r.controldir()), os.path.abspath(w.commondir())) self.assertEqual(r.refs.keys(), w.refs.keys()) self.assertNotEqual(r.head(), w.head())
def test_no_decode_encode(self): repo_dir = tempfile.mkdtemp() repo_dir_bytes = repo_dir.encode(sys.getfilesystemencoding()) self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Populate repo file = Blob.from_string(b'foo') tree = Tree() latin1_name = u'À'.encode('latin1') utf8_name = u'À'.encode('utf8') tree[latin1_name] = (stat.S_IFREG | 0o644, file.id) tree[utf8_name] = (stat.S_IFREG | 0o644, file.id) repo.object_store.add_objects( [(o, None) for o in [file, tree]]) build_index_from_tree( repo.path, repo.index_path(), repo.object_store, tree.id) # Verify index entries index = repo.open_index() latin1_path = os.path.join(repo_dir_bytes, latin1_name) self.assertTrue(os.path.exists(latin1_path)) utf8_path = os.path.join(repo_dir_bytes, utf8_name) self.assertTrue(os.path.exists(utf8_path))
def test_shell_hook_post_commit(self): if os.name != 'posix': self.skipTest('shell hook tests requires POSIX shell') repo_dir = os.path.join(tempfile.mkdtemp()) r = Repo.init(repo_dir) self.addCleanup(shutil.rmtree, repo_dir) (fd, path) = tempfile.mkstemp(dir=repo_dir) post_commit_msg = b"""#!/bin/sh rm """ + path.encode(sys.getfilesystemencoding()) + b""" """ root_sha = r.do_commit( b'empty commit', committer=b'Test Committer <*****@*****.**>', author=b'Test Author <*****@*****.**>', commit_timestamp=12345, commit_timezone=0, author_timestamp=12345, author_timezone=0) self.assertEqual([], r[root_sha].parents) post_commit = os.path.join(r.controldir(), 'hooks', 'post-commit') with open(post_commit, 'wb') as f: f.write(post_commit_msg) os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) commit_sha = r.do_commit( b'empty commit', committer=b'Test Committer <*****@*****.**>', author=b'Test Author <*****@*****.**>', commit_timestamp=12345, commit_timezone=0, author_timestamp=12345, author_timezone=0) self.assertEqual([root_sha], r[commit_sha].parents) self.assertFalse(os.path.exists(path)) post_commit_msg_fail = b"""#!/bin/sh exit 1 """ with open(post_commit, 'wb') as f: f.write(post_commit_msg_fail) os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) warnings.simplefilter("always", UserWarning) self.addCleanup(warnings.resetwarnings) warnings_list, restore_warnings = setup_warning_catcher() self.addCleanup(restore_warnings) commit_sha2 = r.do_commit( b'empty commit', committer=b'Test Committer <*****@*****.**>', author=b'Test Author <*****@*****.**>', commit_timestamp=12345, commit_timezone=0, author_timestamp=12345, author_timezone=0) self.assertEqual(len(warnings_list), 1, warnings_list) self.assertIsInstance(warnings_list[-1], UserWarning) self.assertTrue("post-commit hook failed: " in str(warnings_list[-1])) self.assertEqual([commit_sha], r[commit_sha2].parents)
def test_git_import(self): r = GitRepo.init("a", mkdir=True) self.build_tree(["a/file"]) r.stage("file") r.do_commit(ref=b"refs/heads/abranch", committer=b"Joe <*****@*****.**>", message=b"Dummy") r.do_commit(ref=b"refs/heads/bbranch", committer=b"Joe <*****@*****.**>", message=b"Dummy") self.run_bzr(["git-import", "--colocated", "a", "b"]) self.assertEqual(set([".bzr"]), set(os.listdir("b"))) self.assertEqual(set(["abranch", "bbranch"]), set(ControlDir.open("b").branch_names()))
def init(path=".", bare=False): """Create a new git repository. :param path: Path to repository. :param bare: Whether to create a bare repository. :return: A Repo instance """ if not os.path.exists(path): os.mkdir(path) if bare: return Repo.init_bare(path) else: return Repo.init(path)
def test_init_mkdir_unicode(self): repo_name = u'\xa7' try: os.fsencode(repo_name) except UnicodeEncodeError: self.skipTest('filesystem lacks unicode support') tmp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) repo_dir = os.path.join(tmp_dir, repo_name) t = Repo.init(repo_dir, mkdir=True) self.addCleanup(t.close) self.assertEqual(os.listdir(repo_dir), ['.git']) self.assertFilesystemHidden(os.path.join(repo_dir, '.git'))
def setUp(self): super(ShallowTests, self).setUp() # Smoke test for "bzr log" in a git repository with shallow depth. self.repo = GitRepo.init('gitr', mkdir=True) self.build_tree_contents([("gitr/foo", b"hello from git")]) self.repo.stage("foo") self.repo.do_commit(b"message", committer=b"Somebody <*****@*****.**>", author=b"Somebody <*****@*****.**>", commit_timestamp=1526330165, commit_timezone=0, author_timestamp=1526330165, author_timezone=0, merge_heads=[b'aa' * 20])
def OnPageChanging(self, event): # If no temp repo then we need to use the local one global x2ProfilerApp try: if self.offline_mode.GetValue(): x2ProfilerApp.repo = Repo(x2ProfilerApp.x2swProfilesPath) else: x2ProfilerApp.tmp_repo_path = tempfile.mkdtemp() x2ProfilerApp.repo = Repo.init(x2ProfilerApp.tmp_repo_path) except: pass if x2ProfilerApp.repo == None: event.Veto()
def test_add(self): r = GitRepo.init(self.test_dir) dir = ControlDir.open(self.test_dir) dir.create_branch() self.build_tree(['a', 'b']) output, error = self.run_bzr(['add', 'a']) self.assertEqual('adding a\n', output) self.assertEqual('', error) output, error = self.run_bzr( ['add', '--file-ids-from=../othertree', 'b']) self.assertEqual('adding b\n', output) self.assertEqual( 'Ignoring --file-ids-from, since the tree does not support ' 'setting file ids.\n', error)
def test_shell_hook_commit_msg(self): if os.name != "posix": self.skipTest("shell hook tests requires POSIX shell") commit_msg_fail = """#!/bin/sh exit 1 """ commit_msg_success = """#!/bin/sh exit 0 """ repo_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) r = Repo.init(repo_dir) self.addCleanup(r.close) commit_msg = os.path.join(r.controldir(), "hooks", "commit-msg") with open(commit_msg, "w") as f: f.write(commit_msg_fail) os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) self.assertRaises( errors.CommitError, r.do_commit, b"failed commit", committer=b"Test Committer <*****@*****.**>", author=b"Test Author <*****@*****.**>", commit_timestamp=12345, commit_timezone=0, author_timestamp=12345, author_timezone=0, ) with open(commit_msg, "w") as f: f.write(commit_msg_success) os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) commit_sha = r.do_commit( b"empty commit", committer=b"Test Committer <*****@*****.**>", author=b"Test Author <*****@*****.**>", commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0, ) self.assertEqual([], r[commit_sha].parents)
def test__determine_relative_changes_from_commits(self): tmp = Path(mkdtemp()) test_proj = ( Path(__file__).parent / "./data/lambda_build_with_relative_commits" ).resolve() copytree(test_proj, tmp / "test") repo = Repo.init(tmp / "test") Path(tmp / "test/ex.txt").touch() repo.stage("ex.txt") initial_commit = repo.do_commit(b"initial") filenames = [] for file in Path(tmp / "test").glob("**/*"): if file.is_file(): filenames.append(file.relative_to(Path(tmp / "test"))) repo.stage(filenames) second_commit = repo.do_commit(b"second") mkdir(f"{tmp}/test/ExampleNoPackage") Path(f"{tmp}/test/ExampleNoPackage/lambda_function.py").touch() c = Config.create( project_config_path=tmp / "test" / ".taskcat.yml", project_root=(tmp / "test").resolve(), args={ "project": { "lambda_zip_path": "lambda_functions/packages", "lambda_source_path": "lambda_functions/source", } }, ) LambdaBuild( c, project_root=(tmp / "test").resolve(), from_ref=initial_commit, to_ref=second_commit, ) path = tmp / "test" zip_suffix = Path("lambda_functions") / "packages" / "TestFunc" / "lambda.zip" self.assertEqual((path / "lambda_functions" / "packages").is_dir(), True) self.assertEqual((path / zip_suffix).is_file(), True) zip_suffix = ( Path("lambda_functions") / "packages" / "ExampleNoPackage" / "lambda.zip" ) self.assertEqual((path / zip_suffix).is_file(), False)
def test_write_file_new_empty_auto_commit_push(self): self.test_write_file_new_empty() repo = Repo.init(self._mkdtemp()) client, host_path = get_transport_and_path(self.layer['repo'].path) refs = client.fetch( host_path, repo, determine_wants=repo.object_store.determine_wants_all ) repo["HEAD"] = refs["HEAD"] repo["refs/heads/master"] = refs["refs/heads/master"] repo._build_tree() with open(os.path.join(repo.path, 'world'), 'r') as fp: self.assertEqual(fp.read(), '')
def test_git_import_tags(self): r = GitRepo.init("a", mkdir=True) self.build_tree(["a/file"]) r.stage("file") cid = r.do_commit(ref=b"refs/heads/abranch", committer=b"Joe <*****@*****.**>", message=b"Dummy") r[b"refs/tags/atag"] = cid self.run_bzr(["git-import", "--colocated", "a", "b"]) self.assertEqual(set([".bzr"]), set(os.listdir("b"))) b = ControlDir.open("b") self.assertEqual(["abranch"], list(b.get_branches().keys())) self.assertEqual( ["atag"], list(b.open_branch("abranch").tags.get_tag_dict().keys()))
def test_fetch_ignores_missing_refs(self): r = self.open_repo('a.git') missing = b'1234566789123456789123567891234657373833' r.refs[b'refs/heads/blah'] = missing tmp_dir = self.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) t = Repo.init(tmp_dir) self.addCleanup(t.close) r.fetch(t) self.assertIn(b'a90fa2d900a17e99b433217e988c4eb4a2e9a097', t) self.assertIn(b'a90fa2d900a17e99b433217e988c4eb4a2e9a097', t) self.assertIn(b'a90fa2d900a17e99b433217e988c4eb4a2e9a097', t) self.assertIn(b'28237f4dc30d0d462658d6b937b08a0f0b6ef55a', t) self.assertIn(b'b0931cadc54336e78a1d980420e3268903b57a50', t) self.assertNotIn(missing, t)
def _init_git(self, scm: "Git", branch: Optional[str] = None, **kwargs): from dulwich.repo import Repo as DulwichRepo from ..utils import push_refspec DulwichRepo.init(os.fspath(self.root_dir)) refspec = f"{EXEC_NAMESPACE}/" push_refspec(scm, self.git_url, refspec, refspec, **kwargs) if branch: push_refspec(scm, self.git_url, branch, branch, **kwargs) self.scm.set_ref(EXEC_BRANCH, branch, symbolic=True) elif self.scm.get_ref(EXEC_BRANCH): self.scm.remove_ref(EXEC_BRANCH) if self.scm.get_ref(EXEC_CHECKPOINT): self.scm.remove_ref(EXEC_CHECKPOINT) # checkout EXEC_HEAD and apply EXEC_MERGE on top of it without # committing head = EXEC_BRANCH if branch else EXEC_HEAD self.scm.checkout(head, detach=True) merge_rev = self.scm.get_ref(EXEC_MERGE) self.scm.merge(merge_rev, squash=True, commit=False)
def repo_initialize(self): """ Initializes a repo on disk where source data should be stored. The subdirectory of parent_location is based off the name of the Fetcher. """ pth = Path(self.repo_location) gitpth = Path(self.repo_location + '/.git') if not pth.is_dir(): pth.mkdir() if gitpth.is_dir(): raise ValueError("Requested location already contains a repo.") self.repo = Repo.init(self.repo_location) self.has_repo = True
def test_get_untracked_paths_nested(self): with open(os.path.join(self.repo.path, 'notignored'), 'w') as f: f.write('blah\n') subrepo = Repo.init(os.path.join(self.repo.path, 'nested'), mkdir=True) with open(os.path.join(subrepo.path, 'another'), 'w') as f: f.write('foo\n') self.assertEqual( set(['notignored']), set(porcelain.get_untracked_paths(self.repo.path, self.repo.path, self.repo.open_index()))) self.assertEqual( set(['another']), set(porcelain.get_untracked_paths(subrepo.path, subrepo.path, subrepo.open_index())))
def test_git_import_colo(self): r = GitRepo.init("a", mkdir=True) self.build_tree(["a/file"]) r.stage("file") r.do_commit(ref=b"refs/heads/abranch", committer=b"Joe <*****@*****.**>", message=b"Dummy") r.do_commit(ref=b"refs/heads/bbranch", committer=b"Joe <*****@*****.**>", message=b"Dummy") self.make_controldir("b", format="development-colo") self.run_bzr(["git-import", "--colocated", "a", "b"]) self.assertEqual( set([b.name for b in ControlDir.open("b").list_branches()]), set(["abranch", "bbranch"]))
def syncRepo(self, targetPath, repoUrl = None): assert os.path.exists(targetPath) or repoUrl, "Either repo should exist or supply remote origin" if os.path.exists(targetPath): try: localRepo = Repo(targetPath) config = localRepo.get_config() remoteUrl = config.get(("remote", "origin"), "url") if not remoteUrl: raise dulwich.errors.NotGitRepository() if repoUrl and repoUrl != remoteUrl: print("Error: Supplied remote URL does not match remote url in repo config!") sys.exit(1) except dulwich.errors.NotGitRepository: print("Error: %s will be overwritten, delete or move it." % targetPath) sys.exit(1) else: remoteUrl = repoUrl os.makedirs(targetPath) localRepo = Repo.init(targetPath) logger.info("Trying syncing %s to %s" % (remoteUrl, targetPath)) client, hostPath = get_transport_and_path(remoteUrl) try: remoteRefs = client.fetch(hostPath, localRepo) logger.info("Synced %s to %s" % (remoteUrl, targetPath)) localRepo["HEAD"] = remoteRefs["HEAD"] localRepo.reset_index() config = localRepo.get_config() config.set(("remote", "origin"), "url", remoteUrl) config.write_to_path() except (dulwich.errors.NotGitRepository,dulwich.errors.GitProtocolError): shutil.rmtree(targetPath) return False except KeyError: # Handle wild KeyError appearing. # in an ugly way for now shutil.rmtree(targetPath) return self.syncRepo(targetPath, remoteUrl) return True
def __init__(self, path=None, workdir=None, create=False, bare=False): assert path or workdir if workdir: self.path = workdir.path else: self.path = path if create: # XXX: fragile path.ensure(dir=1) self.repo = Repo.init(path.strpath) else: assert self.path.check(dir=True) try: self.repo = Repo(self.path.strpath) except NotGitRepository: raise NotFoundError('git', self.path)
def test_empty(self): repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: tree = Tree() repo.object_store.add_object(tree) build_index_from_tree(repo.path, repo.index_path(), repo.object_store, tree.id) # Verify index entries index = repo.open_index() self.assertEqual(len(index), 0) # Verify no files self.assertEqual(['.git'], os.listdir(repo.path))
def test_shell_hook_pre_commit(self): if os.name != 'posix': self.skipTest('shell hook tests requires POSIX shell') pre_commit_fail = """#!/bin/sh exit 1 """ pre_commit_success = """#!/bin/sh exit 0 """ repo_dir = os.path.join(self.mkdtemp()) self.addCleanup(shutil.rmtree, repo_dir) r = Repo.init(repo_dir) self.addCleanup(r.close) pre_commit = os.path.join(r.controldir(), 'hooks', 'pre-commit') with open(pre_commit, 'w') as f: f.write(pre_commit_fail) os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) self.assertRaises(errors.CommitError, r.do_commit, 'failed commit', committer='Test Committer <*****@*****.**>', author='Test Author <*****@*****.**>', commit_timestamp=12345, commit_timezone=0, author_timestamp=12345, author_timezone=0) with open(pre_commit, 'w') as f: f.write(pre_commit_success) os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) commit_sha = r.do_commit( b'empty commit', committer=b'Test Committer <*****@*****.**>', author=b'Test Author <*****@*****.**>', commit_timestamp=12395, commit_timezone=0, author_timestamp=12395, author_timezone=0) self.assertEqual([], r[commit_sha].parents)
def clone(source, target=None, bare=False, checkout=None, errstream=sys.stdout, outstream=None): """Clone a local or remote git repository. :param source: Path or URL for source repository :param target: Path to target repository (optional) :param bare: Whether or not to create a bare repository :param errstream: Optional stream to write progress to :param outstream: Optional stream to write progress to (deprecated) :return: The new repository """ if outstream is not None: import warnings warnings.warn("outstream= has been deprecated in favour of errstream=.", DeprecationWarning, stacklevel=3) errstream = outstream if checkout is None: checkout = (not bare) if checkout and bare: raise ValueError("checkout and bare are incompatible") client, host_path = get_transport_and_path(source) if target is None: target = host_path.split("/")[-1] if not os.path.exists(target): os.mkdir(target) if bare: r = Repo.init_bare(target) else: r = Repo.init(target) try: remote_refs = client.fetch(host_path, r, determine_wants=r.object_store.determine_wants_all, progress=errstream.write) r[b"HEAD"] = remote_refs[b"HEAD"] if checkout: errstream.write(b'Checking out HEAD') r.reset_index() except: r.close() raise return r
def test_add_if_new_symbolic(self): # Use an empty repo instead of the default. tear_down_repo(self._repo) repo_dir = os.path.join(tempfile.mkdtemp(), 'test') os.makedirs(repo_dir) self._repo = Repo.init(repo_dir) refs = self._repo.refs nines = '9' * 40 self.assertEqual('ref: refs/heads/master', refs.read_ref('HEAD')) self.assertFalse('refs/heads/master' in refs) self.assertTrue(refs.add_if_new('HEAD', nines)) self.assertEqual('ref: refs/heads/master', refs.read_ref('HEAD')) self.assertEqual(nines, refs['HEAD']) self.assertEqual(nines, refs['refs/heads/master']) self.assertFalse(refs.add_if_new('HEAD', '1' * 40)) self.assertEqual(nines, refs['HEAD']) self.assertEqual(nines, refs['refs/heads/master'])
def test_local_whoami(self): r = GitRepo.init("gitr", mkdir=True) self.build_tree_contents([('gitr/.git/config', """\ [user] email = [email protected] name = Test User """)]) out, err = self.run_bzr(["whoami", "-d", "gitr"]) self.assertEqual(out, "Test User <*****@*****.**>\n") self.assertEqual(err, "") self.build_tree_contents([('gitr/.git/config', """\ [user] email = [email protected] """)]) out, err = self.run_bzr(["whoami", "-d", "gitr"]) self.assertEqual(out, "[email protected]\n") self.assertEqual(err, "")
def test_nested_gitignores(self): tmp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, tmp_dir) repo = Repo.init(tmp_dir) with open(os.path.join(repo.path, '.gitignore'), 'wb') as f: f.write(b'/*\n') f.write(b'!/foo\n') os.mkdir(os.path.join(repo.path, 'foo')) with open(os.path.join(repo.path, 'foo', '.gitignore'), 'wb') as f: f.write(b'/bar\n') with open(os.path.join(repo.path, 'foo', 'bar'), 'wb') as f: f.write(b'IGNORED') m = IgnoreFilterManager.from_repo(repo) self.assertTrue(m.is_ignored('foo/bar'))
def test_normal_from_repo(self): # Create repo folder = Path.cwd() try: rp = Repo(str(folder)) except NotGitRepository: rp = Repo.init(str(folder)) try: version = rp.head().decode() self.original_revision = version except KeyError: FILE_NAME_TEST = 'file_test.txt' test_file = folder / FILE_NAME_TEST test_file.touch() rp.stage(FILE_NAME_TEST.encode()) version = rp.do_commit(b'Test commit').decode() v = get_source_revision() assert v == version[:10]
def test_add_if_new_symbolic(self): # Use an empty repo instead of the default. repo_dir = os.path.join(tempfile.mkdtemp(), "test") os.makedirs(repo_dir) repo = Repo.init(repo_dir) self.addCleanup(tear_down_repo, repo) refs = repo.refs nines = b"9" * 40 self.assertEqual(b"ref: refs/heads/master", refs.read_ref(b"HEAD")) self.assertFalse(b"refs/heads/master" in refs) self.assertTrue(refs.add_if_new(b"HEAD", nines)) self.assertEqual(b"ref: refs/heads/master", refs.read_ref(b"HEAD")) self.assertEqual(nines, refs[b"HEAD"]) self.assertEqual(nines, refs[b"refs/heads/master"]) self.assertFalse(refs.add_if_new(b"HEAD", b"1" * 40)) self.assertEqual(nines, refs[b"HEAD"]) self.assertEqual(nines, refs[b"refs/heads/master"])
def setUp(self): super(BuildRepoBytesRootTests, self).setUp() self._repo_dir = self.get_repo_dir() os.makedirs(self._repo_dir) r = self._repo = Repo.init(self._repo_dir) self.assertFalse(r.bare) self.assertEqual(b'ref: refs/heads/master', r.refs.read_ref(b'HEAD')) self.assertRaises(KeyError, lambda: r.refs[b'refs/heads/master']) with open(os.path.join(r._path_bytes, b'a'), 'wb') as f: f.write(b'file contents') r.stage(['a']) commit_sha = r.do_commit(b'msg', committer=b'Test Committer <*****@*****.**>', author=b'Test Author <*****@*****.**>', commit_timestamp=12345, commit_timezone=0, author_timestamp=12345, author_timezone=0) self.assertEqual([], r[commit_sha].parents) self._root_commit = commit_sha
def dbBlock(args, api=False, toggle=True): # Retrieve user record db = TinyDB(args.userdb, **db_format) User = Query() if api: table = db.table('api_users') else: table = db if toggle: verb = ('Block', 'Blocking', 'blocked') else: verb = ('Unblock', 'Unblocking', 'unblocked') user_list = table.search(User.userid == args.userid) status = len(user_list) if status < 1: print('User {} not found. Exiting.'.format(args.userid)) sys.exit(1) elif status > 1: print('ID not unique. Is there a problem in the database?') sys.exit(2) print('{} user {}...'.format(verb[1], args.userid)) user = user_list[0] # Update user record table.update({'blocked': toggle}, doc_ids=[user.doc_id]) # Add file to Git index try: repo = Repo(os.path.dirname(args.userdb)) except NotGitRepository: repo = Repo.init(os.path.dirname(args.userdb)) git.add(repo=repo, paths=[args.userdb]) # Prepare commit information committer = 'MSCWG <{}>'.format(mscwg_email).encode('utf8') author = committer message = ('{} user {}\n\nChanged by dbctl.py'.format( verb[0], args.userid).encode('utf8')) # Execute commit git.commit(repo, message=message, author=author, committer=committer) print('\nUser successfully {}'.format(verb[2]))
def test_get_unstaged_deleted_changes(self): """Unit test for get_unstaged_changes.""" repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Commit a dummy file then remove it foo1_fullpath = os.path.join(repo_dir, 'foo1') with open(foo1_fullpath, 'wb') as f: f.write(b'origstuff') repo.stage(['foo1']) repo.do_commit(b'test status', author=b'', committer=b'') os.unlink(foo1_fullpath) changes = get_unstaged_changes(repo.open_index(), repo_dir) self.assertEqual(list(changes), [b'foo1'])
def setUp(self): super(GraftsInRepoTests, self).setUp() self._repo_dir = os.path.join(tempfile.mkdtemp()) r = self._repo = Repo.init(self._repo_dir) self.addCleanup(shutil.rmtree, self._repo_dir) self._shas = [] commit_kwargs = { 'committer': 'Test Committer <*****@*****.**>', 'author': 'Test Author <*****@*****.**>', 'commit_timestamp': 12395, 'commit_timezone': 0, 'author_timestamp': 12395, 'author_timezone': 0, } self._shas.append(r.do_commit('empty commit', **commit_kwargs)) self._shas.append(r.do_commit('empty commit', **commit_kwargs)) self._shas.append(r.do_commit('empty commit', **commit_kwargs))
def test_no_decode_encode(self): repo_dir = tempfile.mkdtemp() repo_dir_bytes = os.fsencode(repo_dir) self.addCleanup(shutil.rmtree, repo_dir) with Repo.init(repo_dir) as repo: # Populate repo file = Blob.from_string(b'foo') tree = Tree() latin1_name = u'À'.encode('latin1') latin1_path = os.path.join(repo_dir_bytes, latin1_name) utf8_name = u'À'.encode('utf8') utf8_path = os.path.join(repo_dir_bytes, utf8_name) tree[latin1_name] = (stat.S_IFREG | 0o644, file.id) tree[utf8_name] = (stat.S_IFREG | 0o644, file.id) repo.object_store.add_objects([(o, None) for o in [file, tree]]) try: build_index_from_tree(repo.path, repo.index_path(), repo.object_store, tree.id) except OSError as e: if e.errno == 92 and sys.platform == 'darwin': # Our filename isn't supported by the platform :( self.skipTest('can not write filename %r' % e.filename) else: raise except UnicodeDecodeError: # This happens e.g. with python3.6 on Windows. # It implicitly decodes using utf8, which doesn't work. self.skipTest('can not implicitly convert as utf8') # Verify index entries index = repo.open_index() self.assertIn(latin1_name, index) self.assertIn(utf8_name, index) self.assertTrue(os.path.exists(latin1_path)) self.assertTrue(os.path.exists(utf8_path))