Exemple #1
0
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
Exemple #2
0
  def prepare_backup_folder(self):
    print("Preparing backup folder : ", self.container)
    os.mkdir(self.container)
    pygit2.init_repository(self.container, False)

    # look for the restore script in the default install dir first
    try:
      shutil.copy2("/usr/share/pacbackup/pacrestore.sh", self.container)
    except FileNotFoundError:
      try:
        shutil.copy2(os.path.join(os.path.dirname(os.path.realpath(__file__)),
          "pacrestore.sh"), self.container)
      except FileNotFoundError:
        print("Couldn't find the restore script anywhere, try reinstalling", file=stderr)
        shutil.rmtree(self.container)
        exit()

    repo = pygit2.Repository(self.container)
    index = repo.index

    index.read()
    index.add_all()
    index.write()
    tree = index.write_tree()

    message = "Initial Commit - Automated Package List Backup"
    comitter = pygit2.Signature('PacBackup '+__version__, '')
    sha = repo.create_commit('HEAD', 
      comitter, comitter, message, 
      tree, 
      [])
Exemple #3
0
 def init_backend(cls, path, fields, init=False, soft=False):
     # Metadata database
     init_repository('{0}/database'.format(path), bare=False)
     lfs.make_folder('{0}/database/.git/patchs'.format(path))
     cls.init_backend_static(path)
     # Make catalog
     make_catalog('{0}/catalog'.format(path), fields)
Exemple #4
0
    def initial(self, prefix):
        """
        Set up the git repo at ``settings.GIT_REPO_PATH``.
        And add initial directory to the repo.

        """
        pygit2.init_repository(self.repo_path, True)  # a bare repository
    def test_011_storage_empty_basic(self):
        emptydir = join(self.testdir, 'empty')

        init_repository(join(emptydir, '.git'), bare=True)

        item = DummyItem(emptydir)
        storage = GitStorage(item)
        self.assertEqual(storage.files(), [])

        pathinfo = storage.pathinfo('')
        self.assertEqual(pathinfo, {
            'basename': '',
            'date': '',
            'size': 0,
            'type': 'folder',
        })

        result = list(storage.listdir(''))
        self.assertEqual(result, [])

        result = storage.log(None, 1)
        self.assertEqual(result, [])

        self.assertEqual(storage.shortrev, None)
        self.assertEqual(storage.rev, None)
Exemple #6
0
def _init(victim, str_victim):
    try:
        rmtree(str_victim)
    except OSError:
        pass
    victim.mkdir()
    init_repository(str_victim)
Exemple #7
0
def repositories():
    if request.method == 'POST':
        username = '******'
        reponame = request.form['reponame']
        repodesc = request.form['repodesc']
        init_repository('/home/git/repositories/' + username + '/' + reponame, True)
        return redirect(url_for('.index', name=username, reponame=reponame))
Exemple #8
0
 def init(self):
     pygit2.init_repository(self.dir)
     os.makedirs(self.md_path)
     os.makedirs(self.generate_path)
     self.config = config.Config(self.dir)
     for file in resources.INIT_FILES:
         with open(os.path.join(self.dir, file), "w+") as f:
             f.write(resources.INIT_FILES[file])
Exemple #9
0
 def __init__(self, path):
     # TODO path should probably be a resource, ie redis url etc.
     self.path = path
     self.object_root = os.path.join(self.path, "objects")
     if not os.path.exists(self.object_root):
         log.info("initializing database in %s" % (path))
         pygit2.init_repository(path, True)
     self.repo = pygit2.Repository(path)
     self.check_repo_sanity()
Exemple #10
0
    def setUp(self):

        self.dir = TemporaryDirectory()
        self.remotedir = TemporaryDirectory()
        self.file = NamedTemporaryFile(dir=self.dir.name, delete=False)
        self.filename = path.basename(self.file.name)
        self.author = Signature('QuitStoreTest', '*****@*****.**')
        self.comitter = Signature('QuitStoreTest', '*****@*****.**')

        # Initialize repository
        init_repository(self.dir.name, False)
Exemple #11
0
def create_projects_git(folder, bare=False):
    """ Create some projects in the database. """
    repos = []
    for project in ['test.git', 'test2.git']:
        repo_path = os.path.join(folder, project)
        repos.append(repo_path)
        if not os.path.exists(repo_path):
            os.makedirs(repo_path)
        pygit2.init_repository(repo_path, bare=bare)

    return repos
Exemple #12
0
    def initialise(self, new_remote=None):
        """Setup the .git folder, with optional remote"""
        log.info("Setting up a .git folder")
        git_folder = os.path.join(self.location, ".git")
        if os.path.exists(git_folder):
            raise GitError("Trying to initialise git, but .git folder already exists", location=self.location)

        pygit2.init_repository(self.location)
        self.add_change("Initial commit", changed_files=True)
        if new_remote:
            self.change_remote(new_remote)
Exemple #13
0
 def setUp(self):
     self.repo_path = mkdtemp()
     init_repository(self.repo_path, False)
     self.repo = Repository(self.repo_path)
     self.file_name = 'foo.rst'
     self.file_path = os.path.join(self.repo_path, self.file_name)
     with codecs.open(self.file_path, 'w', encoding='utf-8') as fp:
         fp.write('test\n')
     self.tree = self.repo.TreeBuilder()
     self.last_commit = git_commit(self.repo, self.tree, [self.file_name])
     self.changectx = self.repo.head
    def create_storage(cls, path):
        """
            Create repository, and return GitStorage object on it

            :param path: Absolute path to the Git repository to create.
            :type path: str
            :returns: GitStorage
        """

        init_repository(path, False)

        return cls(path)
Exemple #15
0
def create_git_repo(name, gitfolder):
    # Create a git project based on the package information.
    # get the path of the git repo
    gitrepo = os.path.join(gitfolder, '%s.git' % name)

    if os.path.exists(gitrepo):
        raise fresque.exceptions.RepoExistsException(
            'The project named "%s" already have '
            'a git repository' % name
        )
    # create a bare git repository
    pygit2.init_repository(gitrepo, bare=True)
    return 'Successfully created Project {0} git respository'.format(name)
Exemple #16
0
    def setUp(self):
        self.repo_path = mkdtemp()
        init_repository(self.repo_path, False)
        self.repo = Repository(self.repo_path)

        # create files and commit
        self.sign = Signature('foo', '*****@*****.**')
        self.repo_files = ['a%i.rst' % i for i in range(5)]
        for i in self.repo_files:
            with codecs.open(os.path.join(self.repo_path, i), 'w',
                             encoding='utf-8') as fp:
                fp.write('dumb file %s\n' % i)
        self.tree = self.repo.TreeBuilder()
        self.old_commit = git_commit(self.repo, self.tree, self.repo_files)
Exemple #17
0
    def setUp(self):
        # For tests, it's easier to use global_config so that we don't
        # have to pass a config object around.
        from gitmodel.workspace import Workspace
        from gitmodel import exceptions
        from gitmodel import utils

        self.exceptions = exceptions
        self.utils = utils

        # Create temporary repo to work from
        self.repo_path = tempfile.mkdtemp(prefix='python-gitmodel-')
        pygit2.init_repository(self.repo_path, False)
        self.workspace = Workspace(self.repo_path)
