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

Saurab/sway config #3

Merged
merged 4 commits into from
May 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
[tool.poetry]
name = "pymonorepo"
name = "sway"
version = "0.1.0"
description = "managing micro-repos for monorepos"
authors = ["Saurabh Chopra <[email protected]>"]
license = "MIT"
readme = "README.md"

[tool.poetry.scripts]
sway = "sway.main:main"

[tool.poetry.dependencies]
python = "^3.8"

Expand Down
7 changes: 7 additions & 0 deletions sway/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from __future__ import annotations

from sway.main import main

if __name__ == "__main__":
raise SystemExit(main())

Empty file added sway/commands/__init__.py
Empty file.
20 changes: 20 additions & 0 deletions sway/commands/branch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from __future__ import annotations

import argparse

from sway.commands.config import SwayConfig


def branch_cmd(args: argparse.Namespace, config: SwayConfig) -> int:
# parse args
repo = args.repo or []

for _repo in repo:
if len(_repo) != 2:
raise ValueError(
f"'--repo/-r' must be used with 'repo-id repo-branch'. got {_repo}"
)

repo_id, repo_branch = _repo
print(repo_id, repo_branch)

Empty file added sway/commands/build.py
Empty file.
117 changes: 117 additions & 0 deletions sway/commands/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
from __future__ import annotations

import argparse

from sway.utils.yaml import get_config, set_config

class RepoEnvConfig:
def __init__(self, env: str, branch: str):
self.env = env
self.branch = branch

def __repr__(self):
return f"{self.env} - {self.branch}"


class RepoConfig:
def __init__(self, repo_id: str, repo: str, path: str | None = None, envs: RepoEnvConfig | None = None):
self.id = repo_id
self.repo = repo
self.path = path
self.envs = envs

def __repr__(self):
return f"{self.id} | {self.repo} | {self.path} | {self.envs}"


class SwayConfig:
def __init__(self, repos: list[RepoConfig]):
self.repos = repos

def __repr__(self):
return f"{self.repos}"


def get_config_object() -> SwayConfig:
data = get_config()

repos = []
for repo in data["repos"]:

repos.append(
RepoConfig(
# make it optional, create id from repo when not given
repo_id=repo["id"],
repo=repo["repo"],
path=repo.get("path", "./../"),
envs=[
RepoEnvConfig(env=env["env"], branch=env["branch"])
for env in repo.get("envs", [])
],
)
)

return SwayConfig(repos=repos)


def config_init(args: argparse.Namespace) -> int:
q = "Would you like to define your repos interactively? (yes/no) "
a = input(q)
if a not in ("yes", "y"):
print("Refer the README.md in the `sway` repository for config file instructions.")
return 0

repos = []
while True:
print("\nAdding Repository:")
repo = input("repo: [Example: [email protected]:saurbhc/sway] ")
repo_id = input("id: [Example: sway] ")
repo_path = input("path: [Example: /home/ubuntu/dev/sway] ")

q = f"\nWould you like to define --environment/-e for {repo_id}? (yes/no) "
a = input(q)
if a not in ("yes", "y"):
repos.append({
"id": repo_id,
"repo": repo,
"path": repo_path,
})
break

envs = []
while True:
print(f"\n- Adding Environment for Repository {repo_id}:")
env = input("- env: [Example: dev] ")
branch = input("- branch: [Example: develop] ")
envs.append({
"env": env,
"branch": branch,
})

q = f"\nWould you like to define more --environment/-e for {repo_id}? (yes/no) "
a = input(q)
if a not in ("yes", "y"):
break

repos.append({
"id": repo_id,
"repo": repo,
"path": repo_path,
"envs": envs,
})

q = "Would you like to define more repos interactively? (yes/no) "
a = input(q)
if a not in ("yes", "y"):
break

set_config(data={"repos": repos})

return 0

def config_validate() -> int:
config = get_config_object()
breakpoint()

return 0

72 changes: 72 additions & 0 deletions sway/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
from __future__ import annotations

import argparse

from sway.commands.branch import branch_cmd
from sway.commands.config import get_config_object, config_init, config_validate


def main() -> int:
parser = argparse.ArgumentParser(prog="sway")

# subparsers
subparsers = parser.add_subparsers(dest="command")
config_parser = subparsers.add_parser(
"config",
help=".pymonorepo-config.yaml options",
)
branch_parser = subparsers.add_parser(
"branch",
help="branch-management options",
)
build_parser = subparsers.add_parser(
"build",
help="build-management options",
)

# config subparsers
config_subparsers = config_parser.add_subparsers(dest="action")
config_init_parser = config_subparsers.add_parser(
"init",
help="generate .sway-config.yaml config interatively",
)
config_validate_parser = config_subparsers.add_parser(
"validate",
help="validate .sway-config.yaml config",
)

# branch subparser commands
branch_parser.add_argument(
"--repo",
"-r",
type=str,
nargs="*",
action="append",
metavar=("repo_id", "repo_branch"),
help="use repo-id with provided branch, use --repo/-r {repo-id} {repo-branch}",
)
branch_parser.add_argument(
"--environment",
"-E",
help="Project env setup in .sway-config.yaml",
)

args = parser.parse_args()

if args.command == "config" and args.action == "init":
return config_init(args=args)

if args.command == "config" and args.action == "validate":
return config_validate(args=args)

config = get_config_object()

if args.command == "branch":
return branch_cmd(args=args, config=config)

return 1


if __name__ == "__main__":
raise SystemExit(main())

Empty file added sway/utils/__init__.py
Empty file.
44 changes: 44 additions & 0 deletions sway/utils/yaml.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from __future__ import annotations

from pathlib import Path
from typing import Any

import yaml

DEFAULT_CONFIG_FILE_PATH = Path("./.sway-config.yaml")


def yaml_load(o: Any, **kwargs: Any):
return yaml.load(
o,
Loader=getattr(yaml, "CSafeLoader", yaml.SafeLoader),
**kwargs,
)


def yaml_dump(o: Any, **kwargs: Any) -> str:
return yaml.dump(
o,
Dumper=getattr(yaml, "CSafeDumper", yaml.SafeDumper),
default_flow_style=False,
indent=4,
sort_keys=False,
**kwargs,
)


def get_config():
with open(DEFAULT_CONFIG_FILE_PATH) as f:
manifest = yaml_load(f.read())

return manifest


def set_config(data: Any) -> None:
with open(DEFAULT_CONFIG_FILE_PATH, "w") as f:
f.write(yaml_dump(data))


def touch_config() -> None:
DEFAULT_CONFIG_FILE_PATH.touch(mode=0o600, exist_ok=True)