Skip to content

Commit

Permalink
init and build
Browse files Browse the repository at this point in the history
  • Loading branch information
SirEntropy committed Aug 26, 2024
1 parent 60a7e02 commit baacf39
Show file tree
Hide file tree
Showing 5 changed files with 534 additions and 0 deletions.
6 changes: 6 additions & 0 deletions cased/cli.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import click

from cased.commands.build import build
from cased.commands.deploy import deploy
from cased.commands.init import init
from cased.commands.login import login, logout
from cased.commands.resources import branches, deployments

CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])


@click.group()
def cli():
Expand All @@ -17,6 +21,8 @@ def cli():


cli.add_command(deploy)
cli.add_command(init)
cli.add_command(build)
cli.add_command(login)
cli.add_command(logout)
cli.add_command(deployments)
Expand Down
177 changes: 177 additions & 0 deletions cased/commands/build.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import os

import click
import yaml
from rich.console import Console
from rich.panel import Panel

console = Console()


@click.command()
def build():
"""Build GitHub Actions workflow based on configuration."""
console.print(Panel.fit("Building GitHub Actions Workflow", style="bold magenta"))

# Validate config and workflow files
config = validate_config_file()
workflow = validate_workflow_file()

if config and workflow:
# Generate GitHub Actions workflow
github_workflow = generate_github_actions_workflow(config, workflow)

# Write GitHub Actions workflow file
os.makedirs(".github/workflows", exist_ok=True)
with open(".github/workflows/cased_workflow.yml", "w") as f:
for key, value in github_workflow.items():
yaml.dump({key: value}, f, default_flow_style=False)
f.write("\n")

console.print(
Panel.fit(
"GitHub Actions workflow generated successfully!", style="bold green"
)
)
console.print(
"Workflow file: [bold].github/workflows/cased_workflow.yml[/bold]"
)
else:
console.print(
Panel.fit(
"Failed to generate GitHub Actions workflow. Please check your configuration.", # noqa: E501
style="bold red",
)
)


def validate_config_file():
try:
with open(".cased/config.yaml", "r") as f:
config = yaml.safe_load(f)

required_keys = ["project", "environment", "runtime", "testing"]
for key in required_keys:
if key not in config:
raise ValueError(f"Missing required section: {key}")

# Add more specific validation rules here
if "<" in str(config) or ">" in str(config):
console.print(
"[bold yellow]Warning:[/bold yellow] Some placeholder values in config.yaml have not been replaced." # noqa: E501
)

return config
except FileNotFoundError:
console.print(
"[bold red]Error:[/bold red] config.yaml not found. Run 'cased init' first."
)
except yaml.YAMLError as e:
console.print(f"[bold red]Error:[/bold red] Invalid YAML in config.yaml: {e}")
except ValueError as e:
console.print(f"[bold red]Error:[/bold red] {str(e)}")
return None


def validate_workflow_file():
try:
with open(".cased/workflow.yaml", "r") as f:
workflow = yaml.safe_load(f)

required_keys = ["name", "on", "jobs"]
for key in required_keys:
if key not in workflow:
raise ValueError(f"Missing required key in workflow: {key}")

# Add more specific validation rules here

return workflow
except FileNotFoundError:
console.print(
"[bold red]Error:[/bold red] workflow.yaml not found. Run 'cased init' first." # noqa: E501
)
except yaml.YAMLError as e:
console.print(f"[bold red]Error:[/bold red] Invalid YAML in workflow.yaml: {e}")
except ValueError as e:
console.print(f"[bold red]Error:[/bold red] {str(e)}")
return None


def generate_github_actions_workflow(config, workflow):
github_workflow = {"name": workflow["name"], "on": workflow["on"], "jobs": {}}

# Build and Test job
build_and_test_job = {
"runs-on": "ubuntu-latest",
"steps": [
{"name": "Checkout code", "uses": "actions/checkout@v2"},
{
"name": "Set up Python",
"uses": "actions/setup-python@v2",
"with": {"python-version": config["environment"]["python_version"]},
},
{"name": "Install dependencies", "run": "pip install -r requirements.txt"},
{"name": "Run tests", "run": f"python -m {config['testing']['framework']}"},
],
}

if config["testing"]["coverage"].get("enabled"):
build_and_test_job["steps"].append(
{
"name": "Run coverage",
"run": f"coverage run -m {config['testing']['framework']} && coverage {config['testing']['coverage']['report_type']}", # noqa: E501
}
)

github_workflow["jobs"]["build_and_test"] = build_and_test_job

# Deploy job
deploy_job = {
"needs": "build_and_test",
"runs-on": "ubuntu-latest",
"steps": [
{"name": "Checkout code", "uses": "actions/checkout@v2"},
],
}

if config["docker"]["enabled"]:
deploy_job["steps"].extend(
[
{
"name": "Set up Docker Buildx",
"uses": "docker/setup-buildx-action@v1",
},
{
"name": "Build and push Docker image",
"uses": "docker/build-push-action@v2",
"with": {
"context": ".",
"push": True,
"tags": f"{config['docker']['image_name']}:${{ github.sha }}",
},
},
]
)

if config["cloud_deployment"]["provider"] == "AWS":
deploy_job["steps"].extend(
[
{
"name": "Configure AWS credentials",
"uses": "aws-actions/configure-aws-credentials@v1",
"with": {
"aws-access-key-id": "${{ secrets.AWS_ACCESS_KEY_ID }}",
"aws-secret-access-key": "${{ secrets.AWS_SECRET_ACCESS_KEY }}",
"aws-region": config["cloud_deployment"]["region"],
},
},
{
"name": "Deploy to AWS",
"run": 'echo "Add your AWS deployment commands here"',
},
]
)

github_workflow["jobs"]["deploy"] = deploy_job

return github_workflow
Loading

0 comments on commit baacf39

Please sign in to comment.