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
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,17 @@ budjira project clear # drop the cache
budjira project sync --force # refresh despite a valid cache
```

**Projects of an instance:** list them, or create a company-managed project that shares an
existing project's issue type, screen and workflow schemes — with a Kanban board on top
(needs the *Administer Jira* global permission):

```bash
budjira project list # key, name, id, style, lead
budjira project create APX --name "Apodeixis" --like CDDSINT --dry-run # payloads only
budjira project create APX --name "Apodeixis" --like CDDSINT # project + filter + board
budjira project create OPS --name "Operations" --like CDDSINT --board none
```

### 6. Definition of Ready (DoR) Templates

budjira supports customizable templates for different issue types to ensure consistent quality.
Expand Down
208 changes: 205 additions & 3 deletions budjira/cli/project.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,45 @@
"""Project metadata management commands."""
"""Project commands: metadata cache (sync/show/clear) and administration (list/create)."""

from __future__ import annotations

import json
import re
from enum import Enum
from typing import TYPE_CHECKING, Annotated, Any

import typer
from rich.console import Console
from rich.syntax import Syntax
from rich.table import Table

from budjira.config import get_settings
from budjira.config.metadata_cache import MetadataCache
from budjira.services.projects import build_board_payload, build_filter_payload, build_project_payload
from budjira.utils.connection import get_active_connection
from budjira.utils.errors import BudjiraError
from budjira.utils.errors import BudjiraError, ValidationError
from budjira.utils.formatter import OutputFormatter

if TYPE_CHECKING:
from budjira.models.project import ReferenceProject

app = typer.Typer(
name="project",
help="Manage Jira project metadata (issue types, priorities, components)",
help="Manage Jira projects: list and create projects, cache project metadata",
no_args_is_help=True,
)
console = Console()

# Jira Cloud's default key rule: a letter, then letters/digits/underscore, 2-10 chars.
_PROJECT_KEY = re.compile(r"^[A-Z][A-Z0-9_]{1,9}$")


class BoardChoice(str, Enum):
"""Board to create for a new project."""

KANBAN = "kanban"
SCRUM = "scrum"
NONE = "none"


def _get_metadata_cache() -> MetadataCache:
"""Get metadata cache instance.
Expand Down Expand Up @@ -179,3 +201,183 @@ def clear_metadata(
except BudjiraError as e:
console.print(f"[red]✗[/red] {e}", style="red")
raise typer.Exit(1) from None


def _is_json(ctx: typer.Context) -> bool:
return OutputFormatter.is_json_format(ctx.obj.get("format", "table") if ctx.obj else "table")


@app.command("list")
def list_projects(
ctx: typer.Context,
connection_name: Annotated[
str | None,
typer.Option("--connection", "-c", help="Connection name (uses active connection if not specified)"),
] = None,
) -> None:
"""List all projects of the instance the token can see.

Shows key, name, id, management style (company-/team-managed) and lead.
Answers "does project KEY exist?" — which a search cannot, since an empty
project and a missing one both return no issues.

Examples:
budjira project list
budjira --format json project list --connection work
"""
try:
from budjira.core.jira_client import JiraClient

connection = get_active_connection(connection_name)
projects = JiraClient.from_connection(connection).projects.list_projects()

if _is_json(ctx):
OutputFormatter.output_json(
{
"total": len(projects),
"projects": [{**p.model_dump(), "management": p.management} for p in projects],
}
)
return

table = Table(show_header=True, header_style="bold", box=None, padding=(0, 2))
table.add_column("Key", style="cyan")
table.add_column("Name")
table.add_column("ID", style="dim")
table.add_column("Style")
table.add_column("Lead")
for p in projects:
table.add_row(p.key, p.name, p.id, p.management, p.lead or "[dim]-[/dim]")
console.print(table)
console.print(f"\n[dim]{len(projects)} projects on {connection.name}[/dim]")

except BudjiraError as e:
console.print(f"[red]✗[/red] {e}", style="red")
raise typer.Exit(1) from None


def _print_plan(key: str, reference: ReferenceProject, plan: dict[str, Any]) -> None:
"""Show the payloads a create would send."""
console.print(
f"\n[cyan]Dry run:[/cyan] would create project {key} like {reference.key} — read calls only, nothing created"
)
for label in ("project", "filter", "board"):
if plan.get(label) is not None:
console.print(f"[cyan]{label} payload:[/cyan]")
console.print(Syntax(json.dumps(plan[label], indent=2, ensure_ascii=False), "json", word_wrap=True))


def _scheme_summary(reference: ReferenceProject) -> str:
def show(value: object) -> str:
return "default" if value is None else str(value)

return (
f"issue type scheme {show(reference.issue_type_scheme)}, "
f"screen scheme {show(reference.issue_type_screen_scheme)}, "
f"workflow scheme {show(reference.workflow_scheme)}"
)


@app.command("create")
def create_project(
ctx: typer.Context,
key: Annotated[str, typer.Argument(help="Key of the new project (e.g. APX)")],
name: Annotated[str, typer.Option("--name", "-n", help="Name of the new project")],
like: Annotated[
str,
typer.Option("--like", help="Company-managed project whose issue type, screen and workflow schemes to reuse"),
],
board: Annotated[
BoardChoice,
typer.Option("--board", "-b", help="Board to create on the new project ('none' to skip)"),
] = BoardChoice.KANBAN,
dry_run: Annotated[
bool,
typer.Option("--dry-run", help="Read the reference and print the payloads; create nothing"),
] = False,
connection_name: Annotated[
str | None,
typer.Option("--connection", "-c", help="Connection name (uses active connection if not specified)"),
] = None,
) -> None:
"""Create a company-managed project that shares another project's schemes.

The new project reuses the reference's issue type scheme, issue type screen
scheme and workflow scheme; you become its lead, issues start unassigned.
Then a filter "project = KEY ORDER BY Rank ASC" (shared with the project)
and a board on it are created. The permission scheme is left at the default
(Jira Free does not allow changing it). Needs the 'Administer Jira' global
permission.

Examples:
budjira project create APX --name Apodeixis --like CDDSINT --dry-run
budjira project create APX --name Apodeixis --like CDDSINT
budjira project create OPS --name Operations --like CDDSINT --board none
"""
try:
from budjira.core.jira_client import JiraClient

key = key.strip().upper()
like = like.strip().upper()
if not _PROJECT_KEY.match(key):
raise ValidationError(
f"Invalid project key '{key}': start with a letter, then letters, digits or '_' (2-10 characters)."
)

connection = get_active_connection(connection_name)
projects = JiraClient.from_connection(connection).projects

if projects.project_exists(key):
raise ValidationError(f"Project '{key}' already exists on {connection.name}.")

reference = projects.get_reference(like)
payload = build_project_payload(key, name, reference, lead_account_id=projects.current_account_id())
board_type = None if board is BoardChoice.NONE else board.value

if dry_run:
plan = {
"dry_run": True,
"like": reference.key,
"project": payload,
"filter": build_filter_payload(key, "<new project id>") if board_type else None,
"board": build_board_payload(key, "<new filter id>", board_type) if board_type else None,
}
if _is_json(ctx):
OutputFormatter.output_json(plan)
else:
_print_plan(key, reference, plan)
return

created = projects.create_project(payload)
result: dict[str, Any] = {"project": created, "like": reference.key, "filter_id": None, "board_id": None}
if not _is_json(ctx):
console.print(
f"[green]✓[/green] Created project [cyan]{created['key']}[/cyan] (id {created['id']}) "
f"like {reference.key}: {_scheme_summary(reference)}"
)

if board_type:
try:
result["filter_id"] = projects.create_filter(build_filter_payload(key, created["id"]))
result["board_id"] = projects.create_board(build_board_payload(key, result["filter_id"], board_type))
except BudjiraError as e:
filter_note = f" (filter {result['filter_id']} exists)" if result["filter_id"] else ""
raise BudjiraError(
f"Project {key} was created, but its {board_type} board was not{filter_note}: {e}"
) from e

if _is_json(ctx):
OutputFormatter.output_json(result)
return

if board_type:
console.print(
f"[green]✓[/green] Board '{key} board' (id {result['board_id']}, {board_type}) "
f"on filter {result['filter_id']}"
)
base_url = str(connection.url).rstrip("/")
console.print(f"\n[dim]View in Jira: {base_url}/browse/{key}[/dim]")

except BudjiraError as e:
console.print(f"[red]✗[/red] {e}", style="red")
raise typer.Exit(1) from None
3 changes: 3 additions & 0 deletions budjira/core/jira_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
LabelService,
LinkService,
MetadataService,
ProjectService,
SprintService,
TransitionService,
WorklogService,
Expand Down Expand Up @@ -53,6 +54,7 @@ class JiraClient:
- CommentService: Comments
- AttachmentService: File attachments
- MetadataService: Projects, issue types, priorities, users
- ProjectService: Project listing and creation (create --like)
"""

def __init__(self, connection: Connection, api_token: str) -> None:
Expand Down Expand Up @@ -103,6 +105,7 @@ def __init__(self, connection: Connection, api_token: str) -> None:
self.metadata = MetadataService(self._client)
self.links = LinkService(self._client)
self.sprints = SprintService(self._client)
self.projects = ProjectService(self._client)

@classmethod
def from_connection(cls, connection: Connection) -> JiraClient:
Expand Down
32 changes: 31 additions & 1 deletion budjira/models/ai_prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -615,7 +615,37 @@ def get_default_ai_prompt_template() -> AiPromptTemplate:

**Used by:** issue creation (validating `--type`/`--priority`, sub-task detection) and the
connection-specific AI prompt. The cache lives in `~/.config/budjira/cache/` and expires
automatically; `sync --force` refreshes it on demand.""",
automatically; `sync --force` refreshes it on demand.

### Listing and creating projects

**Available since v1.38.0**

```bash
# All projects the token can see: key, name, id, company-/team-managed, lead
budjira project list
budjira --format json project list

