Skip to content

Commit

Permalink
Merge pull request #404 from Healthlane-Technologies/fixes/release
Browse files Browse the repository at this point in the history
gitignore modified and app name passed
  • Loading branch information
shahharsh176 authored Nov 8, 2024
2 parents 8940983 + 09cc39c commit 5700675
Show file tree
Hide file tree
Showing 10 changed files with 106 additions and 52 deletions.
14 changes: 14 additions & 0 deletions backend/src/zango/api/platform/tenancy/v1/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,20 @@ def update(self, instance, validated_data):
if extra_config_str:
try:
extra_config_json = json.loads(extra_config_str)
default_branch_config = {
"dev": "development",
"staging": "staging",
"prod": "main",
}
if extra_config_json.get("git_config", None):
extra_config_json["git_config"]["branch"] = {
**extra_config_json["git_config"]["branch"],
**{
k: v
for k, v in default_branch_config.items()
if extra_config_json["git_config"]["branch"][k] is None
},
}
validated_data["extra_config"] = extra_config_json
except json.JSONDecodeError:
raise serializers.ValidationError(
Expand Down
6 changes: 2 additions & 4 deletions backend/src/zango/api/platform/tenancy/v1/views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import json
import os
import traceback

from django_celery_results.models import TaskResult
Expand Down Expand Up @@ -115,7 +114,7 @@ def post(self, request, *args, **kwargs):
name=data["name"],
schema_name=data["name"],
app_template_name=app_template_name,
description="",
description=data.get("description"),
app_template=app_template,
tenant_type="app",
status="staged",
Expand Down Expand Up @@ -190,7 +189,6 @@ def put(self, request, *args, **kwargs):
success = True
status_code = 200
if serializer.data.get("extra_config", None):
app_directory = os.path.join(os.getcwd(), "workspaces", obj.name)
new_git_config = serializer.data["extra_config"].get(
"git_config", {}
)
Expand All @@ -203,7 +201,7 @@ def put(self, request, *args, **kwargs):
):
git_setup(
[
app_directory,
obj.name,
"--git_repo_url",
new_repo_url,
"--dev_branch",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,8 @@ def handle(self, *app_labels, **options):
w = Workspace(tenant_obj, None, True)
w.ready()
models_list = self.get_dynamic_config_models(w)
if len(models_list)<1:
self.stdout.write(
"No fixtures found."
)
if len(models_list) < 1:
self.stdout.write("No fixtures found.")
return
elif self.framework_fixtures:
models_list = ["appauth.UserRoleModel"]
Expand Down
7 changes: 4 additions & 3 deletions backend/src/zango/apps/shared/tenancy/models.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import os
import re
import requests
import tempfile
import uuid

from collections import namedtuple

import requests

from django_tenants.models import DomainMixin, TenantMixin

from django.conf import settings
Expand Down Expand Up @@ -151,12 +152,12 @@ def create(cls, name, schema_name, description, app_template_name, **other_param
# initialize tenant's workspace
init_task = initialize_workspace.delay(str(obj.uuid), app_template_path)
return obj, init_task.id

@staticmethod
def download_file(url):
response = requests.get(url)
response.raise_for_status() # Raise an exception for bad status codes

# Create a temporary file
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
temp_file.write(response.content)
Expand Down
15 changes: 12 additions & 3 deletions backend/src/zango/apps/shared/tenancy/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
from django.core.management import call_command
from django.utils import timezone

import zango

from .utils import DEFAULT_THEME_CONFIG, assign_policies_to_anonymous_user


Expand Down Expand Up @@ -44,13 +46,18 @@ def initialize_workspace(tenant_uuid, app_template_path=None):
shutil.copytree(app_template_path, app_dir, dirs_exist_ok=True)

shutil.rmtree(app_template_path)
shutil.rmtree(os.path.join(app_dir, "packages"))

if os.path.exists(os.path.join(app_dir, "packages")):
shutil.rmtree(os.path.join(app_dir, "packages"))
else:
# Creating app folder with the initial files
template_directory = os.path.join(
os.path.dirname(__file__), "workspace_folder_template"
)
cookiecutter_context = {"app_name": tenant.name}
cookiecutter_context = {
"app_name": tenant.name,
"zango_version": zango.__version__,
}

cookiecutter.main.cookiecutter(
template_directory,
Expand Down Expand Up @@ -80,7 +87,9 @@ def initialize_workspace(tenant_uuid, app_template_path=None):
else:
return {"result": "failure", "error": "Failed, see error logs"}
except Exception as e:
import traceback

return {
"result": "failure",
"error": str(e),
"error": traceback.format_exc(),
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{
"app_name": "app_name"
"app_name": "app_name",
"zango_version": "zango_version"
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@
"version": "1.0.0",
"modules": [],
"app_routes": [],
"package_routes": []
"package_routes": [],
"app_name": "{{cookiecutter.app_name}}",
"zango_version": ">={{cookiecutter.zango_version}}"
}

Large diffs are not rendered by default.

88 changes: 60 additions & 28 deletions backend/src/zango/cli/git_setup.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import json
import os
import sys

Expand All @@ -7,6 +6,8 @@

import django

from django.conf import settings

from .update_apps import find_project_name


Expand All @@ -22,19 +23,21 @@ def is_valid_app_directory(directory):


def update_settings_with_git_repo_url(
app_directory, git_repo_url, dev_branch, staging_branch, prod_branch
app_name, git_repo_url, dev_branch, staging_branch, prod_branch
):
"""
Update the 'git_repo_url' in the TenantMode.extra_config field.
Args:
- app_directory (str): Full path of the app directory.
- app_name (str): Full path of the app directory.
- git_repo_url (str): URL of the remote git repository.
- dev_branch (str): Name of the development branch.
- staging_branch (str): Name of the staging branch.
- prod_branch (str): Name of the production branch.
Returns:
- bool: True if successful, False otherwise.
"""
settings_file_path = os.path.join(app_directory, "settings.json")

try:
project_name = find_project_name()
Expand All @@ -45,12 +48,7 @@ def update_settings_with_git_repo_url(

from zango.apps.shared.tenancy.models import TenantModel

# Load current settings from settings.json
with open(settings_file_path, "r") as settings_file:
settings = json.load(settings_file)

# Update git_repo_url in settings
app_name = settings.get("app_name", "")
tenant_obj = TenantModel.objects.get(name=app_name)
git_config = {}
if tenant_obj.extra_config:
Expand All @@ -69,18 +67,14 @@ def update_settings_with_git_repo_url(
tenant_obj.save()

return True
except FileNotFoundError:
click.echo(f"Error: settings.json not found in {app_directory}.")
except json.JSONDecodeError:
click.echo(f"Error: settings.json is not valid JSON in {app_directory}.")
except Exception as e:
click.echo(f"Error occurred while updating tenant extra config: {e}")

return False


@click.command("git-setup")
@click.argument("app_directory", type=click.Path(exists=True, resolve_path=True))
@click.argument("app_name", type=str)
@click.option("--git_repo_url", prompt=True, required=True, help="Repo URL")
@click.option(
"--dev_branch",
Expand All @@ -107,20 +101,32 @@ def update_settings_with_git_repo_url(
"--initialize", is_flag=True, default=False, help="Initialize the repository"
)
def git_setup(
app_directory,
git_repo_url,
dev_branch,
staging_branch,
prod_branch,
initialize,
app_name,
):
"""
Initialize a git repository in the specified app directory and add the given remote repository URL.
APP_DIRECTORY: The directory of the app.
GIT_REPO_URL: The URL of the remote git repository.
"""

try:
from zango.apps.shared.tenancy.models import TenantModel

TenantModel.objects.get(name=app_name)
except TenantModel.DoesNotExist:
click.echo(
f"The app name '{app_name}' provided as an argument is invalid. Please ensure that you have entered the correct app name and try again."
)
return

# Check if the app directory exists
app_directory = os.path.join("workspaces", app_name)
if not os.path.exists(app_directory):
click.echo(f"The directory {app_directory} does not exist.")
return
Expand All @@ -133,48 +139,74 @@ def git_setup(
try:
if initialize:
os.system(f"rm -rf {app_directory}/.git")
os.system("rm -rf .gitignore")
os.system(f"rm -rf {app_directory}/.gitignore")
# Initialize git repository
repo = git.Repo.init(app_directory)

# Create .gitignore file
# TODO: Create git files template
with open(os.path.join(app_directory, ".gitignore"), "w") as gitignore_file:
gitignore_file.write("venv/\n")
gitignore_file.write("*.pyc\n")
gitignore_file.write("__pycache__/\n")
gitignore_file.write(".DS_Store\n")

# Create README.md
with open(os.path.join(app_directory, "README.md"), "w") as readme_file:
readme_file.write(f"# {os.path.basename(app_directory)}\n")
if settings.ENV == "dev":
with open(
os.path.join(app_directory, ".gitignore"), "w"
) as gitignore_file:
gitignore_file.write("venv/\n")
gitignore_file.write("*.pyc\n")
gitignore_file.write("__pycache__/\n")
gitignore_file.write(".DS_Store\n")
gitignore_file.write("node_modules/\n")
gitignore_file.write("*.parcel-cache\n")
gitignore_file.write("packages\n")

# Create README.md
with open(os.path.join(app_directory, "README.md"), "w") as readme_file:
readme_file.write(f"# {os.path.basename(app_directory)}\n")

parts = git_repo_url.split("://")

# Add username and password to the URL
repo_url = f"{parts[0]}://{settings.GIT_USERNAME}:{settings.GIT_PASSWORD}@{parts[1]}"

# Add remote repository
origin = repo.create_remote("origin", git_repo_url)
origin = repo.create_remote("origin", repo_url)

# Fetch all branches from the remote
origin.fetch()

remote_branches = [ref.name.split("/")[-1] for ref in origin.refs]

# Check if the branch exists locally
if dev_branch in remote_branches:
if settings.ENV == "dev" and dev_branch in remote_branches:
raise Exception(
"Can't initialize repository with existing remote branches with same name."
)
else:
# Create a new branch and checkout
repo.git.checkout("-b", dev_branch)

if settings.ENV == "staging":
if staging_branch in remote_branches:
repo.git.checkout(staging_branch, force=True)

if settings.ENV == "prod":
if prod_branch in remote_branches:
repo.git.checkout(prod_branch, force=True)

click.echo(
f"Initialized git repository in {app_directory} and set remote to {git_repo_url}"
)

update_settings_with_git_repo_url(
app_directory, git_repo_url, dev_branch, staging_branch, prod_branch
app_name,
git_repo_url,
dev_branch,
staging_branch,
prod_branch,
)

click.echo(f"Git setup completed in {app_directory}")

except Exception as e:
import traceback

traceback.print_exc()
click.echo(f"An error occurred: {e}")
13 changes: 5 additions & 8 deletions backend/src/zango/cli/update_apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,7 @@ def same_package_version_exists(package, app_directory):

def install_packages(tenant, app_directory):
from zango.core.package_utils import install_package

# Run package migrations

updated_app_manifest = json.loads(
Expand Down Expand Up @@ -456,16 +457,12 @@ def is_update_allowed(tenant, app_settings, git_mode=False, repo_url=None, branc
return False, "Invalid Zango version specifier in settings.json"

if git_mode:
if is_version_greater(remote_version, local_version):
return False, "Remote version is greater than local version"
if not (
is_version_greater(local_version, remote_version)
or (
last_release
and is_version_greater(remote_version, last_release.version)
)
if is_version_greater(local_version, remote_version) or (
last_release and is_version_greater(remote_version, last_release.version)
):
return False, "No version change detected"
else:
return True, "Update allowed"
else:
if last_release and not is_version_greater(local_version, last_release.version):
return False, "No version change detected"
Expand Down

0 comments on commit 5700675

Please sign in to comment.