Python Forum
Creating release on github remote repo with file list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating release on github remote repo with file list
#1
Hello, I'm making the release function which uploads files and creates local and remote github repo. Everything works well until uploading part. Always gives me 400 error, invalid name for request. I tried asking gpt but no resolves, it even commented my function everywhere

def release_to_github(repo_path: str, tag_name: str, release_name: str, access_token: str, files_to_attach: list, pre_release: bool = False) -> None:
    """
    Creates a GitHub release and uploads specified files as assets.

    Args:
        repo_path (str): Local path to the Git repository.
        tag_name (str): Name of the tag to create/release.
        release_name (str): Name of the GitHub release.
        access_token (str): GitHub personal access token with 'repo' scope.
        files_to_attach (list): List of tuples, each containing (file_path, file_name).
        pre_release (bool, optional): Whether the release is a pre-release. Defaults to False.

    Returns:
        None
    """
    try:
        # Validate inputs
        if not os.path.exists(repo_path):
            print(f"Error: Repository path '{repo_path}' does not exist.")
            return

        if not valid_token(access_token):
            print("Error: Invalid GitHub access token.")
            return

        # Initialize Git repository object
        repo = git.Repo(repo_path)

        # Check if tag already exists locally
        if tag_name in [tag.name for tag in repo.tags]:
            print(f"Error: Tag '{tag_name}' already exists in the repository.")
            return

        # Create a new tag in the repository
        repo.create_tag(tag_name)

        # Commit files to be attached to the release
        for file_info in files_to_attach:
            file_path, file_name = file_info
            repo.index.add([file_path])

        repo.index.commit(f"Added release files for {release_name}")

        print(f"Local release '{release_name}' with tag '{tag_name}' created successfully.")

        # Get the remote URL to extract owner and repository name
        remote_url = repo.remotes.origin.url

        # Extract owner and repository name from remote URL
        # Example: https://github.com/owner/repo.git
        if remote_url.endswith('.git'):
            remote_url = remote_url[:-4]  # Remove '.git' at the end if present
        
        parts = remote_url.split('/')
        owner = parts[-2]
        repository = parts[-1]

        # Construct release URL
        create_release_url = f"https://api.github.com/repos/{owner}/{repository}/releases"
        headers = {
            "Authorization": f"token {access_token}",
            "Accept": "application/vnd.github.v3+json"
        }
        data = {
            "tag_name": tag_name,
            "name": release_name,
            "draft": False,
            "prerelease": pre_release
        }

        # Create release on GitHub
        response = requests.post(create_release_url, headers=headers, json=data)

        if response.status_code == 201:
            print(f"Created GitHub release '{release_name}' for tag '{tag_name}' successfully.")

            # Upload assets to the release
            release_id = response.json().get("id")
            upload_url = f"https://uploads.github.com/repos/{owner}/{repository}/releases/{release_id}/assets"
            for file_info in files_to_attach:
                file_path, file_name = file_info
                with open(file_path, "rb") as f:
                    # Ensure filename is properly encoded
                    files = {
                        'name': (file_name, f, 'application/octet-stream')
                    }
                    asset_response = requests.post(upload_url, headers=headers, files=files)
                    if asset_response.status_code == 201:
                        print(f"Uploaded '{file_name}' as an asset to the release.")
                    else:
                        print(f"Failed to upload '{file_name}' as an asset. Status code: {asset_response.status_code}, Message: {asset_response.text}")

        else:
            print(f"Failed to create GitHub release. Status code: {response.status_code}, Message: {response.text}")

    except Exception as e:
        print(f"An unexpected error occurred: {e}")

def valid_token(token: str) -> bool:
    # Implement your access token validation logic here
    # Example: Check token format, expiration, etc.
    return True  # Placeholder, replace with actual validation

# Example usage:
def main():
    try:
        with open(os.path.join(os.getcwd(), "package.rel"), 'rb') as r:
            r_data = tomli.load(r)

        with open(os.path.join(os.getcwd(), "pulse.toml"), 'rb') as p:
            project_data = tomli.load(p)

        with open(os.path.join(CONFIG_PATH, "pulseconfig.toml"), 'rb') as c:
            user_data = tomli.load(c)

        files_to_attach = []
        if "rel_windows" in r_data:
            file_path = os.path.join(os.getcwd(), r_data["rel_windows"])
            file_name = os.path.basename(file_path)
            files_to_attach.append((file_path, file_name))
        if "rel_linux" in r_data:
            file_path = os.path.join(os.getcwd(), r_data["rel_linux"])
            file_name = os.path.basename(file_path)
            files_to_attach.append((file_path, file_name))

        release_to_github(os.path.join(os.getcwd(), '.git'), r_data["version"], "Some release", user_data["token"], files_to_attach, False)

    except Exception as e:
        print(f"An unexpected error occurred: {e}")

if __name__ == "__main__":
    main()
Reply
#2
Quote:I tried asking gpt but no resolves

I think it is wrong way. When program has error, you generally shoud debug it rather than ask 3rd party "what is wrong". Questions generally may help when you nailed down some specific issue and is unsure how to resolve it.

Particularly, do you mean you get 400 in the line 87? Dump the full request data you are sending here. Since the response code says the request is malformed, it would be good to check what exactly you are sending - and perhaps you'll see how exactly it is "malformed", right?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Creating a Dataframe from Zenodo zip file with multiple CSVs about Spotify man0s 0 1,445 Apr-26-2022, 01:45 PM
Last Post: man0s
  Creating more than one excel File at once malvarez1976 0 1,897 Dec-15-2020, 02:04 AM
Last Post: malvarez1976
  How to check whether a file exist in all github branch using github3.py senthilpalani 0 1,307 Nov-03-2020, 08:53 AM
Last Post: senthilpalani
  Creating A List of DataFrames & Manipulating Columns in Each DataFrame firebird 1 4,447 Jul-31-2019, 04:04 AM
Last Post: scidam
  Creating matrix counting words in list of strings jazmad 2 3,651 Dec-23-2018, 05:47 PM
Last Post: jazmad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020