Exemple #18
0
def _setup_temp_repo():
    """
    Set up a temporary Git repository in which to house pack files
    for unpacking into another repository.

    Returns the path to the new .git/objects/pack directory.
    """
    tmpname = 'p4gf_git_tmp'
    tmprepo = os.path.join(os.path.dirname(os.getcwd()), tmpname)
    if os.path.exists(tmprepo):
        shutil.rmtree(tmprepo)
    pygit2.init_repository(tmprepo)
    packdir = os.path.join(tmprepo, '.git', 'objects', 'pack')
    return (tmprepo, packdir)
Exemple #19
0
    def setup_git_repo(self):
        """ Create a basic git repo withing the tests folder that can be used
        then for the tests.
        """

        # Create a bare git repo
        bare_repo_path = os.path.join(self.gitroot, 'test_repo.git')
        os.makedirs(bare_repo_path)
        pygit2.init_repository(bare_repo_path, bare=True)

        # Clone the bare git repo and add the elements we need in it
        git_repo_path = os.path.join(self.gitroot, 'test_repo')
        pygit2.clone_repository(bare_repo_path, git_repo_path, bare=False)

        repo = pygit2.Repository(git_repo_path)

        # Add basic files needed
        open(os.path.join(git_repo_path, '.gitignore'), 'w').close()
        repo.index.add('.gitignore')
        open(os.path.join(git_repo_path, 'sources'), 'w').close()
        repo.index.add('sources')
        repo.index.write()

        with open(os.path.join(
                git_repo_path, '.git', 'config'), 'a') as stream:
            stream.write(GITCONFIG)

        # Commits the files added
        tree = repo.index.write_tree()
        author = pygit2.Signature(
            'Alice Author', '*****@*****.**')
        committer = pygit2.Signature(
            'Cecil Committer', '*****@*****.**')
        repo.create_commit(
            'refs/heads/master',  # the name of the reference to update
            author,
            committer,
            'Add basic file required',
            # binary string representing the tree object ID
            tree,
            # list of binary strings representing parents of the new commit
            []
        )

        # Push to the remote repo
        master_ref = repo.lookup_reference('HEAD').resolve()
        refname = '%s:%s' % (master_ref.name, master_ref.name)
        ori_remote = repo.remotes[0]
        ori_remote.push(refname)
Exemple #20
0
    def test_new_repo(self):
        repo = init_repository(self.temp_dir, False)

        hex_sha = repo.write(GIT_OBJ_BLOB, "Test")
        self.assertEqual(len(hex_sha), 40)

        assert os.path.exists(os.path.join(self._temp_dir, '.git'))
    def __enter__(self):
        repo = pygit2.init_repository(self.path)
        repo.remotes.create('origin', '/dev/null')

        # Set up branch 'master'
        filename = 'Dockerfile'
        dockerfile_path = os.path.join(self.path, filename)
        open(dockerfile_path, mode="w+t").close()
        index = repo.index
        index.add(filename)
        author = pygit2.Signature('Test', '*****@*****.**')
        committer = pygit2.Signature('Test', '*****@*****.**')
        oid = repo.create_commit('HEAD', author, committer,
                                 '', index.write_tree(), [])
        master = repo.head

        # Now set up our branch
        branch = repo.create_branch(BRANCH, repo.get(oid))
        repo.checkout(refname=branch)
        DockerfileParser(dockerfile_path).lines = self.lines

        index = repo.index
        index.add(filename)
        repo.create_commit(branch.name, author, committer,
                           '', index.write_tree(),
                           [repo.head.peel().hex])
        branch.upstream = branch
        return dockerfile_path, repo.head.peel().hex
def test_bump_release_direct(tmpdir, label, expected):
    with DFWithRelease(label=label) as (df_path, commit):
        workflow, args, runner = prepare(tmpdir, df_path, commit,
                                         commit_message='foo')
        runner.run()
        assert open(df_path).readlines()[1].rstrip() == expected
        repo = pygit2.init_repository(os.path.dirname(df_path))

        # We're on the 'branch' branch
        assert repo.head.name == repo.lookup_branch(BRANCH).name

        # and one commit ahead of where we were
        assert repo.head.peel().parents[0].hex == commit

        # Examine metadata for newest commit
        author = repo.head.peel().author
        assert author.name == args['author_name']
        assert author.email == args['author_email']

        committer = repo.head.peel().committer
        assert ('committer_name' not in args or
                committer.name == args['committer_name'])
        assert ('committer_email' not in args or
                committer.email == args['committer_email'])

        if 'commit_message' in args:
            assert repo.head.peel().message.rstrip() == args['commit_message']
Exemple #23
0
    def save(
            self, force_insert=False, force_update=False, using=None,
            update_fields=None):
        """ Save model and init git repository.

        :return Model: A saved instance

        """
        new = False if self.pk else True
        obj = super(Repository, self).save(
            force_insert, force_update, using, update_fields)
        if new:
            from pygit2 import init_repository
            # Initiate bare repository on server
            init_repository(self.absolute_path, bare=True)
        return obj
Exemple #24
0
 def setUpClass(cls):
     cls.repo_dir = os.path.join(os.path.dirname(__file__),
                                 '..', 'build', 'test', 'repo')
     if os.path.exists(cls.repo_dir):
         shutil.rmtree(cls.repo_dir)
     os.makedirs(cls.repo_dir)
     cls.repo = pygit2.init_repository(cls.repo_dir, bare=True)
    def test_clean_git(self):
        """ Test the clean_git method of pagure.lib.git. """
        pagure.lib.git.clean_git(None, None, None)

        self.test_update_git()

        gitpath = os.path.join(tests.HERE, 'test_ticket_repo.git')
        gitrepo = pygit2.init_repository(gitpath, bare=True)

        # Get the uid of the ticket created
        commit = gitrepo.revparse_single('HEAD')
        patch = pagure.lib.git.commit_to_patch(gitrepo, commit)
        hash_file = None
        for row in patch.split('\n'):
            if row.startswith('+++ b/'):
                hash_file = row.split('+++ b/')[-1]
                break

        # The only file in git is the one of that ticket
        files = [entry.name for entry in commit.tree]
        self.assertEqual(files, [hash_file])

        repo = pagure.lib.get_project(self.session, 'test_ticket_repo')
        issue = pagure.lib.search_issues(self.session, repo, issueid=1)
        pagure.lib.git.clean_git(issue, repo, tests.HERE)

        # No more files in the git repo
        commit = gitrepo.revparse_single('HEAD')
        files = [entry.name for entry in commit.tree]
        self.assertEqual(files, [])
Exemple #26
0
    def __init__(self, repoDir, init=True):
        self.repoDir = repoDir

        if init:
            self._repo = pygit2.init_repository(repoDir)
        else:
            self._repo = pygit2.repository(repoDir)
Exemple #27
0
    def test_new_repo(self):
        repo = init_repository(self._temp_dir, False)

        oid = repo.write(GIT_OBJ_BLOB, "Test")
        self.assertEqual(type(oid), Oid)

        assert os.path.exists(os.path.join(self._temp_dir, ".git"))
