Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
217 lines (193 loc) · 6.89 KB
/
Copy pathcli.py
File metadata and controls
217 lines (193 loc) · 6.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
"""Command-line entrypoint for the `dlthub-init` CLI."""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
from . import strings, telemetry
from .config import DISTRIBUTION_NAME
from .display import console, print_command_failed, print_header, print_next_steps, print_sync_failed, substep
from .dlthub import (
InitMode,
InitOptions,
build_env,
build_steps,
find_dlthub,
get_dlt_version,
has_workspace,
raise_on_failure,
run_step,
)
from .errors import DlthubCommandError, UvError, WorkspaceError
from .uv import find_uv, run_uv_sync
def _ensure_utf8_io_on_windows() -> None:
if sys.platform != "win32":
return
for stream in (sys.stdout, sys.stderr):
reconfigure = getattr(stream, "reconfigure", None)
8000
if reconfigure is None:
continue
try:
reconfigure(encoding="utf-8")
except (OSError, ValueError):
pass
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog=DISTRIBUTION_NAME,
description=(
"Create a dltHub workspace with `dlthub init`, set up your coding agent and install the"
" dependencies. In an existing project, dlthub lists the changes and asks first."
),
)
parser.add_argument(
"project_dir",
nargs="?",
default=None,
help="Directory to initialize, created when missing. Defaults to the current directory.",
)
parser.add_argument(
"--name",
default=None,
help="Workspace name. Defaults to the directory name.",
)
existing = parser.add_mutually_exclusive_group()
existing.add_argument(
"--overwrite",
action="store_true",
help=(
"Overwrite the existing dependency file, .gitignore and .dlt/.workspace instead of merging"
" into them. The settings files are never overwritten."
),
)
existing.add_argument("--force", dest="overwrite", action="store_true", help=argparse.SUPPRESS)
existing.add_argument(
"--skip",
action="store_true",
help="Keep existing files as they are and create only the missing ones, without asking.",
)
parser.add_argument(
"--dependencies",
choices=["auto", "pyproject", "requirements"],
default=None,
help="Dependency file to create. See `dlthub init --help`.",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Print the plan without writing anything.",
)
# takes a required value, unlike in `dlthub init`, so it never swallows the directory
parser.add_argument(
"--agent",
default=None,
metavar="NAME",
help="Coding agent to set up, for example claude, cursor, codex or cortex. Detected when omitted.",
)
parser.add_argument(
"-y",
"--yes",
action="store_true",
help="Apply the changes to existing files without asking.",
)
parser.add_argument(
"-v",
"--verbose",
action="store_true",
help="Show the output of uv sync.",
)
parser.add_argument(
"--no-sync",
action="store_true",
help="Do not install the dependencies with uv sync.",
)
parser.add_argument(
"--no-telemetry",
action="store_true",
help="Disable usage telemetry for this run, also in the dlthub commands it runs.",
)
return parser
def main(argv: list[str] | None = None) -> int:
_ensure_utf8_io_on_windows()
args = build_parser().parse_args(argv)
telemetry.init(no_telemetry=args.no_telemetry)
try:
run(args)
except KeyboardInterrupt:
telemetry.track_run("cancelled")
console.print(strings.MSG_CANCELLED)
return 130
except DlthubCommandError as exc:
telemetry.add_properties(failed_step=exc.step)
telemetry.track_run("failed", error_code=type(exc).__name__)
print_command_failed(exc)
return exc.returncode if exc.returncode > 0 else 1
except WorkspaceError as exc:
telemetry.track_run("failed", error_code=type(exc).__name__)
console.print(strings.MSG_ERROR_PREFIX.format(message=exc))
return 1
except Exception as exc:
telemetry.track_run("failed", error_code=type(exc).__name__)
console.print(strings.MSG_UNEXPECTED_ERROR.format(message=exc))
if args.verbose:
console.print_exception()
else:
console.print(strings.MSG_UNEXPECTED_ERROR_HINT)
return 1
telemetry.track_run("success")
return 0
def run(args: argparse.Namespace) -> None:
project_dir = resolve_target(args.project_dir)
dlt_version = get_dlt_version()
telemetry.add_properties(dlt_version=str(dlt_version))
options = InitOptions(
mode=_get_mode(args),
name=args.name,
dependencies=args.dependencies,
dry_run=args.dry_run,
agent=args.agent,
yes=args.yes,
)
dlthub = find_dlthub()
uv_executable = find_uv()
env = build_env(uv_executable, telemetry_off=telemetry.is_opted_out(args.no_telemetry))
print_header(project_dir, dlt_version)
_make_dir(project_dir)
for step in build_steps(options, dlt_version, workspace_exists=has_workspace(project_dir)):
raise_on_failure(step, run_step(dlthub, step, project_dir, env), options, dlt_version)
if options.dry_run:
return
if not (project_dir / "pyproject.toml").is_file():
# `uv sync` needs a pyproject.toml, dlthub already said how to install a requirements.txt
print_next_steps(project_dir, sync_pending=False)
return
synced = _maybe_sync(project_dir, uv_executable, no_sync=args.no_sync, verbose=args.verbose)
print_next_steps(project_dir, sync_pending=not synced)
def resolve_target(requested_arg: str | None) -> Path:
if requested_arg is not None:
return Path(requested_arg).expanduser().resolve()
return Path.cwd().resolve()
def _get_mode(args: argparse.Namespace) -> InitMode:
if args.overwrite:
return "overwrite"
if args.skip:
return "skip"
return "merge"
def _make_dir(project_dir: Path) -> None:
try:
project_dir.mkdir(parents=True, exist_ok=True)
except OSError as exc:
raise WorkspaceError(strings.ERROR_WRITE_FAILED.format(path=project_dir, reason=exc)) from exc
def _maybe_sync(project_dir: Path, uv_executable: str | None, *, no_sync: bool, verbose: bool) -> bool:
if no_sync:
return False
if uv_executable is None:
console.print(strings.MSG_NO_UV)
return False
try:
with substep(strings.MSG_INSTALLING_DEPS, strings.MSG_INSTALLED_DEPS, verbose=verbose):
run_uv_sync(uv_executable, project_dir, verbose=verbose)
except UvError as exc:
print_sync_failed(exc)
return False
return True
if __name__ == "__main__":
sys.exit(main())