sprout-cli 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sprout/__init__.py +3 -0
- sprout/__main__.py +13 -0
- sprout/cli.py +83 -0
- sprout/commands/__init__.py +1 -0
- sprout/commands/create.py +89 -0
- sprout/commands/ls.py +93 -0
- sprout/commands/path.py +28 -0
- sprout/commands/rm.py +84 -0
- sprout/exceptions.py +12 -0
- sprout/types.py +28 -0
- sprout/utils.py +177 -0
- sprout_cli-0.2.0.dist-info/METADATA +182 -0
- sprout_cli-0.2.0.dist-info/RECORD +16 -0
- sprout_cli-0.2.0.dist-info/WHEEL +4 -0
- sprout_cli-0.2.0.dist-info/entry_points.txt +2 -0
- sprout_cli-0.2.0.dist-info/licenses/LICENSE +21 -0
sprout/__init__.py
ADDED
sprout/__main__.py
ADDED
sprout/cli.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Main CLI interface for sprout."""
|
|
2
|
+
|
|
3
|
+
import typer
|
|
4
|
+
from rich.console import Console
|
|
5
|
+
|
|
6
|
+
from sprout import __version__
|
|
7
|
+
from sprout.commands.create import create_worktree
|
|
8
|
+
from sprout.commands.ls import list_worktrees
|
|
9
|
+
from sprout.commands.path import get_worktree_path
|
|
10
|
+
from sprout.commands.rm import remove_worktree
|
|
11
|
+
from sprout.types import BranchName
|
|
12
|
+
|
|
13
|
+
app = typer.Typer(
|
|
14
|
+
name="sprout",
|
|
15
|
+
help="CLI tool to automate git worktree and Docker Compose development workflows.",
|
|
16
|
+
add_completion=False,
|
|
17
|
+
)
|
|
18
|
+
console = Console()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def version_callback(value: bool) -> None:
|
|
22
|
+
"""Show version and exit."""
|
|
23
|
+
if value:
|
|
24
|
+
console.print(f"sprout version {__version__}")
|
|
25
|
+
raise typer.Exit()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@app.callback()
|
|
29
|
+
def callback(
|
|
30
|
+
version: bool = typer.Option(
|
|
31
|
+
None,
|
|
32
|
+
"--version",
|
|
33
|
+
"-v",
|
|
34
|
+
help="Show version and exit.",
|
|
35
|
+
callback=version_callback,
|
|
36
|
+
is_eager=True,
|
|
37
|
+
),
|
|
38
|
+
) -> None:
|
|
39
|
+
"""sprout - Manage git worktrees with Docker Compose environments."""
|
|
40
|
+
pass
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@app.command()
|
|
44
|
+
def create(
|
|
45
|
+
branch_name: BranchName = typer.Argument(
|
|
46
|
+
...,
|
|
47
|
+
help="Name of the branch to create worktree for",
|
|
48
|
+
),
|
|
49
|
+
) -> None:
|
|
50
|
+
"""Create a new development environment."""
|
|
51
|
+
create_worktree(branch_name)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@app.command()
|
|
55
|
+
def ls() -> None:
|
|
56
|
+
"""List all managed development environments."""
|
|
57
|
+
list_worktrees()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@app.command()
|
|
61
|
+
def rm(
|
|
62
|
+
branch_name: BranchName = typer.Argument(
|
|
63
|
+
...,
|
|
64
|
+
help="Name of the branch to remove",
|
|
65
|
+
),
|
|
66
|
+
) -> None:
|
|
67
|
+
"""Remove a development environment."""
|
|
68
|
+
remove_worktree(branch_name)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@app.command()
|
|
72
|
+
def path(
|
|
73
|
+
branch_name: BranchName = typer.Argument(
|
|
74
|
+
...,
|
|
75
|
+
help="Name of the branch to get path for",
|
|
76
|
+
),
|
|
77
|
+
) -> None:
|
|
78
|
+
"""Get the path of a development environment."""
|
|
79
|
+
get_worktree_path(branch_name)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
if __name__ == "__main__":
|
|
83
|
+
app()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Command implementations for sprout."""
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Implementation of the create command."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Never
|
|
5
|
+
|
|
6
|
+
import typer
|
|
7
|
+
from rich.console import Console
|
|
8
|
+
|
|
9
|
+
from sprout.exceptions import SproutError
|
|
10
|
+
from sprout.types import BranchName
|
|
11
|
+
from sprout.utils import (
|
|
12
|
+
branch_exists,
|
|
13
|
+
ensure_sprout_dir,
|
|
14
|
+
get_git_root,
|
|
15
|
+
is_git_repository,
|
|
16
|
+
parse_env_template,
|
|
17
|
+
run_command,
|
|
18
|
+
worktree_exists,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
console = Console()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def create_worktree(branch_name: BranchName) -> Never:
|
|
25
|
+
"""Create a new worktree with development environment."""
|
|
26
|
+
# Check prerequisites
|
|
27
|
+
if not is_git_repository():
|
|
28
|
+
console.print("[red]Error: Not in a git repository[/red]")
|
|
29
|
+
console.print("Please run this command from the root of a git repository.")
|
|
30
|
+
raise typer.Exit(1)
|
|
31
|
+
|
|
32
|
+
git_root = get_git_root()
|
|
33
|
+
env_example = git_root / ".env.example"
|
|
34
|
+
|
|
35
|
+
if not env_example.exists():
|
|
36
|
+
console.print("[red]Error: .env.example file not found[/red]")
|
|
37
|
+
console.print(f"Expected at: {env_example}")
|
|
38
|
+
raise typer.Exit(1)
|
|
39
|
+
|
|
40
|
+
# Check if worktree already exists
|
|
41
|
+
if worktree_exists(branch_name):
|
|
42
|
+
console.print(f"[red]Error: Worktree for branch '{branch_name}' already exists[/red]")
|
|
43
|
+
raise typer.Exit(1)
|
|
44
|
+
|
|
45
|
+
# Ensure .sprout directory exists
|
|
46
|
+
sprout_dir = ensure_sprout_dir()
|
|
47
|
+
worktree_path = sprout_dir / branch_name
|
|
48
|
+
|
|
49
|
+
# Create the worktree
|
|
50
|
+
console.print(f"Creating worktree for branch [cyan]{branch_name}[/cyan]...")
|
|
51
|
+
|
|
52
|
+
# Check if branch exists, create if it doesn't
|
|
53
|
+
if not branch_exists(branch_name):
|
|
54
|
+
console.print(f"Branch '{branch_name}' doesn't exist. Creating new branch...")
|
|
55
|
+
# Create branch with -b flag
|
|
56
|
+
cmd = ["git", "worktree", "add", "-b", branch_name, str(worktree_path)]
|
|
57
|
+
else:
|
|
58
|
+
cmd = ["git", "worktree", "add", str(worktree_path), branch_name]
|
|
59
|
+
|
|
60
|
+
try:
|
|
61
|
+
run_command(cmd)
|
|
62
|
+
except SproutError as e:
|
|
63
|
+
console.print(f"[red]Error creating worktree: {e}[/red]")
|
|
64
|
+
raise typer.Exit(1) from e
|
|
65
|
+
|
|
66
|
+
# Generate .env file
|
|
67
|
+
console.print("Generating .env file...")
|
|
68
|
+
try:
|
|
69
|
+
env_content = parse_env_template(env_example)
|
|
70
|
+
env_file = worktree_path / ".env"
|
|
71
|
+
env_file.write_text(env_content)
|
|
72
|
+
except SproutError as e:
|
|
73
|
+
console.print(f"[red]Error generating .env file: {e}[/red]")
|
|
74
|
+
# Clean up worktree on failure
|
|
75
|
+
run_command(["git", "worktree", "remove", str(worktree_path)], check=False)
|
|
76
|
+
raise typer.Exit(1) from e
|
|
77
|
+
except KeyboardInterrupt:
|
|
78
|
+
console.print("\n[yellow]Cancelled by user[/yellow]")
|
|
79
|
+
# Clean up worktree on cancellation
|
|
80
|
+
run_command(["git", "worktree", "remove", str(worktree_path)], check=False)
|
|
81
|
+
raise typer.Exit(130) from None
|
|
82
|
+
|
|
83
|
+
# Success message
|
|
84
|
+
console.print(f"\n[green]✅ Workspace '{branch_name}' created successfully![/green]\n")
|
|
85
|
+
console.print("Navigate to your new environment with:")
|
|
86
|
+
console.print(f" [cyan]cd {worktree_path.relative_to(Path.cwd())}[/cyan]")
|
|
87
|
+
|
|
88
|
+
# Exit successfully
|
|
89
|
+
raise typer.Exit(0)
|
sprout/commands/ls.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Implementation of the ls command."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import typer
|
|
7
|
+
from rich.console import Console
|
|
8
|
+
from rich.table import Table
|
|
9
|
+
|
|
10
|
+
from sprout.exceptions import SproutError
|
|
11
|
+
from sprout.types import WorktreeInfo
|
|
12
|
+
from sprout.utils import get_sprout_dir, is_git_repository, run_command
|
|
13
|
+
|
|
14
|
+
console = Console()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def list_worktrees() -> None:
|
|
18
|
+
"""List all managed development environments."""
|
|
19
|
+
if not is_git_repository():
|
|
20
|
+
console.print("[red]Error: Not in a git repository[/red]")
|
|
21
|
+
raise typer.Exit(1)
|
|
22
|
+
|
|
23
|
+
sprout_dir = get_sprout_dir()
|
|
24
|
+
|
|
25
|
+
# Get worktree list from git
|
|
26
|
+
try:
|
|
27
|
+
result = run_command(["git", "worktree", "list", "--porcelain"])
|
|
28
|
+
except SproutError as e:
|
|
29
|
+
console.print(f"[red]Error listing worktrees: {e}[/red]")
|
|
30
|
+
raise typer.Exit(1) from e
|
|
31
|
+
|
|
32
|
+
# Parse worktree output
|
|
33
|
+
worktrees: list[WorktreeInfo] = []
|
|
34
|
+
current_worktree: WorktreeInfo = {}
|
|
35
|
+
|
|
36
|
+
for line in result.stdout.strip().split("\n"):
|
|
37
|
+
if not line:
|
|
38
|
+
if current_worktree:
|
|
39
|
+
worktrees.append(current_worktree)
|
|
40
|
+
current_worktree = {}
|
|
41
|
+
continue
|
|
42
|
+
|
|
43
|
+
if line.startswith("worktree "):
|
|
44
|
+
current_worktree["path"] = Path(line[9:])
|
|
45
|
+
elif line.startswith("branch "):
|
|
46
|
+
current_worktree["branch"] = line[7:]
|
|
47
|
+
elif line.startswith("HEAD "):
|
|
48
|
+
current_worktree["head"] = line[5:]
|
|
49
|
+
|
|
50
|
+
if current_worktree:
|
|
51
|
+
worktrees.append(current_worktree)
|
|
52
|
+
|
|
53
|
+
# Filter for sprout-managed worktrees
|
|
54
|
+
sprout_worktrees: list[WorktreeInfo] = []
|
|
55
|
+
current_path = Path.cwd().resolve()
|
|
56
|
+
|
|
57
|
+
for wt in worktrees:
|
|
58
|
+
wt_path = wt["path"].resolve()
|
|
59
|
+
if wt_path.parent == sprout_dir:
|
|
60
|
+
# Check if we're currently in this worktree
|
|
61
|
+
wt["is_current"] = current_path == wt_path or current_path.is_relative_to(wt_path)
|
|
62
|
+
|
|
63
|
+
# Get last modified time
|
|
64
|
+
if wt_path.exists():
|
|
65
|
+
stat = wt_path.stat()
|
|
66
|
+
wt["modified"] = datetime.fromtimestamp(stat.st_mtime)
|
|
67
|
+
else:
|
|
68
|
+
wt["modified"] = None
|
|
69
|
+
|
|
70
|
+
sprout_worktrees.append(wt)
|
|
71
|
+
|
|
72
|
+
if not sprout_worktrees:
|
|
73
|
+
console.print("[yellow]No sprout-managed worktrees found.[/yellow]")
|
|
74
|
+
console.print("Use 'sprout create <branch-name>' to create one.")
|
|
75
|
+
return None
|
|
76
|
+
|
|
77
|
+
# Create table
|
|
78
|
+
table = Table(title="Sprout Worktrees", show_lines=True)
|
|
79
|
+
table.add_column("Branch", style="cyan", no_wrap=True)
|
|
80
|
+
table.add_column("Path", style="blue")
|
|
81
|
+
table.add_column("Status", style="green")
|
|
82
|
+
table.add_column("Last Modified", style="yellow")
|
|
83
|
+
|
|
84
|
+
for wt in sprout_worktrees:
|
|
85
|
+
branch = wt.get("branch", wt.get("head", "detached"))
|
|
86
|
+
path = str(wt["path"].relative_to(Path.cwd()))
|
|
87
|
+
status = "[green]● current[/green]" if wt["is_current"] else ""
|
|
88
|
+
modified_dt = wt.get("modified")
|
|
89
|
+
modified = modified_dt.strftime("%Y-%m-%d %H:%M") if modified_dt else "N/A"
|
|
90
|
+
|
|
91
|
+
table.add_row(branch, path, status, modified)
|
|
92
|
+
|
|
93
|
+
console.print(table)
|
sprout/commands/path.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Implementation of the path command."""
|
|
2
|
+
|
|
3
|
+
from typing import Never, TextIO
|
|
4
|
+
|
|
5
|
+
import typer
|
|
6
|
+
|
|
7
|
+
from sprout.types import BranchName
|
|
8
|
+
from sprout.utils import get_sprout_dir, is_git_repository, worktree_exists
|
|
9
|
+
|
|
10
|
+
console: TextIO = typer.get_text_stream("stdout")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def get_worktree_path(branch_name: BranchName) -> Never:
|
|
14
|
+
"""Get the path of a development environment."""
|
|
15
|
+
if not is_git_repository():
|
|
16
|
+
typer.echo("Error: Not in a git repository", err=True)
|
|
17
|
+
raise typer.Exit(1)
|
|
18
|
+
|
|
19
|
+
# Check if worktree exists
|
|
20
|
+
if not worktree_exists(branch_name):
|
|
21
|
+
typer.echo(f"Error: Worktree for branch '{branch_name}' does not exist", err=True)
|
|
22
|
+
raise typer.Exit(1)
|
|
23
|
+
|
|
24
|
+
worktree_path = get_sprout_dir() / branch_name
|
|
25
|
+
|
|
26
|
+
# Output only the path, no extra formatting
|
|
27
|
+
print(str(worktree_path))
|
|
28
|
+
raise typer.Exit(0)
|
sprout/commands/rm.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Implementation of the rm command."""
|
|
2
|
+
|
|
3
|
+
import typer
|
|
4
|
+
from rich.console import Console
|
|
5
|
+
|
|
6
|
+
from sprout.exceptions import SproutError
|
|
7
|
+
from sprout.types import BranchName
|
|
8
|
+
from sprout.utils import (
|
|
9
|
+
get_sprout_dir,
|
|
10
|
+
is_git_repository,
|
|
11
|
+
run_command,
|
|
12
|
+
worktree_exists,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
console = Console()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def remove_worktree(branch_name: BranchName) -> None:
|
|
19
|
+
"""Remove a development environment."""
|
|
20
|
+
if not is_git_repository():
|
|
21
|
+
console.print("[red]Error: Not in a git repository[/red]")
|
|
22
|
+
raise typer.Exit(1)
|
|
23
|
+
|
|
24
|
+
# Check if worktree exists
|
|
25
|
+
if not worktree_exists(branch_name):
|
|
26
|
+
console.print(f"[red]Error: Worktree for branch '{branch_name}' does not exist[/red]")
|
|
27
|
+
raise typer.Exit(1)
|
|
28
|
+
|
|
29
|
+
worktree_path = get_sprout_dir() / branch_name
|
|
30
|
+
|
|
31
|
+
# Confirm removal
|
|
32
|
+
if not typer.confirm(
|
|
33
|
+
f"Are you sure you want to remove the worktree for branch '{branch_name}'?"
|
|
34
|
+
):
|
|
35
|
+
console.print("[yellow]Cancelled[/yellow]")
|
|
36
|
+
raise typer.Exit(0)
|
|
37
|
+
|
|
38
|
+
# Remove worktree
|
|
39
|
+
console.print(f"Removing worktree for branch [cyan]{branch_name}[/cyan]...")
|
|
40
|
+
try:
|
|
41
|
+
result = run_command(["git", "worktree", "remove", str(worktree_path)], check=False)
|
|
42
|
+
if result.returncode != 0:
|
|
43
|
+
# Try force removal if normal removal fails
|
|
44
|
+
result = run_command(
|
|
45
|
+
["git", "worktree", "remove", "--force", str(worktree_path)], check=False
|
|
46
|
+
)
|
|
47
|
+
if result.returncode != 0:
|
|
48
|
+
console.print(f"[red]Error removing worktree: {result.stderr}[/red]")
|
|
49
|
+
raise typer.Exit(1)
|
|
50
|
+
console.print("[green]✅ Worktree removed successfully[/green]")
|
|
51
|
+
except SproutError as e:
|
|
52
|
+
console.print(f"[red]Error removing worktree: {e}[/red]")
|
|
53
|
+
raise typer.Exit(1) from e
|
|
54
|
+
|
|
55
|
+
# Ask about branch deletion
|
|
56
|
+
try:
|
|
57
|
+
if typer.confirm(f"Do you also want to delete the git branch '{branch_name}'?"):
|
|
58
|
+
try:
|
|
59
|
+
# Try normal deletion first
|
|
60
|
+
result = run_command(["git", "branch", "-d", branch_name], check=False)
|
|
61
|
+
if result.returncode != 0:
|
|
62
|
+
# If normal deletion fails, show the error and ask about force delete
|
|
63
|
+
console.print(f"[yellow]Warning: {result.stderr.strip()}[/yellow]")
|
|
64
|
+
if typer.confirm("Force delete the branch?"):
|
|
65
|
+
run_command(["git", "branch", "-D", branch_name])
|
|
66
|
+
console.print("[green]✅ Branch deleted successfully[/green]")
|
|
67
|
+
else:
|
|
68
|
+
console.print("[yellow]Branch deletion cancelled[/yellow]")
|
|
69
|
+
else:
|
|
70
|
+
console.print("[green]✅ Branch deleted successfully[/green]")
|
|
71
|
+
except SproutError as e:
|
|
72
|
+
console.print(f"[red]Error deleting branch: {e}[/red]")
|
|
73
|
+
console.print(
|
|
74
|
+
"[yellow]Note: The worktree has been removed, "
|
|
75
|
+
"but the branch still exists[/yellow]"
|
|
76
|
+
)
|
|
77
|
+
except Exception as e:
|
|
78
|
+
# Catch any exception during the confirmation prompt
|
|
79
|
+
console.print(f"[red]Error during branch deletion prompt: {e}[/red]")
|
|
80
|
+
# Don't fail the whole command if branch deletion has issues
|
|
81
|
+
pass
|
|
82
|
+
|
|
83
|
+
# Exit successfully - return instead of raising Exit for proper testing
|
|
84
|
+
return
|
sprout/exceptions.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Custom exceptions for sprout."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class SproutError(Exception):
|
|
7
|
+
"""Base exception for sprout errors."""
|
|
8
|
+
|
|
9
|
+
def __init__(self, message: str, *args: Any) -> None:
|
|
10
|
+
"""Initialize the exception with a message."""
|
|
11
|
+
super().__init__(message, *args)
|
|
12
|
+
self.message = message
|
sprout/types.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Type definitions for sprout."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import TypeAlias, TypedDict
|
|
6
|
+
|
|
7
|
+
# Type aliases
|
|
8
|
+
BranchName: TypeAlias = str
|
|
9
|
+
WorktreePath: TypeAlias = Path
|
|
10
|
+
EnvContent: TypeAlias = str
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class WorktreeInfo(TypedDict, total=False):
|
|
14
|
+
"""Information about a git worktree."""
|
|
15
|
+
|
|
16
|
+
path: Path
|
|
17
|
+
branch: str | None
|
|
18
|
+
head: str | None
|
|
19
|
+
is_current: bool
|
|
20
|
+
modified: datetime | None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class GitWorktreeOutput(TypedDict):
|
|
24
|
+
"""Parsed output from git worktree list."""
|
|
25
|
+
|
|
26
|
+
path: Path
|
|
27
|
+
branch: str | None
|
|
28
|
+
head: str | None
|
sprout/utils.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""Common utilities for sprout."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import random
|
|
5
|
+
import re
|
|
6
|
+
import socket
|
|
7
|
+
import subprocess
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import TypeAlias
|
|
10
|
+
|
|
11
|
+
from rich.console import Console
|
|
12
|
+
|
|
13
|
+
from sprout.exceptions import SproutError
|
|
14
|
+
from sprout.types import BranchName
|
|
15
|
+
|
|
16
|
+
# Type aliases
|
|
17
|
+
PortNumber: TypeAlias = int
|
|
18
|
+
PortSet: TypeAlias = set[PortNumber]
|
|
19
|
+
|
|
20
|
+
console = Console()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def is_git_repository() -> bool:
|
|
24
|
+
"""Check if current directory is inside a git repository."""
|
|
25
|
+
try:
|
|
26
|
+
result = subprocess.run(
|
|
27
|
+
["git", "rev-parse", "--git-dir"],
|
|
28
|
+
capture_output=True,
|
|
29
|
+
text=True,
|
|
30
|
+
check=False,
|
|
31
|
+
)
|
|
32
|
+
return result.returncode == 0
|
|
33
|
+
except (subprocess.SubprocessError, FileNotFoundError):
|
|
34
|
+
return False
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def get_git_root() -> Path:
|
|
38
|
+
"""Get the root directory of the git repository."""
|
|
39
|
+
if not is_git_repository():
|
|
40
|
+
raise SproutError("Not in a git repository")
|
|
41
|
+
|
|
42
|
+
result = subprocess.run(
|
|
43
|
+
["git", "rev-parse", "--show-toplevel"],
|
|
44
|
+
capture_output=True,
|
|
45
|
+
text=True,
|
|
46
|
+
check=True,
|
|
47
|
+
)
|
|
48
|
+
return Path(result.stdout.strip())
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def run_command(cmd: list[str], check: bool = True) -> subprocess.CompletedProcess[str]:
|
|
52
|
+
"""Run a command and return the result."""
|
|
53
|
+
try:
|
|
54
|
+
return subprocess.run(
|
|
55
|
+
cmd,
|
|
56
|
+
capture_output=True,
|
|
57
|
+
text=True,
|
|
58
|
+
check=check,
|
|
59
|
+
)
|
|
60
|
+
except subprocess.CalledProcessError as e:
|
|
61
|
+
raise SproutError(f"Command failed: {' '.join(cmd)}\n{e.stderr}") from e
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def get_sprout_dir() -> Path:
|
|
65
|
+
"""Get the .sprout directory path."""
|
|
66
|
+
return get_git_root() / ".sprout"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def ensure_sprout_dir() -> Path:
|
|
70
|
+
"""Ensure .sprout directory exists and return its path."""
|
|
71
|
+
sprout_dir = get_sprout_dir()
|
|
72
|
+
sprout_dir.mkdir(exist_ok=True)
|
|
73
|
+
return sprout_dir
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def get_used_ports() -> PortSet:
|
|
77
|
+
"""Get all ports currently used by sprout worktrees."""
|
|
78
|
+
used_ports: PortSet = set()
|
|
79
|
+
sprout_dir = get_sprout_dir()
|
|
80
|
+
|
|
81
|
+
if not sprout_dir.exists():
|
|
82
|
+
return used_ports
|
|
83
|
+
|
|
84
|
+
# Scan all .env files in .sprout/*/
|
|
85
|
+
for env_file in sprout_dir.glob("*/.env"):
|
|
86
|
+
if env_file.is_file():
|
|
87
|
+
try:
|
|
88
|
+
content = env_file.read_text()
|
|
89
|
+
# Find all port assignments (e.g., PORT=8080)
|
|
90
|
+
port_matches = re.findall(r"=(\d{4,5})\b", content)
|
|
91
|
+
for port_str in port_matches:
|
|
92
|
+
port = int(port_str)
|
|
93
|
+
if 1024 <= port <= 65535:
|
|
94
|
+
used_ports.add(port)
|
|
95
|
+
except (OSError, ValueError):
|
|
96
|
+
continue
|
|
97
|
+
|
|
98
|
+
return used_ports
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def is_port_available(port: PortNumber) -> bool:
|
|
102
|
+
"""Check if a port is available for binding."""
|
|
103
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
|
104
|
+
try:
|
|
105
|
+
sock.bind(("127.0.0.1", port))
|
|
106
|
+
return True
|
|
107
|
+
except OSError:
|
|
108
|
+
return False
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def find_available_port() -> PortNumber:
|
|
112
|
+
"""Find an available port that's not used by sprout or system."""
|
|
113
|
+
used_ports = get_used_ports()
|
|
114
|
+
max_attempts = 1000
|
|
115
|
+
|
|
116
|
+
for _ in range(max_attempts):
|
|
117
|
+
# Random port between 1024 and 65535
|
|
118
|
+
port = random.randint(1024, 65535)
|
|
119
|
+
|
|
120
|
+
if port not in used_ports and is_port_available(port):
|
|
121
|
+
return port
|
|
122
|
+
|
|
123
|
+
raise SproutError("Could not find an available port after 1000 attempts")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def parse_env_template(template_path: Path) -> str:
|
|
127
|
+
"""Parse .env.example template and process placeholders."""
|
|
128
|
+
if not template_path.exists():
|
|
129
|
+
raise SproutError(f".env.example file not found at {template_path}")
|
|
130
|
+
|
|
131
|
+
try:
|
|
132
|
+
content = template_path.read_text()
|
|
133
|
+
except OSError as e:
|
|
134
|
+
raise SproutError(f"Failed to read .env.example: {e}") from e
|
|
135
|
+
|
|
136
|
+
lines: list[str] = []
|
|
137
|
+
# Track used ports within this file to avoid duplicates
|
|
138
|
+
file_ports: PortSet = set()
|
|
139
|
+
|
|
140
|
+
for line in content.splitlines():
|
|
141
|
+
# Process {{ auto_port() }} placeholders
|
|
142
|
+
def replace_auto_port(match: re.Match[str]) -> str:
|
|
143
|
+
port = find_available_port()
|
|
144
|
+
while port in file_ports:
|
|
145
|
+
port = find_available_port()
|
|
146
|
+
file_ports.add(port)
|
|
147
|
+
return str(port)
|
|
148
|
+
|
|
149
|
+
line = re.sub(r"{{\s*auto_port\(\)\s*}}", replace_auto_port, line)
|
|
150
|
+
|
|
151
|
+
# Process {{ VARIABLE }} placeholders
|
|
152
|
+
def replace_variable(match: re.Match[str]) -> str:
|
|
153
|
+
var_name = match.group(1).strip()
|
|
154
|
+
# Check environment variable first
|
|
155
|
+
value = os.environ.get(var_name)
|
|
156
|
+
if value is None:
|
|
157
|
+
# Prompt user for value
|
|
158
|
+
value = console.input(f"Enter a value for '{var_name}': ")
|
|
159
|
+
return value
|
|
160
|
+
|
|
161
|
+
line = re.sub(r"{{\s*([^}]+)\s*}}", replace_variable, line)
|
|
162
|
+
|
|
163
|
+
lines.append(line)
|
|
164
|
+
|
|
165
|
+
return "\n".join(lines)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def worktree_exists(branch_name: BranchName) -> bool:
|
|
169
|
+
"""Check if a worktree already exists for the given branch."""
|
|
170
|
+
worktree_path = get_sprout_dir() / branch_name
|
|
171
|
+
return worktree_path.exists()
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def branch_exists(branch_name: BranchName) -> bool:
|
|
175
|
+
"""Check if a git branch exists."""
|
|
176
|
+
result = run_command(["git", "rev-parse", "--verify", f"refs/heads/{branch_name}"], check=False)
|
|
177
|
+
return result.returncode == 0
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sprout-cli
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: CLI tool to automate git worktree and Docker Compose development workflows
|
|
5
|
+
Author: SecDevLab Inc.
|
|
6
|
+
License: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Topic :: Software Development :: Build Tools
|
|
16
|
+
Classifier: Topic :: Software Development :: Version Control :: Git
|
|
17
|
+
Requires-Python: >=3.11
|
|
18
|
+
Requires-Dist: rich>=13.0.0
|
|
19
|
+
Requires-Dist: typer>=0.9.0
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: mypy>=1.5.0; extra == 'dev'
|
|
22
|
+
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
|
|
23
|
+
Requires-Dist: pytest-mock>=3.0; extra == 'dev'
|
|
24
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
25
|
+
Requires-Dist: ruff>=0.1.0; extra == 'dev'
|
|
26
|
+
Requires-Dist: types-setuptools>=68.0; extra == 'dev'
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# sprout
|
|
30
|
+
|
|
31
|
+
A CLI tool to automate git worktree and Docker Compose development workflows.
|
|
32
|
+
|
|
33
|
+
## Features
|
|
34
|
+
|
|
35
|
+
- 🌱 Create isolated development environments using git worktrees
|
|
36
|
+
- 🔧 Automatic `.env` file generation from templates
|
|
37
|
+
- 🚢 Smart port allocation to avoid conflicts
|
|
38
|
+
- 📁 Centralized worktree management in `.sprout/` directory
|
|
39
|
+
- 🎨 Beautiful CLI interface with colors and tables
|
|
40
|
+
|
|
41
|
+
## Installation
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install sprout
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
For development:
|
|
48
|
+
```bash
|
|
49
|
+
# Clone the repository
|
|
50
|
+
git clone https://github.com/SecDev-Lab/sprout.git
|
|
51
|
+
cd sprout
|
|
52
|
+
|
|
53
|
+
# Install in development mode
|
|
54
|
+
pip install -e ".[dev]"
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Quick Start
|
|
58
|
+
|
|
59
|
+
1. Create a `.env.example` template in your project root:
|
|
60
|
+
```env
|
|
61
|
+
# API Configuration
|
|
62
|
+
API_KEY={{ API_KEY }}
|
|
63
|
+
API_PORT={{ auto_port() }}
|
|
64
|
+
|
|
65
|
+
# Database Configuration
|
|
66
|
+
DB_HOST=localhost
|
|
67
|
+
DB_PORT={{ auto_port() }}
|
|
68
|
+
|
|
69
|
+
# Example: Docker Compose variables (preserved as-is)
|
|
70
|
+
# sprout will NOT process ${...} syntax - it's passed through unchanged
|
|
71
|
+
# DB_NAME=${DB_NAME}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
2. Create a new development environment:
|
|
75
|
+
```bash
|
|
76
|
+
sprout create feature-branch
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
3. Navigate to your new environment:
|
|
80
|
+
```bash
|
|
81
|
+
cd $(sprout path feature-branch)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
4. Start your services:
|
|
85
|
+
```bash
|
|
86
|
+
docker compose up -d
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Commands
|
|
90
|
+
|
|
91
|
+
### `sprout create <branch-name>`
|
|
92
|
+
Create a new development environment with automated setup.
|
|
93
|
+
|
|
94
|
+
### `sprout ls`
|
|
95
|
+
List all managed development environments with their status.
|
|
96
|
+
|
|
97
|
+
### `sprout rm <branch-name>`
|
|
98
|
+
Remove a development environment (with confirmation prompts).
|
|
99
|
+
|
|
100
|
+
### `sprout path <branch-name>`
|
|
101
|
+
Get the filesystem path of a development environment.
|
|
102
|
+
|
|
103
|
+
### `sprout --version`
|
|
104
|
+
Show the version of sprout.
|
|
105
|
+
|
|
106
|
+
## Template Syntax
|
|
107
|
+
|
|
108
|
+
sprout supports two types of placeholders in `.env.example`:
|
|
109
|
+
|
|
110
|
+
1. **Variable Placeholders**: `{{ VARIABLE_NAME }}`
|
|
111
|
+
- **First**: Checks if the variable exists in your environment (e.g., `export API_KEY=xxx`)
|
|
112
|
+
- **Then**: If not found in environment, prompts for user input
|
|
113
|
+
- Example: `{{ API_KEY }}` will use `$API_KEY` if set, otherwise asks you to enter it
|
|
114
|
+
|
|
115
|
+
2. **Auto Port Assignment**: `{{ auto_port() }}`
|
|
116
|
+
- Automatically assigns available ports
|
|
117
|
+
- Avoids conflicts with other sprout environments
|
|
118
|
+
- Checks system port availability
|
|
119
|
+
|
|
120
|
+
3. **Docker Compose Syntax (Preserved)**: `${VARIABLE}`
|
|
121
|
+
- NOT processed by sprout - passed through as-is
|
|
122
|
+
- Useful for Docker Compose variable substitution
|
|
123
|
+
- Example: `${DB_NAME:-default}` remains unchanged in generated `.env`
|
|
124
|
+
|
|
125
|
+
### Environment Variable Resolution Example
|
|
126
|
+
|
|
127
|
+
```bash
|
|
128
|
+
# Set environment variable
|
|
129
|
+
export API_KEY="my-secret-key"
|
|
130
|
+
|
|
131
|
+
# Create sprout environment - API_KEY will be automatically used
|
|
132
|
+
sprout create feature-branch
|
|
133
|
+
# → API_KEY in .env will be set to "my-secret-key" without prompting
|
|
134
|
+
|
|
135
|
+
# For unset variables, sprout will prompt
|
|
136
|
+
sprout create another-branch
|
|
137
|
+
# → Enter a value for 'DATABASE_URL': [user input required]
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## Documentation
|
|
141
|
+
|
|
142
|
+
- [Architecture Overview](docs/sprout-cli/overview.md) - Design philosophy, architecture, and implementation details
|
|
143
|
+
- [Detailed Usage Guide](docs/sprout-cli/usage.md) - Comprehensive usage examples and troubleshooting
|
|
144
|
+
|
|
145
|
+
## Development
|
|
146
|
+
|
|
147
|
+
### Setup
|
|
148
|
+
```bash
|
|
149
|
+
# Install development dependencies
|
|
150
|
+
make setup
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### Testing
|
|
154
|
+
```bash
|
|
155
|
+
# Run tests
|
|
156
|
+
make test
|
|
157
|
+
|
|
158
|
+
# Run tests with coverage
|
|
159
|
+
make test-cov
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
### Code Quality
|
|
163
|
+
```bash
|
|
164
|
+
# Run linter
|
|
165
|
+
make lint
|
|
166
|
+
|
|
167
|
+
# Format code
|
|
168
|
+
make format
|
|
169
|
+
|
|
170
|
+
# Run type checking
|
|
171
|
+
make typecheck
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
## Requirements
|
|
175
|
+
|
|
176
|
+
- Python 3.11+
|
|
177
|
+
- Git
|
|
178
|
+
- Docker Compose (optional, for Docker-based workflows)
|
|
179
|
+
|
|
180
|
+
## License
|
|
181
|
+
|
|
182
|
+
See LICENSE file.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
sprout/__init__.py,sha256=V8j_TQkzXee4z5xpA2Df1Ftxg7_nHaX9ziEIDvh9My8,114
|
|
2
|
+
sprout/__main__.py,sha256=EmC6MLtl-OTnx1BNUe9QuWLaDrK1mWNAp8JvyYoJNKE,203
|
|
3
|
+
sprout/cli.py,sha256=YfTeMqWvAIjUCc5KWV0FBk3wO30K7qgCL4Fsw2y1MoM,1869
|
|
4
|
+
sprout/exceptions.py,sha256=eqF5Lu5kGqKG8TQgJOxHrbUoNdN5NhdM08ZFL77g3-w,322
|
|
5
|
+
sprout/types.py,sha256=5r5FnaKELADni_ERN_ssle71QBwsjWgHO0abSLn0qx0,581
|
|
6
|
+
sprout/utils.py,sha256=XTebUx-_w4No4vuT_mPweLDYGgGiQ_JsgglKkdJ0fdg,5296
|
|
7
|
+
sprout/commands/__init__.py,sha256=79j9h82iK-jDI0RE7N1v4qaqG-HWBMTBn32BauSKxDk,42
|
|
8
|
+
sprout/commands/create.py,sha256=CK6fQXipQq_-BN3rBw-fIJkcQ-dKTPnnd6gllbVs3V4,3044
|
|
9
|
+
sprout/commands/ls.py,sha256=M9iDln9weYrHI_3k4AXrPLUq1tufYIfxiime68jb6vU,3083
|
|
10
|
+
sprout/commands/path.py,sha256=beZmRegtlOwgg2EzijXh6SxdbrKY69PtQ6CpXJeNV_U,836
|
|
11
|
+
sprout/commands/rm.py,sha256=736YuIP6qH6KRXO2Ls6Cl3V-68CyQXOQKz5Tg_6IwM8,3358
|
|
12
|
+
sprout_cli-0.2.0.dist-info/METADATA,sha256=U3gmR5pPcST7yNwuQJFf04_g6LnXsFFfcHKb-yZmNds,4578
|
|
13
|
+
sprout_cli-0.2.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
14
|
+
sprout_cli-0.2.0.dist-info/entry_points.txt,sha256=DZX8C87ZujVYIx_3a7A_WtMYQiilbRuDfGj8sN2Mw9E,48
|
|
15
|
+
sprout_cli-0.2.0.dist-info/licenses/LICENSE,sha256=pj5IbIXKP9QvvhNPeVMwApeWIkW26t9A9BwgulzFtkI,1066
|
|
16
|
+
sprout_cli-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 SecDevLab
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|