Exemple #28
0
def init_repository(url=None):
  """Creates a new Gitless's repository in the cwd.

  Args:
    url: if given the local repository will be a clone of the remote repository
      given by this url.
  """
  cwd = os.getcwd()
  try:
    pygit2.discover_repository(cwd)
    raise GlError('You are already in a Gitless repository')
  except KeyError:  # Expected
    if not url:
      repo = pygit2.init_repository(cwd)
      # We also create an initial root commit
      git.commit(allow_empty=True, m='Initialize repository')
      return repo

    try:
      git.clone(url, cwd)
    except ErrorReturnCode as e:
      raise GlError(stderr(e))

    # We get all remote branches as well and create local equivalents
    repo = Repository()
    remote = repo.remotes['origin']
    for rb in (remote.lookup_branch(bn) for bn in remote.listall_branches()):
      if rb.branch_name == 'master':
        continue
      new_b = repo.create_branch(rb.branch_name, rb.head)
      new_b.upstream = rb
    return repo
Exemple #29
0
 def upload(self, token, metadata, reader):
     name = metadata["name"]
     version = metadata["version"]
     rep = self.repos.get(name)
     if rep is None:
         where = os.path.join(self.root, name)
         need_init = True
         if os.path.exists(where):
             self.warning("%s exists - cleared", where)
             shutil.rmtree(where)
             os.mkdir(where)
     else:
         where = dirname(rep.path)
         need_init = False
     with TarFile.open(mode="r|gz", fileobj=reader) as tar:
         tar.extractall(where)
     if not need_init:
         self.add_version(rep, version)
     else:
         self.repos[name] = rep = pygit2.init_repository(where)
         try:
             self.add_version(rep, version)
         except Exception as e:
             shutil.rmtree(where)
             del self.repos[name]
             self.error("Failed to initialize %s", name)
             raise from_none(e)
         rep.config["forge.tokens"] = self.scramble(token)
     self._generate_images(metadata, rep)
Exemple #30
0
def main():
    parser = ArgumentParser()
    parser.add_argument('-v', '--verbose', action='store_true')
    args = parser.parse_args()

    repo = init_repository('.')
    commits = list(repo.walk(repo.head.target, GIT_SORT_TOPOLOGICAL | GIT_SORT_REVERSE))

    total_commits = 0

    for commit in commits:
        # Skip merge commits
        if len(commit.parents) > 1:
            continue

        if len(commit.parents) == 1:
            diff = repo.diff(commit.parents[0], commit)
        else:
            diff = commit.tree.diff_to_tree(swap=True)

        if diff.stats.insertions + diff.stats.deletions > 5:
            continue

        short_message = commit.message.split('\n')[0]
        print '\033[1m\033[94m[' + short_hash(commit) + ']\033[0m', short_message

        if len(commit.parents) == 1:
            subprocess.call(['git', '--no-pager', 'diff', str(commit.id), str(commit.parents[0].id)])
            print ''
        else:
            print diff.patch

        total_commits += 1

    print str(total_commits) + ' commit(s)'
Exemple #31
0
def test_keyword_arg_true(tmp_path):
    repo = init_repository(tmp_path, bare=True)
    assert repo.is_bare
Exemple #32
0
def test_pos_arg_true(tmp_path):
    repo = init_repository(tmp_path, True)
    assert repo.is_bare
Exemple #33
0
 def test_pos_arg_false(self):
     repo = init_repository(self._temp_dir, False)
     assert not repo.is_bare
Exemple #34
0
def test_no_arg(tmp_path):
    repo = init_repository(tmp_path)
    assert not repo.is_bare
Exemple #35
0
 def test_discover_repo(self):
     repo = init_repository(self._temp_dir, False)
     subdir = os.path.join(self._temp_dir, "test1", "test2")
     os.makedirs(subdir)
     self.assertEqual(repo.path, discover_repository(subdir))
Exemple #36
0
def test_no_arg_aspath(tmp_path):
    repo = init_repository(Path(tmp_path))
    assert not repo.is_bare
Exemple #37
0
    def test_view_docs(self):
        """ Test the view_docs endpoint. """
        tests.create_projects(self.session)
        repo = pygit2.init_repository(os.path.join(tests.HERE, 'docs',
                                                   'test.git'),
                                      bare=True)

        output = self.app.get('/test/docs')
        self.assertEqual(output.status_code, 200)
        self.assertTrue('<h2>Docs</h2>' in output.data)
        self.assertTrue('<p>This repo is brand new!</p>' in output.data)
        self.assertTrue(
            'git clone [email protected]:docs/test.git' in output.data)

        # forked doc repo
        docrepo = os.path.join(tests.HERE, 'docs', 'test', 'test.git')
        repo = pygit2.init_repository(docrepo)

        # Create files in that git repo
        with open(os.path.join(docrepo, 'sources'), 'w') as stream:
            stream.write('foo\n bar')
        repo.index.add('sources')
        repo.index.write()

        folderpart = os.path.join(docrepo, 'folder1', 'folder2')
        os.makedirs(folderpart)
        with open(os.path.join(folderpart, 'test_file'), 'w') as stream:
            stream.write('row1\nrow2\nrow3')
        repo.index.add(os.path.join('folder1', 'folder2', 'test_file'))
        repo.index.write()

        # Commits the files added
        tree = repo.index.write_tree()
        author = pygit2.Signature('Alice Author', '*****@*****.**')
        committer = pygit2.Signature('Cecil Committer', '*****@*****.**')
        repo.create_commit(
            'refs/heads/master',  # the name of the reference to update
            author,
            committer,
            'Add test files and folder',
            # binary string representing the tree object ID
            tree,
            # list of binary strings representing parents of the new commit
            [])

        # Push the changes to the bare repo
        remote = repo.create_remote(
            'origin', os.path.join(tests.HERE, 'docs', 'test.git'))

        PagureRepo.push(remote, 'refs/heads/master:refs/heads/master')

        # Now check the UI

        output = self.app.get('/test/docs')
        self.assertEqual(output.status_code, 200)
        self.assertTrue('<h2>Docs</h2>' in output.data)
        self.assertFalse('<p>This repo is brand new!</p>' in output.data)
        self.assertTrue('<a href="/test/master/folder1">' in output.data)
        self.assertTrue('<a href="/test/master/sources">' in output.data)

        output = self.app.get('/test/master/sources')
        self.assertEqual(output.status_code, 200)
        self.assertTrue('<h2>Docs</h2>' in output.data)
        self.assertTrue('<section class="docs_content">' in output.data)

        output = self.app.get('/test/master/folder1/folder2')
        self.assertEqual(output.status_code, 200)
        self.assertTrue('<h2>Docs</h2>' in output.data)
        self.assertTrue(
            '<li class="file">\n        '
            '<a href="/test/master/folder1/folder2/test_file">' in output.data)

        output = self.app.get('/test/master/folder1/folder2/test_file')
        self.assertEqual(output.status_code, 200)
        self.assertTrue('<h2>Docs</h2>' in output.data)
        self.assertTrue(
            '  <section class="docs_content">\n    <pre>row1\nrow2\n'
            'row3</pre>\n  </section>' in output.data)

        output = self.app.get('/test/master/folder1')
        self.assertEqual(output.status_code, 200)
        self.assertTrue('<h2>Docs</h2>' in output.data)
        self.assertTrue(
            '<li class="folder">\n        '
            '<a href="/test/master/folder1/folder2">' in output.data)

        output = self.app.get('/test/master/folder1/foo')
        self.assertEqual(output.status_code, 200)
        self.assertTrue('<h2>Docs</h2>' in output.data)
        self.assertTrue(
            '<li class="error">File folder1/foo not found</li>' in output.data)

        output = self.app.get('/test/master/folder1/foo/folder2')
        self.assertEqual(output.status_code, 200)
        self.assertTrue(
            '<li class="error">File folder1/foo/folder2 not found</li>' in
            output.data)
