Skip to content
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
43 changes: 42 additions & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ concurrency:
env:
PYTHON_VERSION: "3.13"
KUBECONFORM_VERSION: "v0.7.0"
# Checks the CloudFormation converter's output. From terraform_<version>_SHA256SUMS on
# releases.hashicorp.com; update both together.
TERRAFORM_VERSION: "1.17.2"
TERRAFORM_SHA256: "e6f16b2f0b137ee5729caa8c4e79a3bae4ee261acd198a1fcfa8584a6296605b"
# Every service under services/ (and k8s/). Jobs loop over this list, so the check names
# the branch ruleset requires stay the same when a service is added.
SERVICES: converter-api web
Expand All @@ -39,6 +43,11 @@ jobs:
echo "== $service"
(cd "services/$service" && ruff check . && ruff format --check .)
done
# The rules ruff has no setting for: no nested functions or lambdas, no * or **,
# imports at the top only, no silenced checks, docstrings and return types, and the
# writing rules for the docs. See scripts/check_code_rules.py.
- name: House code rules
run: python scripts/check_code_rules.py

test:
runs-on: ubuntu-latest
Expand Down Expand Up @@ -94,6 +103,8 @@ jobs:
curl -fsS localhost:8080/ | grep -q 'href="/compose-to-k8s"'
curl -fsS -F compose_yaml=$'services:\n app:\n image: nginx\n ports: ["80"]' \
localhost:8080/compose-to-k8s | grep -q 'kind: Deployment'
curl -fsS -F template=$'Resources:\n Logs:\n Type: AWS::S3::Bucket' \
localhost:8080/cfn-to-terraform | grep -q 'aws_s3_bucket'
- name: Show container logs
if: failure()
run: |
Expand All @@ -114,6 +125,34 @@ jobs:
- name: Validate manifests
run: kubeconform -strict -summary -output pretty k8s/

