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

test pycafe link #454

Closed
wants to merge 10 commits into from
6 changes: 1 addition & 5 deletions .github/workflows/host-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,11 @@ jobs:
| jq -r '.artifacts[0].id')
echo "artifact_id=$artifact_id" >> $GITHUB_ENV

- name: Get download URL
run: echo "artifact_url=https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}/artifacts/${{ env.artifact_id }}" >> $GITHUB_ENV

- name: Post Link
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_REPOSITORY: ${{ github.repository }}
PR_NUMBER: ${{ github.event.inputs.pr_number }}
ARTIFACT_URL: ${{ env.artifact_url }}
PR_NUMBER: ${{ github.event.inputs.pr_number }}
ARTIFACT_ID: ${{ env.artifact_id }}
GITHUB_OWNER: snehilvj
FILE_FULLNAME: dash_mantine_components-${{ env.version }}-py3-none-any.whl
Expand Down
31 changes: 8 additions & 23 deletions PRs/app.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,14 @@
from dash import *
import dash_mantine_components as dmc
from dash import Dash, dcc, _dash_renderer
from dash import _dash_renderer

_dash_renderer._set_react_version("18.2.0")

app = Dash(external_stylesheets=dmc.styles.ALL)
app = Dash(__name__)

component = dcc.Markdown(
"""
### PR Sample App
app.layout = dmc.MantineProvider([
html.Div('Hi PyCafe'),
dmc.MultiSelect(data=['Test1', 'Test2'])
])

This sample app uses the unreleased version of dash-mantine-components based on this pull request. You can use it to test bug fixes or try new features.

### How to Use:

1. Replace this app with your own code.
1. The app is hosted live on PyCafe.
3. If you have a PyCafe account, you can save the app to your account. Otherwise, simply copy the URL.
4. Share the link in the pull request or anywhere else.

"""
)


app.layout = dmc.MantineProvider([component])


if __name__ == "__main__":
app.run(debug=True)
app.run()
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,6 @@ is greatly appreciated and helps keep the project growing and thriving!

## ⭐️ Support by Starring the Project
If you find this project helpful, consider giving it a star on GitHub! ⭐️ It helps others discover the project and
motivates us to keep improving it. Your support is greatly appreciated!
motivates us to keep improving it. Your support is greatly appreciated!


121 changes: 85 additions & 36 deletions tmp_deploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,40 +4,47 @@
from urllib.parse import quote, urlencode
import os
from github import Github
from datetime import datetime

GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
REPO_NAME = os.getenv("GITHUB_REPOSITORY")
PR_NUMBER = int(os.getenv("PR_NUMBER"))

files = []
code = ''
code = ""
reqs = {}
for f in os.listdir('PRs'):
file_path = os.path.join('PRs', f)
if f not in ['app.py','requirements.txt']:
with open(file_path, 'rb') as file:
for root, dirs, filenames in os.walk(f"PRs"):
for f in filenames:
file_path = os.path.join(root, f)
if f not in ["app.py", "requirements.txt"]:
with open(file_path, "rb") as file:
files.append(
{
"name": f,
"name": os.path.relpath(file_path, "PRs"),
"content": base64.b64encode(file.read()).decode("utf8"),
"encoding": "base64"
"encoding": "base64",
}
)
elif f == 'app.py':
with open(file_path, 'r') as file:
code = file.read()
else:
with open(file_path, 'r') as file:
reqs = {
'name': f,
'content': file.read()
}
elif f == "app.py":
with open(file_path, "r") as file:
code = file.read()
elif f == "requirements.txt":
with open(file_path, "r") as file:
reqs = {
"name": os.path.relpath(file_path, "PRs"),
"content": file.read(),
}

new_package = f'{os.getenv("PACKAGE_NAME")} @ https://py.cafe/gh/artifact/{os.getenv("GITHUB_REPOSITORY")}/{os.getenv("ARTIFACT_ID")}/{os.getenv("FILE_FULLNAME")}'
if os.getenv("PACKAGE_NAME") in reqs['content']:
reqs['content'] = reqs['content'].replace(os.getenv("PACKAGE_NAME"), new_package)
if os.getenv("PACKAGE_NAME") in reqs["content"]:
reqs["content"] = reqs["content"].replace(os.getenv("PACKAGE_NAME"), new_package)
else:
reqs['content'] += f'\n{new_package}'
reqs["content"] += f"\n{new_package}"


def generate_link(files, code):
json_object = {
"requirements": reqs['content'],
"requirements": reqs["content"],
"code": code,
"files": files,
}
Expand All @@ -50,30 +57,72 @@ def generate_link(files, code):
type = "dash" # replace by dash, or streamlit
return f"{base_url}/snippet/{type}/v1?{query}"


# Generate the link
link = generate_link(files, code)

# Initialize Github object
g = Github(GITHUB_TOKEN)

# Get the repository
repo = g.get_repo(REPO_NAME)

# Get the pull request
pull_request = repo.get_pull(PR_NUMBER)


# Post the link as a comment on the pull request
def post_comment(link):
# Get environment variables
GITHUB_TOKEN = os.getenv('GITHUB_TOKEN')
REPO_NAME = os.getenv('GITHUB_REPOSITORY')
PR_NUMBER = int(os.getenv('PR_NUMBER'))
# Find existing comments by the bot
comments = pull_request.get_issue_comments()
bot_comment = None

for comment in comments:
if comment.body.startswith("Test Environment for ["):
bot_comment = comment
break

# Get current UTC datetime
current_utc_time = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")

# Define the comment body with datetime
comment_body = f"Test Environment for [{REPO_NAME}-{PR_NUMBER}]({link})\nUpdated on: {current_utc_time}"

# Update the existing comment or create a new one
if bot_comment:
bot_comment.edit(comment_body)
print("Comment updated on the pull request.")
else:
pull_request.create_issue_comment(comment_body)
print("Comment added to the pull request.")

# Initialize Github object
g = Github(GITHUB_TOKEN)

# Get the repository
repo = g.get_repo(REPO_NAME)
# Create deployment message for a status
def create_deployment_message(link):
# Create a deployment
deployment = repo.create_deployment(
ref=pull_request.head.sha,
task="deploy",
auto_merge=False,
required_contexts=[],
payload={},
environment="staging",
description=f"Deploying PR #{PR_NUMBER} to PyCafe",
transient_environment=True,
production_environment=False,
)

# Get the pull request
pull_request = repo.get_pull(PR_NUMBER)
# Update the deployment status
deployment.create_status(
state="success",
target_url="https://py.cafe/",
description="Deployment to staging succeeded!",
environment_url=link,
auto_inactive=True,
)

# Add a comment to the pull request
comment_body = f"Generated link: [{REPO_NAME}-{PR_NUMBER}]({link})"
pull_request.create_issue_comment(comment_body)
print(f"Deployment message added to PR #{PR_NUMBER}")

print("Comment added to the pull request.")

# Call the function to post the comment
post_comment(link)
post_comment(link)
create_deployment_message(link)
Loading