Exemple #38
0
def add_binary_git_repo(folder, filename):
    """ Create a fake image file for the specified git repo. """
    if not os.path.exists(folder):
        os.makedirs(folder)
    brepo = pygit2.init_repository(folder, bare=True)

    newfolder = tempfile.mkdtemp(prefix='pagure-tests')
    repo = pygit2.clone_repository(folder, newfolder)

    content = """<89>PNG^M
^Z
^@^@^@^MIHDR^@^@^@K^@^@^@K^H^F^@^@^@8Nzê^@^@^@^FbKGD^@ÿ^@ÿ^@ÿ ½§<93>^@^@^@  pHYs^@^@^M×^@^@^M×^AB(<9b>x^@^@^@^GtIM
E^GÞ
^N^U^F^[<88>]·<9c>^@^@  <8a>IDATxÚí<9c>ÛO^Tg^_Ç?3³»ì^B
<8b>®ËË<8b>X^NÕõ^EQÚ^Z­^Qc<82>^Pk5Úô¦iMÄ^[{×^K<9b>&^^Xÿ^A<8d>WM^S^SmÒ<8b>j¯Zê<8d>   6^QO^Dª¶´/Ö^M^T5^^*¼¬<9c>^Oî<8
1><99>÷<82>Y<8b>03;3»<83>hù&d óìÃÌw~§çûüf`^Q<8b>XÄ"^V±<88>^?:<84>^Er^N^R ª¿^K3ÎK<99>ñ3^EÈêïÿ8²ò<81> <90>¥C^T^Z<84>
É@^Tè^E<86>_g²²<80>^\<95>$^?<86>æ^\TI^[SI|åÉ^R<81>Õ*QNb^\èVÝõ<95>#Ë^M^T^C^Eóì-<83>ÀC þ*<90>%^B+<80>^?¿äÄñ^XèϤ¥e<9
a>,^O°^Vp-<90>l<9f>^@Â<99><8a>gR^FOÌ^O<84>TËZ(HZù3õ'íÉ2<81>^R Ìé+oll¤½½<9d>þþ~^TEAQ^T"<91>^HW¯^åèÑ£¸\º^F]^F¬|Ùn(^@
å@<9e>S^DíÚµ<8b>cÇ<8e>±iÓ¦<94>cãñ8Ç<8f>^_§©©<89>^[7nh^M^Y^Fþ|YdU8ET0^X¤©©<89>Í<9b>7[þî^W_|ÁÄÄ^DçÏ<9f>çÑ£G^Y#,<9d><
98>µ^RXæ^DQõõõ´¶¶RVfϳÇÇÇyøð!<95><95><95>dggsïÞ½<99><87>½j^B^Z<99>¯<98>åW^CgƱsçN<9a><9b><9b>ÉÎζ=G<þw<89>µaÃ^F^Z^
Z^Zf^OYag^UaDz<jÖË86nÜÈåË<97>§ã<83>`?B<9c>9sæï<85>¥¢^P^L^Fµ,Ì^O^LX©Ã$^[<96>XéTyðË/¿<90><9b><9b>kûûCCC<9c>:u<8a>ÁÁÁ
^WÈN^RöøñcFF^ð¾^B bVÉ°Z<^F<9c>*8¿ùæ^[<82>Á á<98>X,FKK^K'O<9e>äâÅ<8b>ȲLAA^A[·n¥¸¸^XA^Pp»ÝºV¹wï^¾üòËÙ×^_PU<8c><8c>f
C7Pí^DQeee<84>ÃaÜn·î<98><9e><9e>^^¶oß®<95>ݦM^^T©®®¦®®<8e>©©)Ý1ׯ_§½½}ö¡ßͬ%­¸S±SµÔ<9e>={^L<89>úé§<9f>¨¨¨Ð%
"""

    parents = []
    commit = None
    try:
        commit = repo.revparse_single('HEAD')
    except KeyError:
        pass
    if commit:
        parents = [commit.oid.hex]

    # Create a file in that git repo
    with open(os.path.join(newfolder, filename), 'w') as stream:
        stream.write(content)
    repo.index.add(filename)
    repo.index.write()

    # Commits the files added
    tree = repo.index.write_tree()
    author = pygit2.Signature(
        'Alice Author', '*****@*****.**')
    committer = pygit2.Signature(
        'Cecil Committer', '*****@*****.**')
    repo.create_commit(
        'refs/heads/master',  # the name of the reference to update
        author,
        committer,
        'Add a fake image file',
        # binary string representing the tree object ID
        tree,
        # list of binary strings representing parents of the new commit
        parents
    )

    # Push to origin
    ori_remote = repo.remotes[0]
    master_ref = repo.lookup_reference('HEAD').resolve()
    refname = '%s:%s' % (master_ref.name, master_ref.name)

    PagureRepo.push(ori_remote, refname)

    shutil.rmtree(newfolder)
Exemple #39
0
def add_readme_git_repo(folder):
    """ Create a README file for the specified git repo. """
    if not os.path.exists(folder):
        os.makedirs(folder)
    brepo = pygit2.init_repository(folder, bare=True)

    newfolder = tempfile.mkdtemp(prefix='pagure-tests')
    repo = pygit2.clone_repository(folder, newfolder)

    content = """Pagure
======

:Author: Pierre-Yves Chibon <*****@*****.**>


Pagure is a light-weight git-centered forge based on pygit2.

Currently, Pagure offers a web-interface for git repositories, a ticket
system and possibilities to create new projects, fork existing ones and
create/merge pull-requests across or within projects.


Homepage: https://github.com/pypingou/pagure

Dev instance: http://209.132.184.222/ (/!\\ May change unexpectedly, it's a dev instance ;-))
"""

    parents = []
    commit = None
    try:
        commit = repo.revparse_single('HEAD')
    except KeyError:
        pass
    if commit:
        parents = [commit.oid.hex]

    # Create a file in that git repo
    with open(os.path.join(newfolder, 'README.rst'), 'w') as stream:
        stream.write(content)
    repo.index.add('README.rst')
    repo.index.write()

    # Commits the files added
    tree = repo.index.write_tree()
    author = pygit2.Signature(
        'Alice Author', '*****@*****.**')
    committer = pygit2.Signature(
        'Cecil Committer', '*****@*****.**')
    repo.create_commit(
        'refs/heads/master',  # the name of the reference to update
        author,
        committer,
        'Add a README file',
        # binary string representing the tree object ID
        tree,
        # list of binary strings representing parents of the new commit
        parents
    )

    # Push to origin
    ori_remote = repo.remotes[0]
    master_ref = repo.lookup_reference('HEAD').resolve()
    refname = '%s:%s' % (master_ref.name, master_ref.name)

    PagureRepo.push(ori_remote, refname)

    shutil.rmtree(newfolder)
