Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Map git possibilities #3

Open
p-ferreira opened this issue Nov 24, 2023 · 3 comments
Open

Map git possibilities #3

p-ferreira opened this issue Nov 24, 2023 · 3 comments

Comments

@p-ferreira
Copy link
Owner

No description provided.

@steffencruz
Copy link

steffencruz commented Nov 24, 2023

Steps to investigate

  • Create repo
  • Add and commit files
  • Push
  • Pull
  • Checkout
  • PR
  • Diff

@steffencruz
Copy link

First Attempt

import os
import subprocess
# Allowed git commands:
commands = ['init','clone','checkout','pull','commit','push'] # create, review and merge PRs

# TODO: Replace with pygithub
class GitHubRepo:

    def __init__(self, name, title=None, remove_existing=False):
        self.name = name
        self.user = 'cruxsj'
        self.url = f'https://github.com/{self.user}/{name}.git'
        self.path = os.path.join(os.getcwd(), name)
        self.title = title
        self.branch = 'main'
        self.create(remove_existing)
        self.cd()
        print(f'Current working directory: {os.getcwd()}')

    def __str__(self):
        return f'GitHubRepo(name={self.name!r}, title={self.title!r}, path={self.path!r}, branch={self.branch!r})'

    def __repr__(self):
        return str(self)

    def _run_system_command(self, command):
        print(f'Running command: {command!r}')
        result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        # Checking the status
        if result.returncode == 0:
            print("Command executed successfully!")
            if result.stdout:
                print(f"Output: {result.stdout}")
        else:
            raise Exception(f'Command failed with return code: {result.returncode!r}: {result.stderr!r}')

    def create(self, remove_existing):

        if remove_existing and os.path.exists(self.path):
            self._run_system_command(f'rm -rf {self.path}')

        if not os.path.exists(self.name):
            os.mkdir(self.path)
            self.cd()
            self._run_system_command('git init')
            try:
                self._run_system_command(f'gh repo create -s demo_gpt_repo -d "On a mission to mine" --public')
            except:
                print('Repo already exists')

            try:
                self._run_system_command(f'git remote remove origin')
            except:
                print('No remote to remove')
            self._run_system_command(f'git remote add origin {self.url}')

        else:
            print(f'Repo {self.name!r} already exists')

        return self

    def cd(self):

        if os.getcwd() != self.path:
            print('Changing dir')
            os.chdir(self.path)
        else:
            print('Already in the right directory')
        
        print(f'Current working directory: {os.getcwd()}, contents: {os.listdir()}')

    def checkout(self, branch=None):

        if branch is None:
            branch = 'main'
        self._run_system_command(f'git checkout -b {branch}')
        self.branch = branch

    def commit(self, files, message, branch=None):

        if branch is not None:
            self.checkout(branch)

        for filename, content in files.items():
            path = os.path.join(self.path, filename)
            with open(path, 'w') as f:
                print(f'Writing to {path}')
                f.write(content)

            self._run_system_command(f'git add {path}')
        self._run_system_command(f'git commit -m "{message}"')

        return self

    def push(self, branch=None):

        if branch is None:
            branch = self.branch

        self._run_system_command(f'git push -u origin {branch}')

        return self

    def pull(self, branch=None):

        if branch is None:
            branch = self.branch

        self._run_system_command(f'git pull origin {branch}')

        return self

    def create_pr(self, branch_name, title, body):
        pass

    def merge_pr(self, pr_id):
        pass

repo = GitHubRepo(name='demo_gpt_repo', title='Demo GPT Repo', remove_existing=True)

# Imitate files coming from miner
files = {
    'README.md': f'# Demo GPT Repo \n\nThis is a demo repo for GPT. ',
    'main.py': f'print("Hello world")',
}
repo.commit(files, message='First commit').push()

@steffencruz
Copy link

Pre-existing Github+Python Solutions

https://chat.openai.com/share/91e6e4da-68ab-4594-ba89-d7de08b9f060

The best Python API for interacting with GitHub depends on your specific needs and preferences. However, a few popular options are widely used due to their robustness, ease of use, and comprehensive feature sets:

  1. PyGithub: This is one of the most popular Python libraries for interacting with the GitHub API. It provides an intuitive interface for accessing the full range of GitHub's features, including repositories, user profiles, organizations, and more. It's well-documented and actively maintained.

  2. Github3.py: Another comprehensive library that mirrors the GitHub API closely. It's known for its Pythonic interface and covers almost every aspect of the GitHub API. It's also well-documented and actively maintained.

  3. GitPython: While GitPython is more focused on interacting with Git repositories rather than the GitHub API directly, it's still a valuable tool for automating git operations in Python. If your work revolves more around git operations than GitHub's specific features, this might be a good choice.

  4. Octokit.py: This is a Python client for GitHub's Octokit, which is a family of client libraries for the GitHub API. Octokit.py provides a straightforward way to access the GitHub API and is a good choice if you're already familiar with other Octokit libraries.

  5. AIOGitHubAPI: For those working with asynchronous Python (asyncio), this library provides an async interface to the GitHub API. It's particularly useful for integration with async Python applications.

The "best" choice depends on your specific requirements:

  • If you need a full-featured, well-documented library, PyGithub is often the first choice.
  • For a more Pythonic interface, Github3.py might be more suitable.
  • GitPython is great for git-centric tasks.
  • Octokit.py is a good choice if you're comfortable with the Octokit ecosystem.
  • For async applications, AIOGitHubAPI is a strong contender.

It's also a good idea to check the latest state of these libraries, as the open-source landscape can change rapidly.

Repository owner deleted a comment from pavana21 Feb 23, 2024
Repository owner deleted a comment from pavana21 Feb 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: In Progress
Development

No branches or pull requests

4 participants
@steffencruz @p-ferreira and others