I am trying to write a python script that when run, will push files to one of my GitHub repositories. I'm using the package GitPython. I want to use an access token to log in into my GitHub account (instead of entering my username and password) because I have two-factor authentication. I've created the token, but I can't figure out how to add it to my GitPython code.
Here is my code so far:
def push(repo_dir):
import os
from git import Repo
# set working directory
os.chdir("XXX")
#repo_dir = 'Pantone'
repo = Repo(repo_dir)
file_list = [
"index.html",
"Data/colors.csv"
]
commit_message = 'Adding new color'
repo.index.add(file_list)
repo.index.commit(commit_message)
origin = repo.remote('origin')
origin.push()
If I understand your question correctly, you are trying to write a python script to update files stored at your repository in GitHub.
The alternative to using GitPython is to just directly import github
Here is the alternative to your code:
Get file content from GitHub repo:
from github import Github
token = "your_github_token_here"
g = Github(token)
repo = g.get_repo("username/repository")
contents = repo.get_contents("")
while contents:
file_content = contents.pop(0)
if file_content.type == "dir":
contents.extend(repo.get_contents(file_content.path))
else:
print(file_content.path)
file_content = repo.get_contents("path_to_your_file_in_github")
file_content_decoded = (str(file_content.decoded_content.decode()))
print(file_content_decoded)
Write file content to GitHub repo:
# Write contents to file in GitHub repo:
token = "your_github_token"
g = Github(token)
file_path = "path_to_your_file"
content = "This is the content of your file."
try:
file = repo.get_contents(file_path)
repo.update_file(file.path, "Updating file", content, file.sha)
print(f"Updated {file_path}")
except:
repo.create_file(file_path, "Creating new file", content)
print(f"Created {file_path}")
file = repo.get_contents(file_path)
repo.update_file(file.path, "Updating file", content, file.sha)
print(f"Updated {file_path}")
I am not sure if that fully answers the question, but it works for me!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With