How to automate git push processes using python?

Question:

I’m trying to automate the git push processes using python.

I’ve succeeded automating all except entering the username and password after the git push command.

This is my code so far:

import subprocess
import sys

add: str = sys.argv[1]
commit: str = sys.argv[2]
branch: str = sys.argv[3]


def run_command(command: str):
    print(command)
    process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
    print(str(process.args))
    if command.startswith("git push"):
        output, error = process.communicate()
    else:
        output, error = process.communicate()
    try:
        output = bytes(output).decode()
        error = bytes(error).decode()
        if not output:
            print("output: " + output)
        print("error: " + error)
    except TypeError:
        print()


def main():
    global add
    global commit
    global branch
    if add == "" or add == " ":
        add = "."
    if branch == "":
        branch = "master"
    print("add: '" + add + "' commit: '" + commit + "' branch: '" + branch + "'")

    command = "git add " + add
    run_command(command)

    commit = commit.replace(" ", "''")
    command = 'git commit -m "' + commit + '"'
    run_command(command)

    command = "git push origin " + branch
    run_command(command)


if __name__ == '__main__':
    main()

Is there any way to send the information to the command?

Asked By: TheZadok42

||

Answers:

If possible, use a credential helper in order to cache that information (credentials associated to a remote URL).
Check the gitcredential section and “Git Tools – Credential Storage“.

git config --global credential.helper

That way, you won’t have to enter that information at all.

Answered By: VonC

This is how I solved it:

# make sure to cd into the git repo foler

import subprocess
import sys
import os


msg = input('Type the commit message (+ ENTER):') 
repo_directory = os.getcwd()

subprocess.run(["git", "add", "."], cwd=repo_directory)
# commit file
subprocess.run(["git", "commit", "-m", msg], cwd=repo_directory)
# push
subprocess.run(["git", "push"], cwd=repo_directory)  
Answered By: Bas
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.