Exemple #40
0
def test_pos_arg_false(tmp_path):
    repo = init_repository(tmp_path, False)
    assert not repo.is_bare
    def test_view_repo_empty(self, send_email):
        """ Test the view_repo endpoint when the project has a slash in its
        name.
        """
        send_email.return_value = True

        tests.create_projects(self.session)
        # Non-existant git repo
        output = self.app.get('/test')
        self.assertEqual(output.status_code, 404)

        # Create a git repo to play with
        gitrepo = os.path.join(self.path, 'repos', 'test.git')
        repo = pygit2.init_repository(gitrepo, bare=True)

        # With git repo
        output = self.app.get('/test')
        self.assertEqual(output.status_code, 200)
        output_text = output.get_data(as_text=True)
        self.assertIn(
            '<input class="form-control bg-white" type="text" '
            'value="git://localhost.localdomain/test.git" readonly>',
            output_text)
        self.assertIn(
            '<p>The Project Creator has not pushed any code yet</p>',
            output_text)

        # We can't create the project `forks/test` the normal way
        self.assertRaises(
            pagure.exceptions.PagureException,
            pagure.lib.query.new_project,
            self.session,
            name='test',
            namespace='forks',
            repospanner_region=None,
            description='test project forks/test',
            url='',
            avatar_email='',
            user='******',
            blacklist=pagure.config.config['BLACKLISTED_PROJECTS'],
            allowed_prefix=pagure.config.config['ALLOWED_PREFIX'],
        )

        # So just put it in the DB
        item = pagure.lib.model.Project(
            user_id=1,  # pingou
            name='test',
            namespace='forks',
            description='test project forks/test',
            hook_token='aaabbbcccddd',
        )
        self.session.add(item)
        self.session.commit()

        # Create a git repo to play with
        gitrepo = os.path.join(self.path, 'repos', 'forks/test.git')
        repo = pygit2.init_repository(gitrepo, bare=True)

        output = self.app.get('/forks/test')
        self.assertEqual(output.status_code, 200)
        output_text = output.get_data(as_text=True)
        self.assertIn(
            '<input class="form-control bg-white" type="text" '
            'value="git://localhost.localdomain/forks/test.git" readonly>',
            output_text)
        self.assertIn(
            '<p>The Project Creator has not pushed any code yet</p>',
            output_text)

        output = self.app.get('/forks/test/issues')
        self.assertEqual(output.status_code, 200)
        output_text = output.get_data(as_text=True)
        self.assertIn(
            '<title>Issues - forks/test - Pagure</title>', output_text)
        self.assertIn(
            '<span class="font-weight-bold">no open issues found</span>\n',
            output_text)
Exemple #42
0
 def test_keyword_arg_false(self):
     repo = init_repository(self._temp_dir, bare=False)
     self.assertFalse(repo.is_bare)
Exemple #43
0
 def test_keyword_arg_true(self):
     repo = init_repository(self._temp_dir, bare=True)
     self.assertTrue(repo.is_bare)
    def test_view_repo_empty(self, send_email):
        """ Test the view_repo endpoint when the project has a slash in its
        name.
        """
        send_email.return_value = True

        tests.create_projects(self.session)
        # Non-existant git repo
        output = self.app.get('/test')
        self.assertEqual(output.status_code, 404)

        # Create a git repo to play with
        gitrepo = os.path.join(tests.HERE, 'repos', 'test.git')
        repo = pygit2.init_repository(gitrepo, bare=True)

        # With git repo
        output = self.app.get('/test')
        self.assertEqual(output.status_code, 200)
        self.assertIn(
            '<div class="card-block">\n            '
            '<h5><strong>Owners</strong></h5>', output.data)
        self.assertIn('<p>The Project Creator has not pushed any code yet</p>',
                      output.data)

        # We can't create the project `forks/test` the normal way
        self.assertRaises(
            pagure.exceptions.PagureException,
            pagure.lib.new_project,
            self.session,
            name='test',
            namespace='forks',
            description='test project forks/test',
            url='',
            avatar_email='',
            user='******',
            blacklist=pagure.APP.config['BLACKLISTED_PROJECTS'],
            allowed_prefix=pagure.APP.config['ALLOWED_PREFIX'],
            gitfolder=pagure.APP.config['GIT_FOLDER'],
            docfolder=pagure.APP.config['DOCS_FOLDER'],
            ticketfolder=pagure.APP.config['TICKETS_FOLDER'],
            requestfolder=pagure.APP.config['REQUESTS_FOLDER'],
        )

        # So just put it in the DB
        item = pagure.lib.model.Project(
            user_id=1,  # pingou
            name='test',
            namespace='forks',
            description='test project forks/test',
            hook_token='aaabbbcccddd',
        )
        self.session.add(item)
        self.session.commit()

        # Create a git repo to play with
        gitrepo = os.path.join(tests.HERE, 'repos', 'forks/test.git')
        repo = pygit2.init_repository(gitrepo, bare=True)

        output = self.app.get('/forks/test')
        self.assertEqual(output.status_code, 200)
        self.assertIn(
            '<div class="card-block">\n            '
            '<h5><strong>Owners</strong></h5>', output.data)
        self.assertIn('<p>The Project Creator has not pushed any code yet</p>',
                      output.data)

        output = self.app.get('/forks/test/issues')
        self.assertEqual(output.status_code, 200)
        self.assertIn('<title>Issues - forks/test - Pagure</title>',
                      output.data)
        self.assertIn('<td colspan="5" class="noresult">No issues found</td>',
                      output.data)
Exemple #45
0
 def create_repository(path, bare):
     return init_repository(path, bare)
Exemple #46
0
 def git_init(self, path):
     pygit2.init_repository(path)
Exemple #47
0
 def test_no_arg(self):
     repo = init_repository(self._temp_dir)
     assert not repo.is_bare