# Converts the CloudFormation fixtures and checks the Terraform with the real providers.
validate-terraform:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: ${{ env.PYTHON_VERSION }}
cache: pip
cache-dependency-path: services/*/requirements-dev.txt
- name: Install converter-api dependencies
run: pip install -r services/converter-api/requirements.txt
- name: Install Terraform
run: |
curl -sSfL --retry 5 --retry-delay 5 --retry-all-errors -o terraform.zip \
"https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_linux_amd64.zip"
echo "${TERRAFORM_SHA256} terraform.zip" | sha256sum -c -
unzip -q terraform.zip terraform
sudo mv terraform /usr/local/bin/
terraform version
- name: terraform fmt and validate on every fixture
env:
# Each provider is downloaded once and shared by all fixtures.
TF_PLUGIN_CACHE_DIR: ${{ runner.temp }}/terraform-plugins
run: |
mkdir -p "$TF_PLUGIN_CACHE_DIR"
PYTHON=python scripts/validate-terraform.sh

# Deploys k8s/ to a real kind cluster (same config as `make cluster-up`) and uses the UI.
# Catches what static checks can't: probes, securityContext vs the image, Pod Security,
# and that the NetworkPolicy really blocks everything but web from reaching converter-api.
Expand Down Expand Up @@ -167,6 +206,8 @@ jobs:
# A conversion through the UI: web -> converter-api inside the cluster.
curl -fsS -F compose_yaml=$'services:\n app:\n image: nginx\n ports: ["80"]' \
localhost:8080/compose-to-k8s | tee /tmp/convert.html | grep -q 'kind: Deployment'
curl -fsS -F template=$'Resources:\n Logs:\n Type: AWS::S3::Bucket' \
localhost:8080/cfn-to-terraform | grep -q 'aws_s3_bucket'
- name: converter-api is reachable from web only
run: |
# Single quotes only: this string is also embedded in the JSON below. The marker is
Expand Down Expand Up @@ -219,7 +260,7 @@ jobs:

# Only after every check above passes, and only for pushes to main (not PRs).
publish:
needs: [lint, test, build, validate-k8s, e2e]
needs: [lint, test, build, validate-k8s, validate-terraform, e2e]
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
permissions:
contents: read
Expand Down
80 changes: 50 additions & 30 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,56 +1,76 @@
# Contributing to DevToolkit

Thanks for helping. This guide covers local setup, adding a converter or service, and the PR process.
Thanks for helping. This guide covers local setup, the code rules, adding a converter or service and the PR process.

## Local setup

```bash
make install # .venv with app + dev dependencies for every service
make lint # ruff check + format check, every service
make lint # ruff check + format check on every service, then the house code rules
make test # pytest with coverage, every service
make run # live-reloading API on http://localhost:8000
make run-web # live-reloading web UI on http://localhost:8080 (needs `make run` in another terminal)
```

Install [kubeconform](https://github.com/yannh/kubeconform) if you change anything in `k8s/`, then run `make validate-k8s`.
Install [kubeconform](https://github.com/yannh/kubeconform) if you change anything in `k8s/`, then run `make validate-k8s`. Install [Terraform](https://developer.hashicorp.com/terraform/install) if you change the CloudFormation converter, then run `make validate-terraform`.

## Code rules

`make lint` and the `lint` CI job enforce these with ruff and `scripts/check_code_rules.py`.

- **Functions live at module or class level.** A function or method never defines another one. Lambdas are replaced by named functions; pass a bound method as a callback.
- **No `*` or `**` syntax.** No star imports, `*args`, `**kwargs`, keyword-only markers or unpacking. Write `a + [b]`, `dict(a, key=value)` and explicit arguments.
- **Imports at the top of the module**, before any other statement. Never inside a function, a class, an `if` block or a test.
- **Problems get fixed at the cause.** Comments that switch a checker off (`noqa`, `type: ignore`, `pragma: no cover`, `nosec`) are not accepted.
- **Classes with one job each.** Dataclasses go in a `models.py` and constants in a `constants.py`. An `__init__.py` holds only a docstring or plain imports.
- **Docstrings and type hints** on every module, class, function and method outside `tests/`: what it does, plus an example when the input format needs one.
- **Comments explain why**, in plain words.
- **ruff** formats the code (`make format` fixes most things).

## Writing rules

For the docs, page copy and every message a user reads (errors, conversion notes):

- Lead with the result, skip filler and prefer the smaller true claim.
- Say what something does or is.
- No apostrophes: write "does not" and "the stack name".
- No comma before "and" or "or".
- No em dashes.

The Markdown checks run with the code rules.

## Adding a new converter

Example: adding a CloudFormation to Terraform converter.
Example: a Kubernetes to Docker Compose converter.

1. **Logic.** Create a package `services/converter-api/converters/k8s_to_compose/`. Keep it pure: classes and functions take strings or dicts and return dicts, with no FastAPI imports, which keeps the logic easy to test. Give it a `models.py`, a `constants.py` and an `errors.py` with an error class that carries a message safe to show the user.
2. **Endpoint.** Add a route in `services/converter-api/main.py` with a Pydantic request model that sets a `max_length` on text fields. Return `{"success": true, ...}` on success and HTTP 400 with `{"success": false, "error": "..."}` for bad input.
3. **Tests.** Add tests covering the happy path, each supported input format and every error branch. CI fails under 95% coverage and the current code is at 100%. Please keep it there.
4. **Page.** Add a template in `services/web/templates/` and a router in `services/web/routes/`, following `routes/compose.py`: the form dataclass goes in `models.py`, its checks in `inputs.py`, the converter-api call in `conversions.py` and every user-facing text in `messages.py`. Include the router in `main.py`. Link it from `index.html` and `base.html`. Test it in `services/web/tests/` with the fake API from `conftest.py`.
5. **Docs.** Add the endpoint to `docs/reference/api.md` and its rules to a page in `docs/reference/`. Keep `README.md` to the overview and quick start.

### CloudFormation to Terraform mappings

1. **Logic.** Create `services/converter-api/converters/cfn_to_terraform.py`. Keep it pure: functions take strings or dicts and return dicts. No FastAPI imports in here, which keeps the logic easy to test.
- A `parse_...()` function that validates input and raises a clear error.
- One or more `convert_...()` functions.
2. **Endpoint.** Add a route in `services/converter-api/main.py`. Use a Pydantic request model with a `max_length` on text fields. Return `{"success": true, ...}` on success and HTTP 400 with `{"success": false, "error": "..."}` for bad input.
3. **Tests.** Add `tests/test_cfn_to_terraform.py`, covering the happy path, each supported input format, and every error branch. CI fails under 95% coverage, and the current code is at 100%. Please keep it there.
4. **Page.** Add a template in `services/web/templates/` and a GET/POST route pair in `services/web/main.py`, following `compose_to_k8s.html`. Link it from `index.html` and `base.html`. Test it in `services/web/tests/` with the fake API from `conftest.py`.
5. **Docs.** Add the endpoint to `docs/reference/api.md` and its rules to `docs/reference/conversion-rules.md`. Keep `README.md` to the overview and quick start.
Each CloudFormation type with a hand-written `aws` provider mapping is a `ResourceConverter` subclass (`converters/cfn/resources/base.py`) in one of the modules in `converters/cfn/resources/`, listed in the `CONVERTERS` tuple of its module. The class names the two types and what `Ref` and `Fn::GetAtt` read. Its `convert(b)` method takes properties one at a time from `b.props` (`attr`, `number`, `json`, `tags`, `block`...). Properties it leaves are kept as comments and reported in the notes. Check attribute names against the provider schema (`terraform providers schema -json`), add the type to a fixture in `tests/fixtures/cfn/` and run `make validate-terraform`. Types without a mapping use the `awscc` provider through `converters/cfn/awscc_index.json`; rebuild that file with `python -m tools.build_awscc_index` (from `services/converter-api`) when you bump the awscc version.

## Adding a new service

1. `services/<name>/` with a `Dockerfile` that follows the existing ones: multi-stage, non-root UID 10001, `HEALTHCHECK`, `/health` and `/ready` endpoints.
2. `k8s/<name>/` manifests following the `web` pattern: probes, resource limits, non-root security context, a ConfigMap for its settings. The image name goes in `deployment.yaml`; scripts read it from there.
3. Add the name to the `SERVICES` list in `Makefile`, `.github/workflows/ci.yaml` and `scripts/deploy-local.sh`, add a job for it in `.github/workflows/build-push.yaml`, and its directory to `.github/dependabot.yml`.

## Code style

- **ruff** for linting and formatting (`make format` fixes most things).
- **Type hints** on all functions.
- **Docstrings** on public functions. Say what it does and give an example if the input format is non-obvious.
- **Comments explain why**, not what. Plain words, no buzzwords.
3. Add the name to the `SERVICES` list in `Makefile`, `.github/workflows/ci.yaml` and `scripts/deploy-local.sh`, add a job for it in `.github/workflows/build-push.yaml` and add its directory to `.github/dependabot.yml`.

## Web UI rules

The design system is one file: `services/web/styles/input.css`. Every colour, size, radius and font is a token there, named for its job (`surface`, `ink`, `accent`), with light and dark values side by side.

- **No raw values in templates.** Use token classes (`bg-surface`, `text-ink-muted`, `border-hairline`, `rounded-sm`, `text-step-1`) and the component classes (`btn`, `card`, `field`, `alert`, `code`, `nav-link`). Tailwind's own palette, radii and text sizes are removed, so `bg-slate-50` or `rounded-lg` produce no CSS at all. If you need a value the tokens lack, add a token.
- **One component per concept.** A variant is a modifier class (`btn-primary`), not a new component.
- **Token classes in templates.** Use token classes (`bg-surface`, `text-ink-muted`, `border-hairline`, `rounded-sm`, `text-step-1`) and the component classes (`btn`, `card`, `field`, `alert`, `code`, `nav-link`). The Tailwind palette, radii and text sizes are removed, so `bg-slate-50` or `rounded-lg` produce no CSS at all. When you need a value the tokens lack, add a token.
- **One component per concept.** A variant is a modifier class (`btn-primary`). A part two pages share, such as the file list with tabs, is one template both include (`_files.html`).
- **Both themes.** New colours get a light and a dark value, checked for contrast: 4.5:1 for text, 3:1 for interface borders. The two dark blocks in `input.css` must stay identical.
- **Keyboard and motion.** Anything clickable is at least 44px tall (`min-h-11`), focus stays visible, and animation respects `prefers-reduced-motion` (already handled globally).
- **Scripts.** `app.js` and the editor bundle are the only JavaScript, and every page must work without them: forms post and the server renders the result. The one inline script (theme before first paint) is allowed by hash in the Content-Security-Policy; don't add others.
- **Icons.** Inline SVGs from `templates/icons/` (`{% include "icons/copy.svg" %}`), sized by the `.icon` class. Add icons from the pinned Lucide release named in the docs, strip `width`/`height`, and add `aria-hidden="true"`.
- **Editors.** YAML goes through the CodeMirror editor (`services/web/editor/`), which reads its colours from the tokens. A new tool page needs only a `[data-editor]` container around its textarea and a result fragment; `app.js` does the rest.
- **Copy.** Lead with the result, no filler, no em dashes, and prefer the smaller true claim. The product is called DevToolkit; pages name what the tool does, not what to paste.
- **Keyboard and motion.** Anything clickable is at least 44px tall (`min-h-11`), focus stays visible and animation respects `prefers-reduced-motion` (handled globally).
- **Scripts.** `app.js` and the editor bundle are the only JavaScript. Every page works without them: forms post and the server renders the result. The one inline script (theme before first paint) is allowed by hash in the Content-Security-Policy; keep it the only one.
- **Icons.** Inline SVGs from `templates/icons/` (`{% include "icons/copy.svg" %}`), sized by the `.icon` class. Add icons from the pinned Lucide release named in the docs, strip `width`/`height` and add `aria-hidden="true"`.
- **Editors.** YAML and Terraform go through the CodeMirror editor (`services/web/editor/`), which reads its colours from the tokens. A new tool page needs only a `[data-editor]` container around its textarea and a result fragment; `app.js` does the rest.
- **Copy.** Follow the writing rules above. The product is called DevToolkit; pages name what the tool does.

`make css` rebuilds `static/app.css` and `make editor` rebuilds `static/vendor/editor.js` (Node.js 22); the Dockerfile does both during the image build.

Expand All @@ -62,16 +82,16 @@ Every container must have:
- `livenessProbe` and `readinessProbe`
- `runAsNonRoot: true`, `allowPrivilegeEscalation: false`, `capabilities.drop: ["ALL"]`, `readOnlyRootFilesystem: true`

The `devtoolkit` namespace enforces the `restricted` Pod Security Standard, so pods that break these rules are rejected by the cluster.
The `devtoolkit` namespace enforces the `restricted` Pod Security Standard, so the cluster rejects pods that break these rules.

**No secrets in code or manifests.** Use GitHub repo variables, Workload Identity, or Kubernetes Secrets created outside the repo.
**Secrets stay outside code and manifests.** Use GitHub repo variables, Workload Identity or Kubernetes Secrets created outside the repo.

## Pull request process

1. Branch from `main`.
2. Keep each PR to one change: one converter, one fix, and so on.
2. Keep each PR to one change: one converter, one fix and so on.
3. Run `make lint test` (and `make validate-k8s` if you touched `k8s/`) before pushing.
4. Open a PR into `main`. CI must pass: lint, tests, Docker builds, manifest validation, end-to-end on kind.
4. Open a PR into `main`. CI must pass: lint, tests, Docker builds, manifest validation, Terraform validation, end-to-end on kind.
5. A maintainer reviews and merges. Merging to `main` builds and pushes the images of the services that changed.

## License
Expand Down
8 changes: 6 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ KIND_VERSION := $(shell awk '$$1 == "kind" {print $$2}' .tool-versions)
TAILWIND_VERSION := $(shell sed -n -E 's/^ARG TAILWIND_VERSION=(.*)/\1/p' services/web/Dockerfile)

.DEFAULT_GOAL := help
.PHONY: help install lint format test run run-web css editor build validate-k8s cluster-up cluster-down deploy-local port-forward clean
.PHONY: help install lint format test run run-web css editor build validate-k8s validate-terraform cluster-up cluster-down deploy-local port-forward clean

help: ## List available commands
@grep -E '^[a-zA-Z0-9_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-14s\033[0m %s\n", $$1, $$2}'
Expand All @@ -17,8 +17,9 @@ $(VENV):
install: $(VENV) ## Install dev dependencies for every service into .venv
$(BIN)/pip install $(foreach s,$(SERVICES),-r services/$(s)/requirements-dev.txt)

lint: ## Run ruff lint and format checks on every service
lint: ## Run ruff and the house code rules (scripts/check_code_rules.py) on every service and the docs
@for s in $(SERVICES); do echo "== $$s"; (cd services/$$s && ../../$(BIN)/ruff check . && ../../$(BIN)/ruff format --check .) || exit 1; done
@echo "== code rules"; $(BIN)/python scripts/check_code_rules.py

format: ## Auto-format every service with ruff
@for s in $(SERVICES); do (cd services/$$s && ../../$(BIN)/ruff check --fix . && ../../$(BIN)/ruff format .) || exit 1; done
Expand Down Expand Up @@ -55,6 +56,9 @@ build: ## Build every service's Docker image
validate-k8s: ## Validate K8s manifests with kubeconform
kubeconform -strict -summary k8s/

validate-terraform: ## Convert the CloudFormation fixtures and run terraform validate on them (needs terraform)
PYTHON=$(BIN)/python scripts/validate-terraform.sh

cluster-up: ## Create the local kind cluster (no-op if it exists)
@kind version | grep -q '$(KIND_VERSION) ' \
|| echo "warning: this project uses kind $(KIND_VERSION) (.tool-versions); you have: $$(kind version)"
Expand Down
Loading