Push new local branch to remote using Gitpython





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I looked at a few references but I am still having problems:



SO: Pushing local branch to remote branch - gitpython



SO: Use GitPython to Checkout a new branch and push to remote



Related question: https://github.com/gitpython-developers/GitPython/issues/471



Tutorial: https://gitpython.readthedocs.io/en/stable/tutorial.html



My understanding of Git is really basic, please bear with me. I want to clone a remote repo, create a new branch, and push the new branch back to remote.



This seems to work:



import git
import subprocess

nm_brnch = 'new_branch'

# Clone
repo_url = r'my_remote.git'
repo = git.Repo.clone_from(repo_url, dnm_wrk, branch=r'some_branch')

# Create new branch
git = repo.git
git.checkout('HEAD', b=nm_brnch)

# Push new branch to remote
subprocess.call(f'git push -u origin {nm_brnch}')


But it's ugly :(. I tried this without success:



repo.head.set_reference(nm_brnch)
repo.git.push("origin", nm_brnch)









share|improve this question































    1















    I looked at a few references but I am still having problems:



    SO: Pushing local branch to remote branch - gitpython



    SO: Use GitPython to Checkout a new branch and push to remote



    Related question: https://github.com/gitpython-developers/GitPython/issues/471



    Tutorial: https://gitpython.readthedocs.io/en/stable/tutorial.html



    My understanding of Git is really basic, please bear with me. I want to clone a remote repo, create a new branch, and push the new branch back to remote.



    This seems to work:



    import git
    import subprocess

    nm_brnch = 'new_branch'

    # Clone
    repo_url = r'my_remote.git'
    repo = git.Repo.clone_from(repo_url, dnm_wrk, branch=r'some_branch')

    # Create new branch
    git = repo.git
    git.checkout('HEAD', b=nm_brnch)

    # Push new branch to remote
    subprocess.call(f'git push -u origin {nm_brnch}')


    But it's ugly :(. I tried this without success:



    repo.head.set_reference(nm_brnch)
    repo.git.push("origin", nm_brnch)









    share|improve this question



























      1












      1








      1


      1






      I looked at a few references but I am still having problems:



      SO: Pushing local branch to remote branch - gitpython



      SO: Use GitPython to Checkout a new branch and push to remote



      Related question: https://github.com/gitpython-developers/GitPython/issues/471



      Tutorial: https://gitpython.readthedocs.io/en/stable/tutorial.html



      My understanding of Git is really basic, please bear with me. I want to clone a remote repo, create a new branch, and push the new branch back to remote.



      This seems to work:



      import git
      import subprocess

      nm_brnch = 'new_branch'

      # Clone
      repo_url = r'my_remote.git'
      repo = git.Repo.clone_from(repo_url, dnm_wrk, branch=r'some_branch')

      # Create new branch
      git = repo.git
      git.checkout('HEAD', b=nm_brnch)

      # Push new branch to remote
      subprocess.call(f'git push -u origin {nm_brnch}')


      But it's ugly :(. I tried this without success:



      repo.head.set_reference(nm_brnch)
      repo.git.push("origin", nm_brnch)









      share|improve this question
















      I looked at a few references but I am still having problems:



      SO: Pushing local branch to remote branch - gitpython



      SO: Use GitPython to Checkout a new branch and push to remote



      Related question: https://github.com/gitpython-developers/GitPython/issues/471



      Tutorial: https://gitpython.readthedocs.io/en/stable/tutorial.html



      My understanding of Git is really basic, please bear with me. I want to clone a remote repo, create a new branch, and push the new branch back to remote.



      This seems to work:



      import git
      import subprocess

      nm_brnch = 'new_branch'

      # Clone
      repo_url = r'my_remote.git'
      repo = git.Repo.clone_from(repo_url, dnm_wrk, branch=r'some_branch')

      # Create new branch
      git = repo.git
      git.checkout('HEAD', b=nm_brnch)

      # Push new branch to remote
      subprocess.call(f'git push -u origin {nm_brnch}')


      But it's ugly :(. I tried this without success:



      repo.head.set_reference(nm_brnch)
      repo.git.push("origin", nm_brnch)






      python push gitpython






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 15 at 2:00









      A-B-B

      24.4k66470




      24.4k66470










      asked Nov 23 '18 at 13:40









      deckarddeckard

      31527




      31527
























          1 Answer
          1






          active

          oldest

          votes


















          0














          I'm using gitpython==2.1.11 with Python 3.7. Below is my push function in which I first try a high-level push, and then a low-level push as necessary. Note how I check the return value of either command. I also log the push actions, and this explains what's happening at every step.



          class GitCommandError(Exception):
          pass

          class Git:
          def _commit_and_push_repo(self) -> None:
          repo = self._repo
          remote = repo.remote()
          remote_name = remote.name
          branch_name = repo.active_branch.name

          # Note: repo.index.entries was observed to also include unpushed files in addition to uncommitted files.
          log.debug('Committing repository index in active branch "%s".', branch_name)
          self._repo.index.commit('')
          log.info('Committed repository index in active branch "%s".', branch_name)

          def _is_pushed(push_info: git.remote.PushInfo) -> bool:
          valid_flags = {push_info.FAST_FORWARD, push_info.NEW_HEAD} # UP_TO_DATE flag is intentionally skipped.
          return push_info.flags in valid_flags # This check can require the use of & instead.

          push_desc = f'active branch "{branch_name}" to repository remote "{remote_name}"'
          log.debug('Pushing %s.', push_desc)
          try:
          push_info = remote.push()[0]
          except git.exc.GitCommandError: # Could be due to no upstream branch.
          log.warning('Failed to push %s. This could be due to no matching upstream branch.', push_desc)
          log.info('Reattempting to push %s using a lower-level command which also sets upstream branch.', push_desc)
          push_output = repo.git.push('--set-upstream', remote_name, branch_name)
          log.info('Push output was: %s', push_output)
          expected_msg = f"Branch '{branch_name}' set up to track remote branch '{branch_name}' from '{remote_name}'."
          if push_output != expected_msg:
          raise RepoPushError(f'Failed to push {push_desc}.')
          else:
          is_pushed = _is_pushed(push_info)
          logger = log.debug if is_pushed else log.warning
          logger('Push flags were %s and message was "%s".', push_info.flags, push_info.summary.strip())
          if not is_pushed:
          log.warning('Failed first attempt at pushing %s. A pull will be performed.', push_desc)
          self._pull_repo()
          log.info('Reattempting to push %s.', push_desc)
          push_info = remote.push()[0]
          is_pushed = _is_pushed(push_info)
          logger = log.debug if is_pushed else log.error
          logger('Push flags were %s and message was "%s".', push_info.flags, push_info.summary.strip())
          if not is_pushed:
          raise RepoPushError(f'Failed to push {push_desc} despite a pull.')
          log.info('Pushed %s.', push_desc)





          share|improve this answer
























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53447788%2fpush-new-local-branch-to-remote-using-gitpython%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I'm using gitpython==2.1.11 with Python 3.7. Below is my push function in which I first try a high-level push, and then a low-level push as necessary. Note how I check the return value of either command. I also log the push actions, and this explains what's happening at every step.



            class GitCommandError(Exception):
            pass

            class Git:
            def _commit_and_push_repo(self) -> None:
            repo = self._repo
            remote = repo.remote()
            remote_name = remote.name
            branch_name = repo.active_branch.name

            # Note: repo.index.entries was observed to also include unpushed files in addition to uncommitted files.
            log.debug('Committing repository index in active branch "%s".', branch_name)
            self._repo.index.commit('')
            log.info('Committed repository index in active branch "%s".', branch_name)

            def _is_pushed(push_info: git.remote.PushInfo) -> bool:
            valid_flags = {push_info.FAST_FORWARD, push_info.NEW_HEAD} # UP_TO_DATE flag is intentionally skipped.
            return push_info.flags in valid_flags # This check can require the use of & instead.

            push_desc = f'active branch "{branch_name}" to repository remote "{remote_name}"'
            log.debug('Pushing %s.', push_desc)
            try:
            push_info = remote.push()[0]
            except git.exc.GitCommandError: # Could be due to no upstream branch.
            log.warning('Failed to push %s. This could be due to no matching upstream branch.', push_desc)
            log.info('Reattempting to push %s using a lower-level command which also sets upstream branch.', push_desc)
            push_output = repo.git.push('--set-upstream', remote_name, branch_name)
            log.info('Push output was: %s', push_output)
            expected_msg = f"Branch '{branch_name}' set up to track remote branch '{branch_name}' from '{remote_name}'."
            if push_output != expected_msg:
            raise RepoPushError(f'Failed to push {push_desc}.')
            else:
            is_pushed = _is_pushed(push_info)
            logger = log.debug if is_pushed else log.warning
            logger('Push flags were %s and message was "%s".', push_info.flags, push_info.summary.strip())
            if not is_pushed:
            log.warning('Failed first attempt at pushing %s. A pull will be performed.', push_desc)
            self._pull_repo()
            log.info('Reattempting to push %s.', push_desc)
            push_info = remote.push()[0]
            is_pushed = _is_pushed(push_info)
            logger = log.debug if is_pushed else log.error
            logger('Push flags were %s and message was "%s".', push_info.flags, push_info.summary.strip())
            if not is_pushed:
            raise RepoPushError(f'Failed to push {push_desc} despite a pull.')
            log.info('Pushed %s.', push_desc)





            share|improve this answer




























              0














              I'm using gitpython==2.1.11 with Python 3.7. Below is my push function in which I first try a high-level push, and then a low-level push as necessary. Note how I check the return value of either command. I also log the push actions, and this explains what's happening at every step.



              class GitCommandError(Exception):
              pass

              class Git:
              def _commit_and_push_repo(self) -> None:
              repo = self._repo
              remote = repo.remote()
              remote_name = remote.name
              branch_name = repo.active_branch.name

              # Note: repo.index.entries was observed to also include unpushed files in addition to uncommitted files.
              log.debug('Committing repository index in active branch "%s".', branch_name)
              self._repo.index.commit('')
              log.info('Committed repository index in active branch "%s".', branch_name)

              def _is_pushed(push_info: git.remote.PushInfo) -> bool:
              valid_flags = {push_info.FAST_FORWARD, push_info.NEW_HEAD} # UP_TO_DATE flag is intentionally skipped.
              return push_info.flags in valid_flags # This check can require the use of & instead.

              push_desc = f'active branch "{branch_name}" to repository remote "{remote_name}"'
              log.debug('Pushing %s.', push_desc)
              try:
              push_info = remote.push()[0]
              except git.exc.GitCommandError: # Could be due to no upstream branch.
              log.warning('Failed to push %s. This could be due to no matching upstream branch.', push_desc)
              log.info('Reattempting to push %s using a lower-level command which also sets upstream branch.', push_desc)
              push_output = repo.git.push('--set-upstream', remote_name, branch_name)
              log.info('Push output was: %s', push_output)
              expected_msg = f"Branch '{branch_name}' set up to track remote branch '{branch_name}' from '{remote_name}'."
              if push_output != expected_msg:
              raise RepoPushError(f'Failed to push {push_desc}.')
              else:
              is_pushed = _is_pushed(push_info)
              logger = log.debug if is_pushed else log.warning
              logger('Push flags were %s and message was "%s".', push_info.flags, push_info.summary.strip())
              if not is_pushed:
              log.warning('Failed first attempt at pushing %s. A pull will be performed.', push_desc)
              self._pull_repo()
              log.info('Reattempting to push %s.', push_desc)
              push_info = remote.push()[0]
              is_pushed = _is_pushed(push_info)
              logger = log.debug if is_pushed else log.error
              logger('Push flags were %s and message was "%s".', push_info.flags, push_info.summary.strip())
              if not is_pushed:
              raise RepoPushError(f'Failed to push {push_desc} despite a pull.')
              log.info('Pushed %s.', push_desc)





              share|improve this answer


























                0












                0








                0







                I'm using gitpython==2.1.11 with Python 3.7. Below is my push function in which I first try a high-level push, and then a low-level push as necessary. Note how I check the return value of either command. I also log the push actions, and this explains what's happening at every step.



                class GitCommandError(Exception):
                pass

                class Git:
                def _commit_and_push_repo(self) -> None:
                repo = self._repo
                remote = repo.remote()
                remote_name = remote.name
                branch_name = repo.active_branch.name

                # Note: repo.index.entries was observed to also include unpushed files in addition to uncommitted files.
                log.debug('Committing repository index in active branch "%s".', branch_name)
                self._repo.index.commit('')
                log.info('Committed repository index in active branch "%s".', branch_name)

                def _is_pushed(push_info: git.remote.PushInfo) -> bool:
                valid_flags = {push_info.FAST_FORWARD, push_info.NEW_HEAD} # UP_TO_DATE flag is intentionally skipped.
                return push_info.flags in valid_flags # This check can require the use of & instead.

                push_desc = f'active branch "{branch_name}" to repository remote "{remote_name}"'
                log.debug('Pushing %s.', push_desc)
                try:
                push_info = remote.push()[0]
                except git.exc.GitCommandError: # Could be due to no upstream branch.
                log.warning('Failed to push %s. This could be due to no matching upstream branch.', push_desc)
                log.info('Reattempting to push %s using a lower-level command which also sets upstream branch.', push_desc)
                push_output = repo.git.push('--set-upstream', remote_name, branch_name)
                log.info('Push output was: %s', push_output)
                expected_msg = f"Branch '{branch_name}' set up to track remote branch '{branch_name}' from '{remote_name}'."
                if push_output != expected_msg:
                raise RepoPushError(f'Failed to push {push_desc}.')
                else:
                is_pushed = _is_pushed(push_info)
                logger = log.debug if is_pushed else log.warning
                logger('Push flags were %s and message was "%s".', push_info.flags, push_info.summary.strip())
                if not is_pushed:
                log.warning('Failed first attempt at pushing %s. A pull will be performed.', push_desc)
                self._pull_repo()
                log.info('Reattempting to push %s.', push_desc)
                push_info = remote.push()[0]
                is_pushed = _is_pushed(push_info)
                logger = log.debug if is_pushed else log.error
                logger('Push flags were %s and message was "%s".', push_info.flags, push_info.summary.strip())
                if not is_pushed:
                raise RepoPushError(f'Failed to push {push_desc} despite a pull.')
                log.info('Pushed %s.', push_desc)





                share|improve this answer













                I'm using gitpython==2.1.11 with Python 3.7. Below is my push function in which I first try a high-level push, and then a low-level push as necessary. Note how I check the return value of either command. I also log the push actions, and this explains what's happening at every step.



                class GitCommandError(Exception):
                pass

                class Git:
                def _commit_and_push_repo(self) -> None:
                repo = self._repo
                remote = repo.remote()
                remote_name = remote.name
                branch_name = repo.active_branch.name

                # Note: repo.index.entries was observed to also include unpushed files in addition to uncommitted files.
                log.debug('Committing repository index in active branch "%s".', branch_name)
                self._repo.index.commit('')
                log.info('Committed repository index in active branch "%s".', branch_name)

                def _is_pushed(push_info: git.remote.PushInfo) -> bool:
                valid_flags = {push_info.FAST_FORWARD, push_info.NEW_HEAD} # UP_TO_DATE flag is intentionally skipped.
                return push_info.flags in valid_flags # This check can require the use of & instead.

                push_desc = f'active branch "{branch_name}" to repository remote "{remote_name}"'
                log.debug('Pushing %s.', push_desc)
                try:
                push_info = remote.push()[0]
                except git.exc.GitCommandError: # Could be due to no upstream branch.
                log.warning('Failed to push %s. This could be due to no matching upstream branch.', push_desc)
                log.info('Reattempting to push %s using a lower-level command which also sets upstream branch.', push_desc)
                push_output = repo.git.push('--set-upstream', remote_name, branch_name)
                log.info('Push output was: %s', push_output)
                expected_msg = f"Branch '{branch_name}' set up to track remote branch '{branch_name}' from '{remote_name}'."
                if push_output != expected_msg:
                raise RepoPushError(f'Failed to push {push_desc}.')
                else:
                is_pushed = _is_pushed(push_info)
                logger = log.debug if is_pushed else log.warning
                logger('Push flags were %s and message was "%s".', push_info.flags, push_info.summary.strip())
                if not is_pushed:
                log.warning('Failed first attempt at pushing %s. A pull will be performed.', push_desc)
                self._pull_repo()
                log.info('Reattempting to push %s.', push_desc)
                push_info = remote.push()[0]
                is_pushed = _is_pushed(push_info)
                logger = log.debug if is_pushed else log.error
                logger('Push flags were %s and message was "%s".', push_info.flags, push_info.summary.strip())
                if not is_pushed:
                raise RepoPushError(f'Failed to push {push_desc} despite a pull.')
                log.info('Pushed %s.', push_desc)






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 15 at 2:11









                A-B-BA-B-B

                24.4k66470




                24.4k66470
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53447788%2fpush-new-local-branch-to-remote-using-gitpython%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    這個網誌中的熱門文章

                    Tangent Lines Diagram Along Smooth Curve

                    Yusuf al-Mu'taman ibn Hud

                    Zucchini