Exemple #48
0
def upgrade(ctx, source, dest):
    """
    Upgrade a repository for an earlier version of Sno to be compatible with the latest version.
    The current repository structure of Sno is known as Datasets V2, which is used from Sno 0.5 onwards.
    """
    source = Path(source)
    dest = Path(dest)

    if dest.exists():
        raise click.BadParameter(f"'{dest}': already exists", param_hint="DEST")

    source_repo = pygit2.Repository(str(source))
    if not source_repo or not source_repo.is_bare:
        raise click.BadParameter(
            f"'{source}': not an existing repository", param_hint="SOURCE"
        )

    source_version = get_repo_version(source_repo)
    if source_version == 2:
        raise InvalidOperation(
            "Cannot upgrade: source repository is already at latest version (Datasets V2)"
        )

    if source_version not in (0, 1):
        raise InvalidOperation(
            "Unrecognised source repository version: {source_version}"
        )

    source_dataset_class = dataset_class_for_version(source_version)

    # action!
    click.secho(f"Initialising {dest} ...", bold=True)
    dest.mkdir()
    dest_repo = pygit2.init_repository(str(dest), bare=True)
    write_repo_version_config(dest_repo, 2)

    # walk _all_ references
    source_walker = source_repo.walk(
        source_repo.head.target, pygit2.GIT_SORT_TOPOLOGICAL | pygit2.GIT_SORT_REVERSE
    )
    for ref in source_repo.listall_reference_objects():
        source_walker.push(ref.resolve().target)

    commit_map = {}

    click.secho("\nWriting new commits ...", bold=True)
    for i, source_commit in enumerate(source_walker):
        dest_parents = []
        for parent_id in source_commit.parent_ids:
            try:
                dest_parents.append(commit_map[parent_id.hex])
            except KeyError:
                raise ValueError(
                    f"Commit {i} ({source_commit.id}): Haven't seen parent ({parent_id})"
                )

        _upgrade_commit(
            i,
            source_repo,
            source_commit,
            source_version,
            source_dataset_class,
            dest_parents,
            dest_repo,
            commit_map,
        )

    click.echo(f"{i+1} commits processed.")

    click.secho("\nUpdating references ...", bold=True)
    for ref in source_repo.listall_reference_objects():
        if ref.type == pygit2.GIT_REF_OID:
            # real references
            target = commit_map[ref.target.hex]
            dest_repo.references.create(ref.name, target, True)  # overwrite
            click.echo(f"  {ref.name} ({ref.target.hex[:8]} → {target[:8]})")

    for ref in source_repo.listall_reference_objects():
        if ref.type == pygit2.GIT_REF_SYMBOLIC:
            dest_repo.references.create(ref.name, ref.target)
            click.echo(f"  {ref.name} → {ref.target}")

    if source_repo.head_is_detached:
        dest_repo.set_head(pygit2.Oid(hex=commit_map[source_repo.head.target.hex]))
    else:
        dest_repo.set_head(source_repo.head.name)

    click.secho("\nCompacting repository ...", bold=True)
    subprocess.check_call(["git", "-C", str(dest), "gc"])

    if "sno.workingcopy.path" in source_repo.config:
        click.secho("\nCreating working copy ...", bold=True)
        subctx = click.Context(ctx.command, parent=ctx)
        subctx.ensure_object(context.Context)
        subctx.obj.user_repo_path = str(dest)
        subctx.invoke(checkout.create_workingcopy)

    click.secho("\nUpgrade complete", fg="green", bold=True)
def create_test_repo(src_dir, dest_dir):
    if os.path.exists(dest_dir):
        shutil.rmtree(dest_dir)
    shutil.copytree(src_dir, dest_dir)
    author = pygit2.Signature(USER_NAME, USER_MAIL)
    committer = author
    in_degree_map, g_next, g_previous = read_dot(os.path.join(dest_dir, 'cg.dot'))
    '''
    {
        'commit_name': {
            'branch_name': '',
            'commit_id': ''
        }
    }
    '''
    commit_infos = {}
    sorted_commits = top_sort(g_next, in_degree_map)
    repo = None
    for idx, commit in enumerate(sorted_commits):
        branch_name = None
        commit_msg = commit
        pathspecs = [commit]
        if idx == 0:
            repo = pygit2.init_repository(dest_dir)
            branch_name = commit
            repo.index.add_all(pathspecs)
            repo.index.write()
            tree = repo.index.write_tree()
            repo.create_commit('HEAD', author, committer, commit_msg, tree, [])
        else:
            previous_commits = g_previous.get(commit)
            if len(previous_commits) == 1:
                previous_commit = previous_commits[0]
                previous_branch_name = commit_infos.get(previous_commit)['branch_name']
                branch_name = previous_branch_name
                previous_commit_id = commit_infos.get(previous_commit)['commit_id']
                repo.checkout(repo.lookup_branch(previous_branch_name))
                i = g_next[previous_commit].index(commit)
                if i > 0:
                    # new branch
                    branch_name = commit
                    new_branch = repo.branches.local.create(branch_name, repo[previous_commit_id])
                    repo.checkout(new_branch)
                repo.index.add_all(pathspecs)
                repo.index.write()
                tree = repo.index.write_tree()
                repo.create_commit('HEAD', author, committer, commit_msg, tree, [repo.head.target])
            else:
                # merge commit
                main_branch_commit = previous_commits[0]
                feat_branch_commit = previous_commits[1]
                branch_name = commit_infos.get(main_branch_commit)['branch_name']
                repo.checkout(repo.lookup_branch(branch_name))
                feat_commit_id = commit_infos.get(feat_branch_commit)['commit_id']
                repo.merge(feat_commit_id)
                repo.index.add_all(pathspecs)
                repo.index.write()
                tree = repo.index.write_tree()
                repo.create_commit('HEAD', author, author, commit_msg, tree, [repo.head.target, feat_commit_id])
        commit_infos[commit] = {
            'branch_name': branch_name,
            'commit_id': repo.head.target
        }
Exemple #50
0
def test_discover_repo_aspath(tmp_path):
    repo = init_repository(Path(tmp_path), False)
    subdir = Path(tmp_path) / "test1" / "test2"
    os.makedirs(subdir)
    assert repo.path == discover_repository(subdir)
Exemple #51
0
        zip_file.writestr(info, content)


if __name__ == '__main__':
    # Cleanup
    if os.path.exists(LOCAL_REPO_1):
        shutil.rmtree(LOCAL_REPO_1)

    if os.path.exists(LOCAL_REPO_2):
        shutil.rmtree(LOCAL_REPO_2)

    if os.path.exists(REMOTE_REPO):
        shutil.rmtree(REMOTE_REPO)

    # Initialize new remote repo
    remote_repo = pygit2.init_repository(REMOTE_REPO, True)

    # Clone local repo
    local_repo_1 = pygit2.clone_repository(REMOTE_REPO,
                                           LOCAL_REPO_1)
    local_repo_2 = pygit2.clone_repository(REMOTE_REPO,
                                           LOCAL_REPO_2)

    # Repo pull fastforwardable
    create_commits(local_repo_1, 1)
    push(local_repo_1)
    pull(local_repo_2)

    # Repo pull merge necessary
    create_commits(local_repo_1, 1)
    create_commits(local_repo_2, 1)
Exemple #52
0
 def create(cls, path, **kw):
     kw['bare'] = kw.pop('bare', False)
     return init_repository(path, **kw)
