Search code examples
pythongitgitpython

How to skip Windows Credentials Manager using GitPython


I am using GitPython to execute git commands that require authentication such as git clone. I am using Windows. My configured credential helper is Windows' Credential Manager and I don't want to change it. That's why when the program runs, I enter my credentials via a GUI which is ok. But during tests, I want to be able to provide them statically, I don't want to enter them via or GUI or any interactive way. Also I don't want to change global configuration for credential.helper even for a limited time (like during runtime) because that might have some side effects. Is there a way I can handle this?


Solution

  • I used _persistent_git_options attribute of Git class with monkey patching. This way, git word in the commands are followed by -c credential.helper= by default.

    import git as gitpy
    '''Keep the original __init__ implementation of gitpy.cmd.Git'''
    old__init__ = gitpy.cmd.Git.__init__
    
    '''
    Method redefining ``__init__`` method of ``gitpy.cmd.Git``.
    
    The new definition wraps original implementation and adds
    "-c credential.helper=" to persistent git options so that
    it will be included in every git command call.
    '''
    def new__init__(self, *args, **kwargs):
        old__init__(self, *args, **kwargs)
        self._persistent_git_options = ["-c", "credential.helper="]
    
    
    '''Set __init__ implementation of gitpy.cmd.Git to that is implemented above'''
    gitpy.cmd.Git.__init__ = new__init__