trainwave-cli 0.2.3__tar.gz → 0.2.5__tar.gz

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.
@@ -0,0 +1,165 @@
1
+ Metadata-Version: 2.3
2
+ Name: trainwave-cli
3
+ Version: 0.2.5
4
+ Summary: Trainwave CLI - A command-line interface for managing Trainwave resources
5
+ License: MIT
6
+ Keywords: cli,trainwave,ai,machine-learning
7
+ Author: Johan Backman
8
+ Author-email: johan@trainwave.ai
9
+ Maintainer: Johan Backman
10
+ Maintainer-email: johan@trainwave.ai
11
+ Requires-Python: >=3.10,<4.0
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Requires-Dist: aiofiles (>=24.1.0,<25.0.0)
26
+ Requires-Dist: aiohttp (>=3.10,<4.0)
27
+ Requires-Dist: beaupy (>=3.9.2,<4.0.0)
28
+ Requires-Dist: boto3 (>=1.30)
29
+ Requires-Dist: dacite (>=1.9.2,<2.0.0)
30
+ Requires-Dist: httpx (==0.28.1)
31
+ Requires-Dist: human-readable (>=1.3.4,<2.0.0)
32
+ Requires-Dist: loguru (>=0.7.2,<0.8.0)
33
+ Requires-Dist: pathspec (>=0.12.1,<0.13.0)
34
+ Requires-Dist: pytimeparse (>=1.1.8,<2.0.0)
35
+ Requires-Dist: tabulate (>=0.9.0,<0.10.0)
36
+ Requires-Dist: toml (>=0.10.2,<0.11.0)
37
+ Requires-Dist: tqdm (>=4.66.4,<5.0.0)
38
+ Requires-Dist: typer (>=0.12.5,<0.13.0)
39
+ Requires-Dist: typer-config[all] (>=1.4.0,<2.0.0)
40
+ Requires-Dist: websockets (>=12.0,<13.0)
41
+ Project-URL: Documentation, https://trainwave.ai/docs
42
+ Project-URL: Homepage, https://trainwave.ai
43
+ Description-Content-Type: text/markdown
44
+
45
+ # Trainwave CLI
46
+
47
+ A command-line interface for interacting with Trainwave's machine learning platform. This CLI tool provides functionality for managing training jobs, handling authentication, managing secrets, and configuring your Trainwave environment.
48
+
49
+ ## Features
50
+
51
+ - Job Management: Create, monitor, and manage training jobs
52
+ - Authentication: Secure authentication with Trainwave's platform
53
+ - Secrets Management: Handle sensitive information for your jobs
54
+ - Configuration: Set up and manage your Trainwave environment
55
+
56
+ ## Installation
57
+
58
+ ### Using pip
59
+
60
+ ```bash
61
+ pip install trainwave-cli
62
+ ```
63
+
64
+ ### From Source
65
+
66
+ 1. Clone the repository
67
+ 2. Install using Poetry:
68
+
69
+ ```bash
70
+ poetry install
71
+ ```
72
+
73
+ ## Usage
74
+
75
+ The CLI provides several main commands:
76
+
77
+ ```bash
78
+ wave jobs # Manage training jobs
79
+ wave auth # Authenticate with Trainwave
80
+ wave config # Configure your Trainwave environment
81
+ wave secrets # Manage job secrets
82
+ ```
83
+
84
+ For detailed help on any command:
85
+
86
+ ```bash
87
+ wave --help
88
+ wave <command> --help
89
+ ```
90
+
91
+ ## Development
92
+
93
+ This project uses Poetry for dependency management and packaging. Here's how to set up your development environment:
94
+
95
+ ### Prerequisites
96
+
97
+ - Python 3.10 or higher
98
+ - Poetry
99
+ - Make (for development commands)
100
+
101
+ ### Setting Up Development Environment
102
+
103
+ 1. Clone the repository
104
+ 2. Install development dependencies:
105
+
106
+ ```bash
107
+ make install-dev
108
+ ```
109
+
110
+ ### Development Commands
111
+
112
+ The project includes several Make targets to help with development:
113
+
114
+ - `make install`: Install production dependencies
115
+ - `make install-dev`: Install development dependencies
116
+ - `make clean`: Remove temporary files and build artifacts
117
+ - `make ruff`: Run Ruff linter
118
+ - `make format`: Format code using Black and Ruff
119
+ - `make check`: Run all code quality checks
120
+ - `make test`: Run the test suite
121
+ - `make help`: Show available make commands
122
+
123
+ ### Code Style
124
+
125
+ The project uses:
126
+
127
+ - Ruff for linting
128
+ - Black for code formatting
129
+ - Type hints are required for all functions
130
+
131
+ ### Running Tests
132
+
133
+ ```bash
134
+ make test
135
+ ```
136
+
137
+ Or directly with pytest:
138
+
139
+ ```bash
140
+ pytest tests/
141
+ ```
142
+
143
+ ## Project Structure
144
+
145
+ ```
146
+ trainwave-cli/
147
+ ├── trainwave_cli/ # Main package directory
148
+ ├── tests/ # Test files
149
+ ├── example/ # Example configurations and usage
150
+ ├── pyproject.toml # Project metadata and dependencies
151
+ └── Makefile # Development automation
152
+ ```
153
+
154
+ ## Contributing
155
+
156
+ 1. Fork the repository
157
+ 2. Create a feature branch
158
+ 3. Make your changes
159
+ 4. Run tests and linting: `make check`
160
+ 5. Submit a pull request
161
+
162
+ ## License
163
+
164
+ [License information here]
165
+
@@ -0,0 +1,120 @@
1
+ # Trainwave CLI
2
+
3
+ A command-line interface for interacting with Trainwave's machine learning platform. This CLI tool provides functionality for managing training jobs, handling authentication, managing secrets, and configuring your Trainwave environment.
4
+
5
+ ## Features
6
+
7
+ - Job Management: Create, monitor, and manage training jobs
8
+ - Authentication: Secure authentication with Trainwave's platform
9
+ - Secrets Management: Handle sensitive information for your jobs
10
+ - Configuration: Set up and manage your Trainwave environment
11
+
12
+ ## Installation
13
+
14
+ ### Using pip
15
+
16
+ ```bash
17
+ pip install trainwave-cli
18
+ ```
19
+
20
+ ### From Source
21
+
22
+ 1. Clone the repository
23
+ 2. Install using Poetry:
24
+
25
+ ```bash
26
+ poetry install
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ The CLI provides several main commands:
32
+
33
+ ```bash
34
+ wave jobs # Manage training jobs
35
+ wave auth # Authenticate with Trainwave
36
+ wave config # Configure your Trainwave environment
37
+ wave secrets # Manage job secrets
38
+ ```
39
+
40
+ For detailed help on any command:
41
+
42
+ ```bash
43
+ wave --help
44
+ wave <command> --help
45
+ ```
46
+
47
+ ## Development
48
+
49
+ This project uses Poetry for dependency management and packaging. Here's how to set up your development environment:
50
+
51
+ ### Prerequisites
52
+
53
+ - Python 3.10 or higher
54
+ - Poetry
55
+ - Make (for development commands)
56
+
57
+ ### Setting Up Development Environment
58
+
59
+ 1. Clone the repository
60
+ 2. Install development dependencies:
61
+
62
+ ```bash
63
+ make install-dev
64
+ ```
65
+
66
+ ### Development Commands
67
+
68
+ The project includes several Make targets to help with development:
69
+
70
+ - `make install`: Install production dependencies
71
+ - `make install-dev`: Install development dependencies
72
+ - `make clean`: Remove temporary files and build artifacts
73
+ - `make ruff`: Run Ruff linter
74
+ - `make format`: Format code using Black and Ruff
75
+ - `make check`: Run all code quality checks
76
+ - `make test`: Run the test suite
77
+ - `make help`: Show available make commands
78
+
79
+ ### Code Style
80
+
81
+ The project uses:
82
+
83
+ - Ruff for linting
84
+ - Black for code formatting
85
+ - Type hints are required for all functions
86
+
87
+ ### Running Tests
88
+
89
+ ```bash
90
+ make test
91
+ ```
92
+
93
+ Or directly with pytest:
94
+
95
+ ```bash
96
+ pytest tests/
97
+ ```
98
+
99
+ ## Project Structure
100
+
101
+ ```
102
+ trainwave-cli/
103
+ ├── trainwave_cli/ # Main package directory
104
+ ├── tests/ # Test files
105
+ ├── example/ # Example configurations and usage
106
+ ├── pyproject.toml # Project metadata and dependencies
107
+ └── Makefile # Development automation
108
+ ```
109
+
110
+ ## Contributing
111
+
112
+ 1. Fork the repository
113
+ 2. Create a feature branch
114
+ 3. Make your changes
115
+ 4. Run tests and linting: `make check`
116
+ 5. Submit a pull request
117
+
118
+ ## License
119
+
120
+ [License information here]
@@ -0,0 +1,82 @@
1
+ [tool.poetry]
2
+ name = "trainwave-cli"
3
+ version = "0.2.5"
4
+ description = "Trainwave CLI - A command-line interface for managing Trainwave resources"
5
+ authors = ["Johan Backman <johan@trainwave.ai>"]
6
+ maintainers = ["Johan Backman <johan@trainwave.ai>"]
7
+ readme = "README.md"
8
+ packages = [{ include = "trainwave_cli" }]
9
+ license = "MIT"
10
+ keywords = ["cli", "trainwave", "ai", "machine-learning"]
11
+ classifiers = [
12
+ "Development Status :: 4 - Beta",
13
+ "Environment :: Console",
14
+ "Intended Audience :: Developers",
15
+ "Intended Audience :: Science/Research",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
23
+ "Topic :: Software Development :: Libraries :: Python Modules",
24
+ ]
25
+
26
+ [tool.poetry.urls]
27
+ Homepage = "https://trainwave.ai"
28
+ Documentation = "https://trainwave.ai/docs"
29
+ # Repository = "TBD"
30
+ # Issues = "TBD"
31
+
32
+ [tool.poetry.dependencies]
33
+ aiofiles = "^24.1.0"
34
+ aiohttp = "^3.10"
35
+ beaupy = "^3.9.2"
36
+ boto3 = ">=1.30"
37
+ dacite = "^1.9.2"
38
+ httpx = "0.28.1"
39
+ human-readable = "^1.3.4"
40
+ loguru = "^0.7.2"
41
+ pathspec = "^0.12.1"
42
+ python = "^3.10"
43
+ pytimeparse = "^1.1.8"
44
+ tabulate = "^0.9.0"
45
+ toml = "^0.10.2"
46
+ tqdm = "^4.66.4"
47
+ typer = "^0.12.5"
48
+ typer-config = { extras = ["all"], version = "^1.4.0" }
49
+ websockets = "^12.0"
50
+
51
+ [tool.poetry.group.dev.dependencies]
52
+ freezegun = "^1.5.1"
53
+ ipdb = "^0.13.13"
54
+ ipython = "^8.34.0"
55
+ pytest = "^8.3.5"
56
+ pytest-asyncio = "^0.25.3"
57
+ pytest-cov = "^6.0.0"
58
+ pytest-httpx = "^0.35.0"
59
+ pytest-mock = "^3.14.0"
60
+
61
+ [tool.poetry.scripts]
62
+ wave = "trainwave_cli.main:entrypoint"
63
+
64
+ [build-system]
65
+ requires = ["poetry-core"]
66
+ build-backend = "poetry.core.masonry.api"
67
+
68
+ # Add tool configurations for common development tools
69
+ [tool.black]
70
+ line-length = 88
71
+ target-version = ["py310"]
72
+ include = '\.pyi?$'
73
+
74
+ [tool.isort]
75
+ profile = "black"
76
+ multi_line_output = 3
77
+ line_length = 88
78
+
79
+ [tool.pytest.ini_options]
80
+ minversion = "6.0"
81
+ addopts = "-ra -q --cov=trainwave_cli"
82
+ testpaths = ["tests"]
@@ -14,6 +14,24 @@ from tqdm import tqdm
14
14
  from trainwave_cli.utils import from_dict
15
15
 
16
16
 
17
+ class JobStatus(Enum):
18
+ SUBMIT_CODE = "SUBMIT_CODE"
19
+ LAUNCHING = "LAUNCHING"
20
+ RUNNING = "RUNNING"
21
+ ERROR = "ERROR"
22
+ UPLOADING = "UPLOADING"
23
+ SUCCESS = "SUCCESS"
24
+ USER_PROCESS_FAILED = "USER_PROCESS_FAILED"
25
+ SYSTEM_TERMINATED = "SYSTEM_TERMINATED"
26
+ USER_CANCELLED = "USER_CANCELLED"
27
+
28
+ @classmethod
29
+ def from_str(cls, provider: str) -> "JobStatus | None":
30
+ if provider.upper() not in JobStatus.__members__:
31
+ return None
32
+ return cls(provider.upper())
33
+
34
+
17
35
  @dataclass(frozen=True)
18
36
  class CloudOffer:
19
37
  cpus: int
@@ -35,22 +53,6 @@ class JobConfig:
35
53
  gpu_type: str
36
54
 
37
55
 
38
- @dataclass
39
- class Job:
40
- id: str
41
- rid: str
42
- state: str
43
- s3_url: str
44
- project: str
45
- cloud_offer: CloudOffer
46
- cost_per_hour: float
47
- config: JobConfig
48
- created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
49
- total_cost: int = 0
50
- upload_url: str = ""
51
- url: str | None = None
52
-
53
-
54
56
  @dataclass(frozen=True)
55
57
  class TrainWaveUser:
56
58
  id: str
@@ -65,7 +67,7 @@ class TrainwaveOrganization:
65
67
  id: str
66
68
  rid: str
67
69
  name: str
68
- computed_credit_balance: int
70
+ computed_credit_balance: int = 0
69
71
 
70
72
 
71
73
  @dataclass(frozen=True)
@@ -75,23 +77,39 @@ class TrainwaveProject:
75
77
  name: str
76
78
 
77
79
 
80
+ @dataclass
81
+ class Job:
82
+ id: str
83
+ rid: str
84
+ state: JobStatus
85
+ s3_url: str
86
+ project: TrainwaveProject
87
+ cloud_offer: CloudOffer
88
+ cost_per_hour: float
89
+ config: JobConfig
90
+ created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
91
+ total_cost: int = 0
92
+ upload_url: str = ""
93
+ url: str | None = None
94
+
95
+
78
96
  @dataclass(frozen=True)
79
97
  class Secret:
80
98
  id: str
81
99
  rid: str
82
100
  name: str
83
101
  organization: str
84
- project: str | None
85
102
  digest: str
103
+ project: str | None = None
86
104
  created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
87
105
 
88
106
 
89
107
  @dataclass(frozen=True)
90
108
  class DjangoPagination:
91
109
  count: int
92
- next: str | None
93
- previous: str | None
94
110
  results: list[dict[str, Any]]
111
+ next: str | None = None
112
+ previous: str | None = None
95
113
 
96
114
 
97
115
  class CLIAuthStatus(Enum):
@@ -105,18 +123,6 @@ class CLIConfigSessionStatus(Enum):
105
123
  PENDING = "pending"
106
124
 
107
125
 
108
- class JobStatus(Enum):
109
- LAUNCHING = "LAUNCHING"
110
- RUNNING = "RUNNING"
111
- ERROR = "ERROR"
112
-
113
- @classmethod
114
- def from_str(cls, provider: str) -> "JobStatus | None":
115
- if provider.upper() not in JobStatus.__members__:
116
- return None
117
- return cls(provider.upper())
118
-
119
-
120
126
  class Api:
121
127
  def __init__(
122
128
  self,
@@ -126,6 +132,7 @@ class Api:
126
132
  organization: str = "",
127
133
  ):
128
134
  verify_ssl = "trainwave.dev" not in endpoint
135
+ endpoint = endpoint.rstrip("/")
129
136
  self.client = httpx.AsyncClient(base_url=endpoint, verify=verify_ssl)
130
137
  self.api_key = api_key
131
138
  self.project = project
@@ -134,6 +141,7 @@ class Api:
134
141
  async def request(self, method, path, **kwargs):
135
142
  headers = kwargs.pop("headers", {})
136
143
  headers["X-Api-Key"] = self.api_key
144
+ path = f"/{path.lstrip('/')}"
137
145
  res = await self.client.request(method, path, headers=headers, **kwargs)
138
146
  self._ensure_no_errors(res)
139
147
  return res
@@ -188,12 +196,14 @@ class Api:
188
196
  return CLIAuthStatus.SUCCESS, api_token
189
197
 
190
198
  async def check_api_key(self) -> bool:
191
- res = await self.request("GET", "/api/v1/organizations/")
192
- if res.status_code != HTTPStatus.OK.value:
199
+ try:
200
+ res = await self.request("GET", "/api/v1/organizations/")
201
+ return (
202
+ res.status_code == HTTPStatus.OK.value
203
+ and len(res.json()["results"]) > 0
204
+ )
205
+ except ValueError:
193
206
  return False
194
- if len(res.json()) > 0:
195
- return True
196
- return False
197
207
 
198
208
  async def list_organizations(self) -> list[TrainwaveOrganization]:
199
209
  res = await self.request("GET", "/api/v1/organizations/")
@@ -248,8 +258,12 @@ class Api:
248
258
  return from_dict(Job, res.json())
249
259
 
250
260
  async def job_status(self, job_id: str) -> JobStatus | None:
261
+ job = await self.get_job(job_id)
262
+ return job.state
263
+
264
+ async def get_job(self, job_id: str) -> Job:
251
265
  res = await self.request("GET", f"/api/v1/jobs/{job_id}/")
252
- return JobStatus.from_str(res.json()["state"])
266
+ return from_dict(Job, res.json())
253
267
 
254
268
  async def cancel_job(self, job_id: str) -> None:
255
269
  await self.request("POST", f"/api/v1/jobs/{job_id}/cancel/", json={})
@@ -3,7 +3,6 @@ import webbrowser
3
3
  from typing import Annotated
4
4
 
5
5
  import typer
6
- from loguru import logger
7
6
  from rich.progress import Progress, SpinnerColumn, TextColumn
8
7
 
9
8
  from trainwave_cli.api import Api, CLIAuthStatus
@@ -78,46 +77,45 @@ async def logout() -> None:
78
77
 
79
78
  This will remove the API key from the configuration.
80
79
  """
80
+ config.api_key = None
81
+ config_manager.save()
81
82
  config_manager.delete()
82
- logger.info("Logged out")
83
+ typer.echo("Logged out")
83
84
 
84
85
 
85
86
  @app.command()
86
87
  @async_command
87
88
  @ensure_api_key
88
89
  async def whoami() -> None:
89
- """Get the current user's information."""
90
- api = Api(config.api_key, config.endpoint)
91
- res = await api.get_myself()
92
- typer.echo(res.email)
90
+ """Show the current user's information."""
91
+ api_client = Api(config.api_key, config.endpoint)
92
+ user = await api_client.get_myself()
93
+ typer.echo(user.email)
93
94
 
94
95
 
95
96
  @app.command()
96
97
  @async_command
97
- async def set_token(api_key: str):
98
- """Manually set the API key for Trainwave."""
99
- api = Api(api_key, config.endpoint)
100
- logger.info("Checking API key...")
101
- if await api.check_api_key():
102
- logger.info("API key is valid!")
98
+ async def set_token(api_key: str) -> None:
99
+ """Set the API key for Trainwave."""
100
+ typer.echo("Checking API key...")
101
+ api_client = Api(api_key, config.endpoint)
102
+ if await api_client.check_api_key():
103
103
  config.api_key = api_key
104
104
  config_manager.save()
105
- logger.info("Done!")
105
+ typer.echo("API key is valid!")
106
106
  else:
107
- logger.error("API key is invalid")
107
+ typer.echo("API key is invalid")
108
108
 
109
109
 
110
110
  @app.command()
111
- @async_command
112
- @ensure_api_key
113
- async def token() -> None:
114
- """Print the current API key."""
111
+ def token() -> None:
112
+ """Show the current API key."""
115
113
  typer.echo(config.api_key)
116
114
 
117
115
 
118
116
  @app.command()
119
- @async_command
120
- async def set_endpoint(endpoint: str) -> None:
121
- """Set the endpoint for Trainwave."""
117
+ def set_endpoint(endpoint: str) -> None:
118
+ """Set the API endpoint for Trainwave."""
122
119
  config.endpoint = endpoint
123
120
  config_manager.save()
121
+ typer.echo(f"Endpoint set to {endpoint}")
@@ -12,12 +12,11 @@ import human_readable
12
12
  import pytimeparse
13
13
  import typer
14
14
  import websockets
15
- from dateutil import parser
16
15
  from loguru import logger
17
16
  from tabulate import tabulate
18
17
  from typer_config.decorators import use_toml_config
19
18
 
20
- from trainwave_cli.api import Api
19
+ from trainwave_cli.api import Api, JobStatus
21
20
  from trainwave_cli.config.config import config
22
21
  from trainwave_cli.format_utils import cents_to_dollars_str
23
22
  from trainwave_cli.io import create_tarball
@@ -171,17 +170,15 @@ async def list_jobs(
171
170
  )
172
171
  jobs = await api_client.list_jobs()
173
172
 
174
- headers = ["ID", "NAME", "STATUS", "CREATED", "GPUS", "COST"]
173
+ headers = ["ID", "NAME", "STATUS", "GPUS", "COST", "CREATED"]
175
174
  table = [
176
175
  [
177
176
  j.rid,
178
177
  j.config.name,
179
- j.state,
180
- human_readable.date_time(
181
- datetime.now(timezone.utc) - parser.parse(j.created_at)
182
- ),
178
+ j.state.value,
183
179
  f"{j.config.gpus} ({j.cloud_offer.gpu_type})",
184
180
  f"{cents_to_dollars_str(j.total_cost)} (${j.cost_per_hour}/h)",
181
+ human_readable.date_time(datetime.now(timezone.utc) - j.created_at),
185
182
  ]
186
183
  for j in jobs
187
184
  ]
@@ -222,6 +219,13 @@ async def logs(
222
219
  job_id: str,
223
220
  ) -> None:
224
221
  """Get the logs of a job."""
222
+ api_client = Api(config.api_key, config.endpoint)
223
+ job = await api_client.get_job(job_id)
224
+
225
+ if job.state in (JobStatus.SUBMIT_CODE, JobStatus.LAUNCHING):
226
+ typer.echo(f"Job {job_id} has not started yet.")
227
+ typer.Exit(1)
228
+
225
229
  logger.remove()
226
230
  logger.add(
227
231
  sys.stdout,
@@ -0,0 +1,125 @@
1
+ import builtins
2
+ import sys
3
+ from datetime import datetime, timezone
4
+ from operator import itemgetter
5
+ from typing import Annotated
6
+
7
+ import human_readable
8
+ import typer
9
+ from tabulate import tabulate
10
+ from typer_config.decorators import use_toml_config
11
+
12
+ from trainwave_cli.api import Api, Secret
13
+ from trainwave_cli.config.config import config
14
+ from trainwave_cli.utils import async_command, ensure_api_key
15
+
16
+ app = typer.Typer()
17
+
18
+
19
+ @app.command()
20
+ @async_command
21
+ @use_toml_config(default_value="trainwave.toml")
22
+ @ensure_api_key
23
+ async def list(
24
+ organization: Annotated[str, typer.Option(help="The organization ID or RID")],
25
+ ) -> None:
26
+ """List all secrets."""
27
+ try:
28
+ api_client = Api(config.api_key, config.endpoint)
29
+ secrets = await api_client.list_secrets(organization)
30
+
31
+ project_scoped = [secret for secret in secrets if secret.project]
32
+ org_scoped = [secret for secret in secrets if not secret.project]
33
+ unique: dict[str, tuple[bool, Secret]] = {}
34
+
35
+ for org_secret in org_scoped:
36
+ unique[org_secret.name] = (False, org_secret)
37
+
38
+ for project_secret in project_scoped:
39
+ if project_secret.name in unique:
40
+ unique[project_secret.name] = (True, project_secret)
41
+ else:
42
+ unique[project_secret.name] = (False, project_secret)
43
+
44
+ sorted_secrets = dict(sorted(unique.items(), key=itemgetter(0)))
45
+
46
+ headers = ["ID", "NAME", "SCOPE", "DIGEST", "CREATED"]
47
+ table = [
48
+ [
49
+ secret.rid,
50
+ secret.name if not overridden else f"{secret.name} (*)",
51
+ "PROJECT" if secret.project else "ORG",
52
+ secret.digest[:16],
53
+ human_readable.date_time(
54
+ datetime.now(timezone.utc) - secret.created_at
55
+ ),
56
+ ]
57
+ for _, (overridden, secret) in sorted_secrets.items()
58
+ ]
59
+
60
+ typer.echo(tabulate(table, headers=headers, tablefmt="grid"))
61
+ except Exception as e:
62
+ typer.echo(f"Error: {e}")
63
+ sys.exit(1)
64
+
65
+
66
+ @app.command()
67
+ @async_command
68
+ @use_toml_config(default_value="trainwave.toml")
69
+ @ensure_api_key
70
+ async def set(
71
+ secrets: Annotated[
72
+ builtins.list[str],
73
+ typer.Argument(help="Secrets to set in the format KEY=VALUE"),
74
+ ],
75
+ organization: Annotated[str, typer.Option(help="The organization ID or RID")],
76
+ project: Annotated[str | None, typer.Option(help="The project ID or RID")] = None,
77
+ ) -> None:
78
+ """Set secrets for an organization or project."""
79
+ try:
80
+ # Parse secrets
81
+ secrets_dict = {}
82
+ for secret in secrets:
83
+ if "=" not in secret:
84
+ typer.echo(f"Error: Invalid secret format: {secret}")
85
+ sys.exit(1)
86
+ key, value = secret.split("=", 1)
87
+ secrets_dict[key] = value
88
+
89
+ # Set secrets
90
+ api_client = Api(config.api_key, config.endpoint)
91
+ await api_client.set_secrets(organization, secrets_dict, project)
92
+ typer.echo("Secrets set successfully")
93
+ except Exception as e:
94
+ typer.echo(f"Error: {e}")
95
+ sys.exit(1)
96
+
97
+
98
+ @app.command()
99
+ @async_command
100
+ @use_toml_config(default_value="trainwave.toml")
101
+ @ensure_api_key
102
+ async def unset(
103
+ secrets: Annotated[builtins.list[str], typer.Argument(help="Secrets to unset")],
104
+ organization: Annotated[str, typer.Option(help="The organization ID or RID")],
105
+ project: Annotated[str | None, typer.Option(help="The project ID or RID")] = None,
106
+ ) -> None:
107
+ """Unset secrets for an organization or project."""
108
+ try:
109
+ # Check if secrets exist
110
+ api_client = Api(config.api_key, config.endpoint)
111
+ existing_secrets = await api_client.list_secrets(organization)
112
+ existing_names = {secret.name for secret in existing_secrets}
113
+
114
+ # Check for nonexistent secrets
115
+ nonexistent = [secret for secret in secrets if secret not in existing_names]
116
+ if nonexistent:
117
+ typer.echo(f"Error: Secrets not found: {', '.join(nonexistent)}")
118
+ sys.exit(1)
119
+
120
+ # Unset secrets
121
+ await api_client.unset_secrets(organization, secrets)
122
+ typer.echo("Secrets unset successfully")
123
+ except Exception as e:
124
+ typer.echo(f"Error: {e}")
125
+ sys.exit(1)
@@ -24,9 +24,11 @@ class ConfigManager:
24
24
  def save(self) -> None:
25
25
  if self.config is None:
26
26
  raise ValueError("Config is not initialized")
27
+
27
28
  data = asdict(self.config)
28
29
  with open(self.CONFIG_PATH, "w") as f:
29
30
  toml.dump(data, f)
31
+
30
32
  self.read()
31
33
 
32
34
  def delete(self) -> None:
@@ -35,8 +37,10 @@ class ConfigManager:
35
37
  def read(self) -> None:
36
38
  if not self.CONFIG_PATH.exists():
37
39
  self._setup_config()
40
+
38
41
  with open(self.CONFIG_PATH) as f:
39
42
  data = toml.load(f)
43
+
40
44
  self.config = Config(
41
45
  **{
42
46
  k: v for k, v in data.items() if k in Config.__dataclass_fields__.keys()
@@ -1,9 +1,12 @@
1
1
  import asyncio
2
- from dataclasses import fields, is_dataclass
2
+ from datetime import datetime
3
+ from enum import Enum
3
4
  from functools import wraps
4
5
  from typing import TypeVar
5
6
 
6
7
  import typer
8
+ from dacite import from_dict as dacite_from_dict
9
+ from dacite.config import Config
7
10
 
8
11
  from trainwave_cli.config.config import config
9
12
 
@@ -22,7 +25,24 @@ def async_command(f):
22
25
  def wrapper(*args, **kwargs):
23
26
  if has_running_event_loop():
24
27
  return f(*args, **kwargs)
25
- return asyncio.run(f(*args, **kwargs))
28
+
29
+ try:
30
+ loop = asyncio.new_event_loop()
31
+ asyncio.set_event_loop(loop)
32
+ try:
33
+ return loop.run_until_complete(f(*args, **kwargs))
34
+ finally:
35
+ loop.close()
36
+ except RuntimeError as e:
37
+ if "Event loop is closed" in str(e):
38
+ # Create a new event loop for testing environments
39
+ loop = asyncio.new_event_loop()
40
+ asyncio.set_event_loop(loop)
41
+ try:
42
+ return loop.run_until_complete(f(*args, **kwargs))
43
+ finally:
44
+ loop.close()
45
+ raise
26
46
 
27
47
  return wrapper
28
48
 
@@ -51,12 +71,8 @@ T = TypeVar("T")
51
71
 
52
72
  def from_dict(data_class: type[T], data: dict) -> T:
53
73
  """Recursively constructs a dataclass from a nested dictionary, skipping unmatched fields."""
54
- field_names = {f.name for f in fields(data_class)}
55
- filtered_data = {k: v for k, v in data.items() if k in field_names}
56
-
57
- for key in filtered_data:
58
- field_type = next(f for f in fields(data_class) if f.name == key).type
59
- if is_dataclass(field_type):
60
- filtered_data[key] = from_dict(field_type, filtered_data[key])
61
-
62
- return data_class(**filtered_data)
74
+ return dacite_from_dict(
75
+ data_class,
76
+ data,
77
+ config=Config(cast=[Enum], type_hooks={datetime: datetime.fromisoformat}),
78
+ )
@@ -1,32 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: trainwave-cli
3
- Version: 0.2.3
4
- Summary:
5
- Author: Johan Backman
6
- Author-email: johan@trainwave.ai
7
- Requires-Python: >=3.10,<4.0
8
- Classifier: Programming Language :: Python :: 3
9
- Classifier: Programming Language :: Python :: 3.10
10
- Classifier: Programming Language :: Python :: 3.11
11
- Classifier: Programming Language :: Python :: 3.12
12
- Classifier: Programming Language :: Python :: 3.13
13
- Requires-Dist: aiofiles (>=24.1.0,<25.0.0)
14
- Requires-Dist: aiohttp (>=3.10,<4.0)
15
- Requires-Dist: beaupy (>=3.9.2,<4.0.0)
16
- Requires-Dist: boto3 (>=1.30)
17
- Requires-Dist: httpx (==0.27.0)
18
- Requires-Dist: human-readable (>=1.3.4,<2.0.0)
19
- Requires-Dist: loguru (>=0.7.2,<0.8.0)
20
- Requires-Dist: pathspec (>=0.12.1,<0.13.0)
21
- Requires-Dist: pytimeparse (>=1.1.8,<2.0.0)
22
- Requires-Dist: tabulate (>=0.9.0,<0.10.0)
23
- Requires-Dist: toml (>=0.10.2,<0.11.0)
24
- Requires-Dist: tqdm (>=4.66.4,<5.0.0)
25
- Requires-Dist: typer (>=0.12.5,<0.13.0)
26
- Requires-Dist: typer-config[all] (>=1.4.0,<2.0.0)
27
- Requires-Dist: websockets (>=12.0,<13.0)
28
- Description-Content-Type: text/markdown
29
-
30
- # TrainWave cli
31
-
32
-
@@ -1,2 +0,0 @@
1
- # TrainWave cli
2
-
@@ -1,37 +0,0 @@
1
- [tool.poetry]
2
- name = "trainwave-cli"
3
- version = "0.2.3"
4
- description = ""
5
- authors = ["Johan Backman <johan@trainwave.ai>"]
6
- readme = "README.md"
7
- packages = [{ include = "trainwave_cli" }]
8
-
9
- [tool.poetry.dependencies]
10
- aiofiles = "^24.1.0"
11
- aiohttp = "^3.10"
12
- beaupy = "^3.9.2"
13
- boto3 = ">=1.30"
14
- httpx = "0.27.0"
15
- human-readable = "^1.3.4"
16
- loguru = "^0.7.2"
17
- pathspec = "^0.12.1"
18
- python = "^3.10"
19
- pytimeparse = "^1.1.8"
20
- tabulate = "^0.9.0"
21
- toml = "^0.10.2"
22
- tqdm = "^4.66.4"
23
- typer = "^0.12.5"
24
- typer-config = { extras = ["all"], version = "^1.4.0" }
25
- websockets = "^12.0"
26
-
27
- [tool.poetry.scripts]
28
- wave = "trainwave_cli.main:entrypoint"
29
-
30
- [tool.poetry.group.dev.dependencies]
31
- pytest-asyncio = "^0.23.8"
32
- freezegun = "^1.5.1"
33
- pytest = "^8.3.2"
34
-
35
- [build-system]
36
- requires = ["poetry-core"]
37
- build-backend = "poetry.core.masonry.api"
@@ -1,100 +0,0 @@
1
- import builtins
2
- from datetime import datetime, timezone
3
- from operator import itemgetter
4
- from typing import Annotated
5
-
6
- import human_readable
7
- import typer
8
- from dateutil import parser
9
- from tabulate import tabulate
10
- from typer_config.decorators import use_toml_config
11
-
12
- from trainwave_cli.api import Api, Secret
13
- from trainwave_cli.config.config import config
14
- from trainwave_cli.utils import async_command, ensure_api_key
15
-
16
- app = typer.Typer()
17
-
18
-
19
- @app.command()
20
- @async_command
21
- @use_toml_config(default_value="trainwave.toml")
22
- @ensure_api_key
23
- async def list(
24
- organization: Annotated[str, typer.Option(help="The organization ID or RID")],
25
- ) -> None:
26
- api_client = Api(config.api_key, config.endpoint)
27
- secrets = await api_client.list_secrets(organization)
28
-
29
- project_scoped = [secret for secret in secrets if secret.project]
30
- org_scoped = [secret for secret in secrets if not secret.project]
31
- unique: dict[str, tuple[bool, Secret]] = {}
32
-
33
- for org_secret in org_scoped:
34
- unique[org_secret.name] = (False, org_secret)
35
-
36
- for project_secret in project_scoped:
37
- if project_secret.name in unique:
38
- unique[project_secret.name] = (True, project_secret)
39
- else:
40
- unique[project_secret.name] = (False, project_secret)
41
-
42
- sorted_secrets = dict(sorted(unique.items(), key=itemgetter(0)))
43
-
44
- headers = ["ID", "NAME", "SCOPE", "DIGEST", "CREATED"]
45
- table = [
46
- [
47
- secret.rid,
48
- secret.name if not overridden else f"{secret.name} (*)",
49
- "PROJECT" if secret.project else "ORG",
50
- secret.digest[:16],
51
- human_readable.date_time(
52
- datetime.now(timezone.utc) - parser.parse(secret.created_at)
53
- ),
54
- ]
55
- for (overridden, secret) in sorted_secrets.values()
56
- ]
57
- typer.echo(tabulate(table, headers=headers, tablefmt="simple"))
58
-
59
-
60
- @app.command()
61
- @async_command
62
- @use_toml_config(default_value="trainwave.toml")
63
- @ensure_api_key
64
- async def set(
65
- organization: Annotated[str, typer.Option(help="The organization ID or RID")],
66
- secrets: builtins.list[str],
67
- project: Annotated[str | None, typer.Option(help="Project ID or RID")] = None,
68
- ) -> None:
69
- secret_dict: dict[str, str] = {}
70
-
71
- for secret in secrets:
72
- _KV_PARTS = 2
73
- splitted = secret.split("=")
74
-
75
- # Validate format
76
- if len(splitted) != _KV_PARTS:
77
- typer.echo(
78
- f"Error: Invalid format '{secret}'. Expected format is KEY=VALUE.",
79
- err=True,
80
- )
81
- raise typer.Exit(code=1)
82
-
83
- secret_name, secret_value = splitted
84
- secret_dict[secret_name] = secret_value
85
-
86
- # Now call API and insert
87
- api_client = Api(config.api_key, config.endpoint)
88
- await api_client.set_secrets(organization, secret_dict, project)
89
-
90
-
91
- @app.command()
92
- @async_command
93
- @use_toml_config(default_value="trainwave.toml")
94
- @ensure_api_key
95
- async def unset(
96
- organization: Annotated[str, typer.Option(help="The organization ID or RID")],
97
- secrets: builtins.list[str],
98
- ) -> None:
99
- api_client = Api(config.api_key, config.endpoint)
100
- await api_client.unset_secrets(organization, secrets)