Exemple #53
0
def create_project(self, username, namespace, name, add_readme,
                   ignore_existing_repo):
    """ Create a project.

    :kwarg username: the user creating the project
    :type user: str
    :kwarg namespace: the namespace of the project
    :type namespace: str
    :kwarg name: the name of the project
    :type name: str
    :kwarg add_readme: a boolean specifying if the project should be
        created with a README file or not
    :type add_readme: bool
    :kwarg ignore_existing_repo: a boolean specifying whether the creation
        of the project should fail if the repo exists on disk or not
    :type ignore_existing_repo: bool

    """

    session = pagure.lib.create_session()

    project = pagure.lib._get_project(
        session, namespace=namespace, name=name,
        case=APP.config.get('CASE_SENSITIVE', False))

    with project.lock('WORKER'):
        userobj = pagure.lib.search_user(session, username=username)
        gitrepo = os.path.join(APP.config['GIT_FOLDER'], project.path)

        # Add the readme file if it was asked
        if not add_readme:
            pygit2.init_repository(gitrepo, bare=True)
        else:
            temp_gitrepo_path = tempfile.mkdtemp(prefix='pagure-')
            temp_gitrepo = pygit2.init_repository(temp_gitrepo_path,
                                                  bare=False)
            author = userobj.fullname or userobj.user
            author_email = userobj.default_email
            if six.PY2:
                author = author.encode('utf-8')
                author_email = author_email.encode('utf-8')
            author = pygit2.Signature(author, author_email)
            content = u"# %s\n\n%s" % (name, project.description)
            readme_file = os.path.join(temp_gitrepo.workdir, "README.md")
            with open(readme_file, 'wb') as stream:
                stream.write(content.encode('utf-8'))
            temp_gitrepo.index.add_all()
            temp_gitrepo.index.write()
            tree = temp_gitrepo.index.write_tree()
            temp_gitrepo.create_commit(
                'HEAD', author, author, 'Added the README', tree, [])
            pygit2.clone_repository(temp_gitrepo_path, gitrepo, bare=True)
            shutil.rmtree(temp_gitrepo_path)

        # Make the repo exportable via apache
        http_clone_file = os.path.join(gitrepo, 'git-daemon-export-ok')
        if not os.path.exists(http_clone_file):
            with open(http_clone_file, 'w') as stream:
                pass

        if APP.config['DOCS_FOLDER']:
            docrepo = os.path.join(APP.config['DOCS_FOLDER'], project.path)
            if os.path.exists(docrepo):
                if not ignore_existing_repo:
                    shutil.rmtree(gitrepo)
                    raise pagure.exceptions.RepoExistsException(
                        'The docs repo "%s" already exists' % project.path
                    )
            else:
                pygit2.init_repository(docrepo, bare=True)

        if APP.config['TICKETS_FOLDER']:
            ticketrepo = os.path.join(
                APP.config['TICKETS_FOLDER'], project.path)
            if os.path.exists(ticketrepo):
                if not ignore_existing_repo:
                    shutil.rmtree(gitrepo)
                    shutil.rmtree(docrepo)
                    raise pagure.exceptions.RepoExistsException(
                        'The tickets repo "%s" already exists' %
                        project.path
                    )
            else:
                pygit2.init_repository(
                    ticketrepo, bare=True,
                    mode=pygit2.C.GIT_REPOSITORY_INIT_SHARED_GROUP)

        requestrepo = os.path.join(
            APP.config['REQUESTS_FOLDER'], project.path)
        if os.path.exists(requestrepo):
            if not ignore_existing_repo:
                shutil.rmtree(gitrepo)
                shutil.rmtree(docrepo)
                shutil.rmtree(ticketrepo)
                raise pagure.exceptions.RepoExistsException(
                    'The requests repo "%s" already exists' %
                    project.path
                )
        else:
            pygit2.init_repository(
                requestrepo, bare=True,
                mode=pygit2.C.GIT_REPOSITORY_INIT_SHARED_GROUP)

        # Install the default hook
        plugin = pagure.lib.plugins.get_plugin('default')
        dbobj = plugin.db_object()
        dbobj.active = True
        dbobj.project_id = project.id
        session.add(dbobj)
        session.flush()
        plugin.set_up(project)
        plugin.install(project, dbobj)
        session.commit()

    task = generate_gitolite_acls.delay(
        namespace=project.namespace,
        name=project.name,
        user=project.user.user if project.is_fork else None)
    _log.info('Refreshing gitolite config queued in task: %s', task.id)

    session.remove()
    gc_clean()

    return ret('view_repo', repo=name, namespace=namespace)
Exemple #54
0
def test_discover_repo(tmp_path):
    repo = init_repository(tmp_path, False)
    subdir = os.path.join(tmp_path, "test1", "test2")
    os.makedirs(subdir)
    assert repo.path == discover_repository(subdir)
Exemple #55
0
    def make_git_tree(self):
        """Make a simple git tree suitable for testing

        It has three branches:
            'base' has two commits: PCI, main
            'first' has base as upstream and two more commits: I2C, SPI
            'second' has base as upstream and three more: video, serial, bootm

        Returns:
            pygit2.Repository: repository
        """
        repo = pygit2.init_repository(self.gitdir)
        self.repo = repo
        new_tree = repo.TreeBuilder().write()

        # pylint doesn't seem to find this
        # pylint: disable=E1101
        author = pygit2.Signature('Test user', '*****@*****.**')
        committer = author
        _ = repo.create_commit('HEAD', author, committer, 'Created master',
                               new_tree, [])

        self.make_commit_with_file(
            'Initial commit', '''
Add a README

''', 'README', '''This is the README file
describing this project
in very little detail''')

        self.make_commit_with_file(
            'pci: PCI implementation', '''
Here is a basic PCI implementation

''', 'pci.c', '''This is a file
it has some contents
and some more things''')
        self.make_commit_with_file(
            'main: Main program', '''
Hello here is the second commit.
''', 'main.c', '''This is the main file
there is very little here
but we can always add more later
if we want to

Series-to: u-boot
Series-cc: Barry Crump <*****@*****.**>
''')
        base_target = repo.revparse_single('HEAD')
        self.make_commit_with_file(
            'i2c: I2C things', '''
This has some stuff to do with I2C
''', 'i2c.c', '''And this is the file contents
with some I2C-related things in it''')
        self.make_commit_with_file(
            'spi: SPI fixes', '''
SPI needs some fixes
and here they are

Signed-off-by: %s

Series-to: u-boot
Commit-notes:
title of the series
This is the cover letter for the series
with various details
END
''' % self.leb, 'spi.c', '''Some fixes for SPI in this
file to make SPI work
better than before''')
        first_target = repo.revparse_single('HEAD')

        target = repo.revparse_single('HEAD~2')
        # pylint doesn't seem to find this
        # pylint: disable=E1101
        repo.reset(target.oid, pygit2.GIT_CHECKOUT_FORCE)
        self.make_commit_with_file(
            'video: Some video improvements', '''
Fix up the video so that
it looks more purple. Purple is
a very nice colour.
''', 'video.c', '''More purple here
Purple and purple
Even more purple
Could not be any more purple''')
        self.make_commit_with_file(
            'serial: Add a serial driver', '''
Here is the serial driver
for my chip.

Cover-letter:
Series for my board
This series implements support
for my glorious board.
END
Series-links: 183237
''', 'serial.c', '''The code for the
serial driver is here''')
        self.make_commit_with_file(
            'bootm: Make it boot', '''
This makes my board boot
with a fix to the bootm
command
''', 'bootm.c', '''Fix up the bootm
command to make the code as
complicated as possible''')
        second_target = repo.revparse_single('HEAD')

        repo.branches.local.create('first', first_target)
        repo.config.set_multivar('branch.first.remote', '', '.')
        repo.config.set_multivar('branch.first.merge', '', 'refs/heads/base')

        repo.branches.local.create('second', second_target)
        repo.config.set_multivar('branch.second.remote', '', '.')
        repo.config.set_multivar('branch.second.merge', '', 'refs/heads/base')

        repo.branches.local.create('base', base_target)
        return repo