# Preview: reads the reference project, prints the payloads, creates nothing
budjira project create APX --name "Apodeixis" --like CDDSINT --dry-run

# Create a company-managed project sharing CDDSINT's issue type, screen and
# workflow schemes, plus a Kanban board on "project = APX ORDER BY Rank ASC"
budjira project create APX --name "Apodeixis" --like CDDSINT

# Other board type, or none
budjira project create OPS --name "Operations" --like CDDSINT --board scrum
budjira project create OPS --name "Operations" --like CDDSINT --board none
```

**Notes:**
- Use `project list` to check whether a key exists — `search "project = KEY"` returns
"No issues found" for an empty project and a missing one alike.
- `--like` needs a **company-managed** reference; team-managed projects have no schemes.
- You become the project lead; issues start unassigned. The permission scheme stays at
the default (Jira Free does not allow changing it).
- Needs the Jira global permission **Administer Jira**. If the board step fails, the
project already exists — the error says so; do not re-run `create`.""",
order=6.5,
enabled=True,
),
Expand Down
40 changes: 40 additions & 0 deletions budjira/models/project.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""Models for Jira project administration (listing and creating projects)."""

from __future__ import annotations

from typing import Literal

from pydantic import BaseModel

BoardType = Literal["kanban", "scrum"]


class ProjectSummary(BaseModel):
"""One project of an instance, as listed by ``project list``."""

key: str
name: str
id: str
style: str
lead: str | None = None

@property
def management(self) -> str:
"""Human label for Jira's ``style`` (classic / next-gen)."""
return {"classic": "company-managed", "next-gen": "team-managed"}.get(self.style, self.style)


class ReferenceProject(BaseModel):
"""A company-managed project whose schemes a new project reuses (``--like``).

Scheme IDs are kept as Jira returns them; ``None`` means the reference has no
scheme of that kind assigned (Jira's default applies) and the new project
will get the default too.
"""

key: str
id: str
project_type_key: str
issue_type_scheme: str | None = None
issue_type_screen_scheme: str | None = None
workflow_scheme: int | None = None
2 changes: 2 additions & 0 deletions budjira/services/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from budjira.services.labels import LabelService
from budjira.services.links import LinkService
from budjira.services.metadata import MetadataService
from budjira.services.projects import ProjectService
from budjira.services.sprints import SprintService
from budjira.services.transitions import TransitionService
from budjira.services.worklogs import WorklogService
Expand All @@ -21,6 +22,7 @@
"LabelService",
"LinkService",
"MetadataService",
"ProjectService",
"SprintService",
"TransitionService",
"WorklogService",
Expand Down
Loading
Loading