Exemple #56
0
def fork(self, name, namespace, user_owner, user_forker, editbranch, editfile):
    """ Forks the specified project for the specified user.

    :arg namespace: the namespace of the project
    :type namespace: str
    :arg name: the name of the project
    :type name: str
    :arg user_owner: the user of which the project is forked, only set
        if the project is already a fork
    :type user_owner: str
    :arg user_forker: the user forking the project
    :type user_forker: str
    :kwarg editbranch: the name of the branch in which the user asked to
        edit a file
    :type editbranch: str
    :kwarg editfile: the file the user asked to edit
    :type editfile: str

    """

    session = pagure.lib.create_session()

    repo_from = pagure.lib._get_project(
        session, namespace=namespace, name=name, user=user_owner,
        case=APP.config.get('CASE_SENSITIVE', False))

    repo_to = pagure.lib._get_project(
        session, namespace=namespace, name=name, user=user_forker,
        case=APP.config.get('CASE_SENSITIVE', False))

    with repo_to.lock('WORKER'):
        reponame = os.path.join(APP.config['GIT_FOLDER'], repo_from.path)
        forkreponame = os.path.join(APP.config['GIT_FOLDER'], repo_to.path)

        frepo = pygit2.clone_repository(reponame, forkreponame, bare=True)
        # Clone all the branches as well
        for branch in frepo.listall_branches(pygit2.GIT_BRANCH_REMOTE):
            branch_obj = frepo.lookup_branch(branch, pygit2.GIT_BRANCH_REMOTE)
            branchname = branch_obj.branch_name.replace(
                branch_obj.remote_name, '', 1)[1:]
            if branchname in frepo.listall_branches(pygit2.GIT_BRANCH_LOCAL):
                continue
            frepo.create_branch(branchname, frepo.get(branch_obj.target.hex))

        # Create the git-daemon-export-ok file on the clone
        http_clone_file = os.path.join(forkreponame, 'git-daemon-export-ok')
        if not os.path.exists(http_clone_file):
            with open(http_clone_file, 'w'):
                pass

        # Only fork the doc folder if the pagure instance supports the doc
        # service/server.
        if APP.config.get('DOCS_FOLDER'):
            docrepo = os.path.join(APP.config['DOCS_FOLDER'], repo_to.path)
            if os.path.exists(docrepo):
                shutil.rmtree(forkreponame)
                raise pagure.exceptions.RepoExistsException(
                    'The docs "%s" already exists' % repo_to.path
                )
            pygit2.init_repository(docrepo, bare=True)

        if APP.config.get('TICKETS_FOLDER'):
            ticketrepo = os.path.join(
                APP.config['TICKETS_FOLDER'], repo_to.path)
            if os.path.exists(ticketrepo):
                shutil.rmtree(forkreponame)
                shutil.rmtree(docrepo)
                raise pagure.exceptions.RepoExistsException(
                    'The tickets repo "%s" already exists' % repo_to.path
                )
            pygit2.init_repository(
                ticketrepo, bare=True,
                mode=pygit2.C.GIT_REPOSITORY_INIT_SHARED_GROUP)

        requestrepo = os.path.join(APP.config['REQUESTS_FOLDER'], repo_to.path)
        if os.path.exists(requestrepo):
            shutil.rmtree(forkreponame)
            shutil.rmtree(docrepo)
            shutil.rmtree(ticketrepo)
            raise pagure.exceptions.RepoExistsException(
                'The requests repo "%s" already exists' % repo_to.path
            )
        pygit2.init_repository(
            requestrepo, bare=True,
            mode=pygit2.C.GIT_REPOSITORY_INIT_SHARED_GROUP)

        pagure.lib.notify.log(
            repo_to,
            topic='project.forked',
            msg=dict(
                project=repo_to.to_json(public=True),
                agent=user_forker,
            ),
        )

    del frepo
    session.remove()

    _log.info('Project created, refreshing auth async')
    task = generate_gitolite_acls.delay(
        namespace=repo_to.namespace,
        name=repo_to.name,
        user=repo_to.user.user if repo_to.is_fork else None)
    _log.info('Refreshing gitolite config queued in task: %s', task.id)
    gc_clean()

    if editfile is None:
        return ret('view_repo', repo=name, namespace=namespace,
                   username=user_forker)
    else:
        return ret('edit_file', repo=name, namespace=namespace,
                   username=user_forker, branchname=editbranch,
                   filename=editfile)
Exemple #57
0
 def test_no_arg(self):
     repo = init_repository(self._temp_dir)
     self.assertFalse(repo.is_bare)
Exemple #58
0
 def test_pos_arg_true(self):
     repo = init_repository(self._temp_dir, True)
     self.assertTrue(repo.is_bare)
Exemple #59
0
def add_content_git_repo(folder):
    """ Create some content for the specified git repo. """
    if not os.path.exists(folder):
        os.makedirs(folder)
    brepo = pygit2.init_repository(folder, bare=True)

    newfolder = tempfile.mkdtemp(prefix='pagure-tests')
    repo = pygit2.clone_repository(folder, newfolder)

    # Create a file in that git repo
    with open(os.path.join(newfolder, 'sources'), 'w') as stream:
        stream.write('foo\n bar')
    repo.index.add('sources')
    repo.index.write()

    parents = []
    commit = None
    try:
        commit = repo.revparse_single('HEAD')
    except KeyError:
        pass
    if commit:
        parents = [commit.oid.hex]

    # Commits the files added
    tree = repo.index.write_tree()
    author = pygit2.Signature(
        'Alice Author', '*****@*****.**')
    committer = pygit2.Signature(
        'Cecil Committer', '*****@*****.**')
    repo.create_commit(
        'refs/heads/master',  # the name of the reference to update
        author,
        committer,
        'Add sources file for testing',
        # binary string representing the tree object ID
        tree,
        # list of binary strings representing parents of the new commit
        parents,
    )

    parents = []
    commit = None
    try:
        commit = repo.revparse_single('HEAD')
    except KeyError:
        pass
    if commit:
        parents = [commit.oid.hex]

    subfolder = os.path.join('folder1', 'folder2')
    if not os.path.exists(os.path.join(newfolder, subfolder)):
        os.makedirs(os.path.join(newfolder, subfolder))
    # Create a file in that git repo
    with open(os.path.join(newfolder, subfolder, 'file'), 'w') as stream:
        stream.write('foo\n bar\nbaz')
    repo.index.add(os.path.join(subfolder, 'file'))
    repo.index.write()

    # Commits the files added
    tree = repo.index.write_tree()
    author = pygit2.Signature(
        'Alice Author', '*****@*****.**')
    committer = pygit2.Signature(
        'Cecil Committer', '*****@*****.**')
    repo.create_commit(
        'refs/heads/master',  # the name of the reference to update
        author,
        committer,
        'Add some directory and a file for more testing',
        # binary string representing the tree object ID
        tree,
        # list of binary strings representing parents of the new commit
        parents
    )

    # Push to origin
    ori_remote = repo.remotes[0]
    master_ref = repo.lookup_reference('HEAD').resolve()
    refname = '%s:%s' % (master_ref.name, master_ref.name)

    PagureRepo.push(ori_remote, refname)

    shutil.rmtree(newfolder)
Exemple #60
0
def test_keyword_arg_false(tmp_path):
    repo = init_repository(tmp_path, bare=False)
    assert not repo.is_bare