itqan-cli 0.3.0__tar.gz → 0.4.0__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.
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/CHANGELOG.md +12 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/PKG-INFO +4 -4
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/README.md +3 -3
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/pyproject.toml +1 -1
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/src/itqan_cli/downloader.py +26 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/src/itqan_cli/main.py +51 -7
- itqan_cli-0.4.0/src/itqan_cli/progress.py +134 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/test_browse.py +59 -1
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/test_downloader.py +95 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/test_init.py +75 -0
- itqan_cli-0.4.0/tests/test_install_progress.py +124 -0
- itqan_cli-0.4.0/tests/test_progress.py +187 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/.gitignore +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/LICENSE +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/RELEASING.md +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/dart/.gitignore +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/dart/README.md +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/dart/analysis_options.yaml +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/dart/bin/itqan.dart +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/dart/lib/itqan_cli.dart +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/dart/lib/src/launcher.dart +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/dart/lib/src/version.dart +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/dart/pubspec.yaml +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/dart/test/launcher_test.dart +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/npm/README.md +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/npm/bin/itqan.js +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/scripts/dart_package.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/scripts/homebrew_formula.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/scripts/npm_packages.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/src/itqan_cli/__init__.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/src/itqan_cli/__main__.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/src/itqan_cli/add.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/src/itqan_cli/browse.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/src/itqan_cli/client.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/src/itqan_cli/credentials.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/src/itqan_cli/exceptions.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/src/itqan_cli/flutter.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/src/itqan_cli/init_template.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/src/itqan_cli/lockfile.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/src/itqan_cli/manifest.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/src/itqan_cli/semver.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/src/itqan_cli/updates.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/__init__.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/conftest.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/test_access.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/test_add.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/test_assets_dir.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/test_cli_integration.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/test_client.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/test_dart_package.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/test_entry_points.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/test_flutter.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/test_homebrew_formula.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/test_languages.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/test_lockfile.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/test_login.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/test_manifest.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/test_npm_packages.py +0 -0
- {itqan_cli-0.3.0 → itqan_cli-0.4.0}/tests/test_updates.py +0 -0
|
@@ -1,3 +1,15 @@
|
|
|
1
|
+
## v0.4.0 (2026-10-18)
|
|
2
|
+
|
|
3
|
+
### Feat
|
|
4
|
+
|
|
5
|
+
- **install**: `itqan install` shows each download's progress in a terminal: bytes done and total,
|
|
6
|
+
percent, rate and time left, or a running byte count when the size isn't known. Piped and CI
|
|
7
|
+
output stays the same; `--no-progress` or `TERM=dumb` turns it off.
|
|
8
|
+
- **init**: `itqan init` asks whether to run `itqan browse` once it has written the manifest, so
|
|
9
|
+
you can pick assets straight away.
|
|
10
|
+
- **browse**: in a Flutter project, `itqan browse` offers to run `itqan install --flutter`, so the
|
|
11
|
+
installed asset folders get listed in `pubspec.yaml`.
|
|
12
|
+
|
|
1
13
|
## v0.3.0 (2026-10-18)
|
|
2
14
|
|
|
3
15
|
### Feat
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: itqan-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: Itqan Quranic Asset Manager: install and pin Itqan Quranic assets in your project.
|
|
5
5
|
Project-URL: Homepage, https://github.com/Itqan-community/itqan-cli
|
|
6
6
|
Project-URL: Repository, https://github.com/Itqan-community/itqan-cli
|
|
@@ -159,7 +159,7 @@ Run these in your project's folder:
|
|
|
159
159
|
|
|
160
160
|
```bash
|
|
161
161
|
itqan init # 1. create itqan-assets.yaml, with commented-out example assets
|
|
162
|
-
itqan browse # 2. search the catalog and add the assets you want (
|
|
162
|
+
itqan browse # 2. search the catalog and add the assets you want (init offers to run it for you)
|
|
163
163
|
itqan install # 3. download them and write itqan-assets.lock
|
|
164
164
|
```
|
|
165
165
|
|
|
@@ -427,10 +427,10 @@ example, `npm ci` for a project with `itqan-cli` in its `devDependencies`, or
|
|
|
427
427
|
|
|
428
428
|
| Command | What it does |
|
|
429
429
|
|---|---|
|
|
430
|
-
| `itqan init` | Create `itqan-assets.yaml` with a few assets from the catalog as commented-out examples (placeholder examples when offline). `--assets-dir` sets where assets go; `--force` overwrites an existing manifest. |
|
|
430
|
+
| `itqan init` | Create `itqan-assets.yaml` with a few assets from the catalog as commented-out examples (placeholder examples when offline), then offers to run `itqan browse` when run in a terminal. `--assets-dir` sets where assets go; `--force` overwrites an existing manifest. |
|
|
431
431
|
| `itqan browse [SEARCH]` | Search the catalog, pick assets, add them to `itqan-assets.yaml` (created if missing), and optionally install them. `--category` limits it to one kind of asset; `--no-interactive` prints a table (the default when not in a terminal); `--json` prints JSON. |
|
|
432
432
|
| `itqan add ASSET[@RANGE]...` | Add assets to `itqan-assets.yaml` (created if missing) and install them. Without `@RANGE` an entry accepts `^` the newest version; an asset already in the manifest gets the new range. `--language` picks a language other than the source; `--no-install` only edits the manifest. |
|
|
433
|
-
| `itqan install` | Download the assets and write `itqan-assets.lock`. Uses the lockfile's exact versions while it matches the manifest. `--force` picks the newest allowed versions and downloads again. `--flutter` keeps `pubspec.yaml` up to date (see [Flutter](#flutter)). `--assets-dir` overrides the manifest's folder for one run. |
|
|
433
|
+
| `itqan install` | Download the assets and write `itqan-assets.lock`. Uses the lockfile's exact versions while it matches the manifest. `--force` picks the newest allowed versions and downloads again. `--flutter` keeps `pubspec.yaml` up to date (see [Flutter](#flutter)). `--assets-dir` overrides the manifest's folder for one run. In a terminal it shows each download's progress; `--no-progress` turns that off. |
|
|
434
434
|
| `itqan sync` | Same as `itqan install`. |
|
|
435
435
|
| `itqan outdated` | List the locked assets that have newer versions: the newest your range allows and the newest overall. `--json` prints JSON. |
|
|
436
436
|
| `itqan login` | Save your API key for the registry, after checking it. `--api-key` passes the key without the prompt. |
|
|
@@ -128,7 +128,7 @@ Run these in your project's folder:
|
|
|
128
128
|
|
|
129
129
|
```bash
|
|
130
130
|
itqan init # 1. create itqan-assets.yaml, with commented-out example assets
|
|
131
|
-
itqan browse # 2. search the catalog and add the assets you want (
|
|
131
|
+
itqan browse # 2. search the catalog and add the assets you want (init offers to run it for you)
|
|
132
132
|
itqan install # 3. download them and write itqan-assets.lock
|
|
133
133
|
```
|
|
134
134
|
|
|
@@ -396,10 +396,10 @@ example, `npm ci` for a project with `itqan-cli` in its `devDependencies`, or
|
|
|
396
396
|
|
|
397
397
|
| Command | What it does |
|
|
398
398
|
|---|---|
|
|
399
|
-
| `itqan init` | Create `itqan-assets.yaml` with a few assets from the catalog as commented-out examples (placeholder examples when offline). `--assets-dir` sets where assets go; `--force` overwrites an existing manifest. |
|
|
399
|
+
| `itqan init` | Create `itqan-assets.yaml` with a few assets from the catalog as commented-out examples (placeholder examples when offline), then offers to run `itqan browse` when run in a terminal. `--assets-dir` sets where assets go; `--force` overwrites an existing manifest. |
|
|
400
400
|
| `itqan browse [SEARCH]` | Search the catalog, pick assets, add them to `itqan-assets.yaml` (created if missing), and optionally install them. `--category` limits it to one kind of asset; `--no-interactive` prints a table (the default when not in a terminal); `--json` prints JSON. |
|
|
401
401
|
| `itqan add ASSET[@RANGE]...` | Add assets to `itqan-assets.yaml` (created if missing) and install them. Without `@RANGE` an entry accepts `^` the newest version; an asset already in the manifest gets the new range. `--language` picks a language other than the source; `--no-install` only edits the manifest. |
|
|
402
|
-
| `itqan install` | Download the assets and write `itqan-assets.lock`. Uses the lockfile's exact versions while it matches the manifest. `--force` picks the newest allowed versions and downloads again. `--flutter` keeps `pubspec.yaml` up to date (see [Flutter](#flutter)). `--assets-dir` overrides the manifest's folder for one run. |
|
|
402
|
+
| `itqan install` | Download the assets and write `itqan-assets.lock`. Uses the lockfile's exact versions while it matches the manifest. `--force` picks the newest allowed versions and downloads again. `--flutter` keeps `pubspec.yaml` up to date (see [Flutter](#flutter)). `--assets-dir` overrides the manifest's folder for one run. In a terminal it shows each download's progress; `--no-progress` turns that off. |
|
|
403
403
|
| `itqan sync` | Same as `itqan install`. |
|
|
404
404
|
| `itqan outdated` | List the locked assets that have newer versions: the newest your range allows and the newest overall. `--json` prints JSON. |
|
|
405
405
|
| `itqan login` | Save your API key for the registry, after checking it. `--api-key` passes the key without the prompt. |
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
from collections.abc import Callable
|
|
5
6
|
from dataclasses import dataclass
|
|
6
7
|
import os
|
|
7
8
|
from pathlib import Path
|
|
@@ -20,6 +21,9 @@ _MARKER_DIR = ".itqan"
|
|
|
20
21
|
# A download URL must never produce a basename matching it, or it would clobber the marker.
|
|
21
22
|
_RESERVED_FILENAME = ".itqan_version"
|
|
22
23
|
|
|
24
|
+
# on_progress(downloaded_bytes, total_bytes): total is None when the server doesn't say.
|
|
25
|
+
ProgressCallback = Callable[[int, int | None], None]
|
|
26
|
+
|
|
23
27
|
|
|
24
28
|
def _validate_slug(slug: str) -> None:
|
|
25
29
|
"""Reject slugs that could escape the assets directory via path traversal.
|
|
@@ -113,6 +117,7 @@ class AssetDownloader:
|
|
|
113
117
|
asset: ResolvedAssetPayload,
|
|
114
118
|
*,
|
|
115
119
|
force: bool = False,
|
|
120
|
+
on_progress: ProgressCallback | None = None,
|
|
116
121
|
) -> DownloadResult:
|
|
117
122
|
"""Materialize a single resolved asset into the assets/<entry name>/ folder.
|
|
118
123
|
|
|
@@ -122,6 +127,8 @@ class AssetDownloader:
|
|
|
122
127
|
Ensures:
|
|
123
128
|
- Safety: slug is validated against path traversal before any I/O.
|
|
124
129
|
- Idempotency: skip if already present and non-empty.
|
|
130
|
+
- Progress: `on_progress` is called once the server answers and after every
|
|
131
|
+
chunk, never for a cached asset.
|
|
125
132
|
- Atomicity: stream to temp file and rename upon success.
|
|
126
133
|
- Marker atomicity: version marker is staged as a temp file then
|
|
127
134
|
renamed — both the artifact and its marker are committed together
|
|
@@ -198,9 +205,16 @@ class AssetDownloader:
|
|
|
198
205
|
raise DownloadError(
|
|
199
206
|
f"Failed to download '{asset.slug}' from {asset.download_url}: HTTP {resp.status_code}"
|
|
200
207
|
)
|
|
208
|
+
total = _content_length(resp)
|
|
209
|
+
done = 0
|
|
210
|
+
if on_progress:
|
|
211
|
+
on_progress(done, total)
|
|
201
212
|
for chunk in resp.iter_content(chunk_size=65536):
|
|
202
213
|
if chunk:
|
|
203
214
|
f_out.write(chunk)
|
|
215
|
+
done += len(chunk)
|
|
216
|
+
if on_progress:
|
|
217
|
+
on_progress(done, total)
|
|
204
218
|
|
|
205
219
|
# Write version string to the staged marker tmp file
|
|
206
220
|
marker_tmp.write_text(asset.resolved_version, encoding="utf-8")
|
|
@@ -235,5 +249,17 @@ class AssetDownloader:
|
|
|
235
249
|
raise DownloadError(f"Error downloading asset '{asset.slug}': {exc}") from exc
|
|
236
250
|
|
|
237
251
|
|
|
252
|
+
def _content_length(resp: requests.Response) -> int | None:
|
|
253
|
+
"""The body size in bytes, or None when unknown. A compressed response's Content-Length
|
|
254
|
+
counts compressed bytes, but iter_content yields them decompressed, so it's unknown too."""
|
|
255
|
+
if resp.headers.get("Content-Encoding", "identity").lower() != "identity":
|
|
256
|
+
return None
|
|
257
|
+
try:
|
|
258
|
+
length = int(resp.headers["Content-Length"])
|
|
259
|
+
except (KeyError, ValueError):
|
|
260
|
+
return None
|
|
261
|
+
return length if length >= 0 else None
|
|
262
|
+
|
|
263
|
+
|
|
238
264
|
def _read_marker(marker: Path) -> str | None:
|
|
239
265
|
return marker.read_text(encoding="utf-8").strip() if marker.is_file() else None
|
|
@@ -11,7 +11,7 @@ import sys
|
|
|
11
11
|
|
|
12
12
|
import click
|
|
13
13
|
|
|
14
|
-
from itqan_cli import add, browse, credentials, flutter as flutter_pubspec, updates
|
|
14
|
+
from itqan_cli import add, browse, credentials, flutter as flutter_pubspec, progress, updates
|
|
15
15
|
from itqan_cli.client import DEFAULT_REGISTRY_URL, CatalogLanguage, CatalogPackage, RegistryClient, ResolvedAssetPayload
|
|
16
16
|
from itqan_cli.downloader import AssetDownloader
|
|
17
17
|
from itqan_cli.exceptions import ItqanCliError, RegistryApiError
|
|
@@ -45,6 +45,7 @@ def _run_install(
|
|
|
45
45
|
api_key: str | None,
|
|
46
46
|
force: bool,
|
|
47
47
|
flutter: bool | None = None,
|
|
48
|
+
no_progress: bool = False,
|
|
48
49
|
) -> int:
|
|
49
50
|
m_path = Path(manifest_path)
|
|
50
51
|
l_path = Path(lockfile_path)
|
|
@@ -126,9 +127,19 @@ def _run_install(
|
|
|
126
127
|
# If any download fails, we raise immediately and the lockfile is untouched.
|
|
127
128
|
click.echo(f"Materializing {len(resolved_payloads)} asset(s) into {a_dir}...")
|
|
128
129
|
download_summary = []
|
|
130
|
+
show_progress = progress.enabled(no_progress)
|
|
129
131
|
|
|
130
|
-
for item in resolved_payloads:
|
|
131
|
-
|
|
132
|
+
for index, item in enumerate(resolved_payloads, start=1):
|
|
133
|
+
bar = None
|
|
134
|
+
if show_progress:
|
|
135
|
+
bar = progress.DownloadProgress(
|
|
136
|
+
f"({index}/{len(resolved_payloads)}) {item.entry_name} [{item.resolved_version}]"
|
|
137
|
+
)
|
|
138
|
+
try:
|
|
139
|
+
res = downloader.materialize_asset(item, force=force, on_progress=bar)
|
|
140
|
+
finally:
|
|
141
|
+
if bar:
|
|
142
|
+
bar.clear()
|
|
132
143
|
status_str = "downloaded" if res.downloaded else "cached (up-to-date)"
|
|
133
144
|
click.echo(f" * {res.slug} [{res.version}]: {status_str} -> {res.target_path}")
|
|
134
145
|
download_summary.append(res)
|
|
@@ -236,6 +247,12 @@ def _notify_updates(resolved_payloads: list[ResolvedAssetPayload], manifest: Ass
|
|
|
236
247
|
help="List the installed asset folders under `flutter: assets:` in the pubspec.yaml next to the manifest. "
|
|
237
248
|
"Once used, later installs keep that list up to date without the flag.",
|
|
238
249
|
)
|
|
250
|
+
@click.option(
|
|
251
|
+
"--no-progress",
|
|
252
|
+
is_flag=True,
|
|
253
|
+
default=False,
|
|
254
|
+
help="Don't draw download progress. It's only drawn in a terminal, and not when TERM=dumb.",
|
|
255
|
+
)
|
|
239
256
|
def install_command(
|
|
240
257
|
manifest_path: str,
|
|
241
258
|
lockfile_path: str,
|
|
@@ -244,6 +261,7 @@ def install_command(
|
|
|
244
261
|
api_key: str | None,
|
|
245
262
|
force: bool,
|
|
246
263
|
flutter: bool | None = None,
|
|
264
|
+
no_progress: bool = False,
|
|
247
265
|
) -> None:
|
|
248
266
|
"""Install assets declared in itqan-assets.yaml."""
|
|
249
267
|
api_key = _api_key(api_key, registry_url)
|
|
@@ -256,6 +274,7 @@ def install_command(
|
|
|
256
274
|
api_key=api_key,
|
|
257
275
|
force=force,
|
|
258
276
|
flutter=flutter,
|
|
277
|
+
no_progress=no_progress,
|
|
259
278
|
)
|
|
260
279
|
sys.exit(exit_code)
|
|
261
280
|
except ItqanCliError as exc:
|
|
@@ -284,6 +303,11 @@ def _warn_withdrawn(resolved_payloads: list[ResolvedAssetPayload]) -> None:
|
|
|
284
303
|
)
|
|
285
304
|
|
|
286
305
|
|
|
306
|
+
def _interactive_terminal() -> bool:
|
|
307
|
+
"""Whether a person is at the keyboard to answer prompts."""
|
|
308
|
+
return sys.stdin.isatty() and sys.stdout.isatty()
|
|
309
|
+
|
|
310
|
+
|
|
287
311
|
def _api_key(api_key: str | None, registry_url: str) -> str | None:
|
|
288
312
|
"""--api-key / ITQAN_API_KEY when given, else the key `itqan login` saved for this registry."""
|
|
289
313
|
if api_key:
|
|
@@ -437,7 +461,7 @@ def init_command(manifest_path: str, assets_dir: str, registry_url: str, api_key
|
|
|
437
461
|
|
|
438
462
|
The examples are real assets from the registry, or placeholders when it
|
|
439
463
|
can't be reached. Uncomment the ones you want, or add assets with
|
|
440
|
-
`itqan browse
|
|
464
|
+
`itqan browse`, which init offers to run when used in a terminal.
|
|
441
465
|
"""
|
|
442
466
|
m_path = Path(manifest_path)
|
|
443
467
|
if m_path.exists() and not force:
|
|
@@ -468,6 +492,21 @@ def init_command(manifest_path: str, assets_dir: str, registry_url: str, api_key
|
|
|
468
492
|
m_path.write_text(content, encoding="utf-8")
|
|
469
493
|
examples = f" with {len(samples)} commented-out example asset(s)" if samples else " with commented-out examples"
|
|
470
494
|
click.echo(f"Created {m_path}{examples}.")
|
|
495
|
+
if _interactive_terminal():
|
|
496
|
+
import questionary
|
|
497
|
+
|
|
498
|
+
if questionary.confirm("Run `itqan browse` now to pick assets to add?", default=True).ask():
|
|
499
|
+
browse_command.callback(
|
|
500
|
+
query=None,
|
|
501
|
+
category=None,
|
|
502
|
+
manifest_path=str(m_path),
|
|
503
|
+
lockfile_path="itqan-assets.lock",
|
|
504
|
+
interactive=True,
|
|
505
|
+
as_json=False,
|
|
506
|
+
registry_url=registry_url,
|
|
507
|
+
api_key=api_key,
|
|
508
|
+
)
|
|
509
|
+
return
|
|
471
510
|
click.echo("Next, run `itqan browse` to find assets and add them to it, or uncomment the examples.")
|
|
472
511
|
if flutter_pubspec.is_flutter_project(m_path.parent / flutter_pubspec.PUBSPEC):
|
|
473
512
|
click.echo(f"Then run `itqan install --flutter` to download them and list them in {flutter_pubspec.PUBSPEC}.")
|
|
@@ -531,7 +570,7 @@ def browse_command(
|
|
|
531
570
|
without it, every asset is listed and you can filter by typing in the picker.
|
|
532
571
|
"""
|
|
533
572
|
if interactive is None:
|
|
534
|
-
interactive =
|
|
573
|
+
interactive = _interactive_terminal()
|
|
535
574
|
if as_json:
|
|
536
575
|
interactive = False
|
|
537
576
|
m_path = Path(manifest_path)
|
|
@@ -587,7 +626,11 @@ def browse_command(
|
|
|
587
626
|
|
|
588
627
|
import questionary
|
|
589
628
|
|
|
590
|
-
|
|
629
|
+
# In a Flutter project, offer the install that also lists the folders in pubspec.yaml;
|
|
630
|
+
# the question names --flutter, so saying yes is the opt-in.
|
|
631
|
+
flutter = flutter_pubspec.is_flutter_project(m_path.parent / flutter_pubspec.PUBSPEC)
|
|
632
|
+
command = "itqan install --flutter" if flutter else "itqan install"
|
|
633
|
+
if questionary.confirm(f"Run `{command}` now?", default=True).ask():
|
|
591
634
|
install_command.callback(
|
|
592
635
|
manifest_path=str(m_path),
|
|
593
636
|
lockfile_path=lockfile_path,
|
|
@@ -595,9 +638,10 @@ def browse_command(
|
|
|
595
638
|
registry_url=registry_url,
|
|
596
639
|
api_key=api_key,
|
|
597
640
|
force=False,
|
|
641
|
+
flutter=True if flutter else None,
|
|
598
642
|
)
|
|
599
643
|
else:
|
|
600
|
-
click.echo("Run `
|
|
644
|
+
click.echo(f"Run `{command}` when you're ready to download them.")
|
|
601
645
|
|
|
602
646
|
|
|
603
647
|
def _add_to_manifest(
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Progress line drawn while `itqan install` downloads an asset.
|
|
2
|
+
|
|
3
|
+
Only drawn in a terminal: piped, redirected or CI output stays plain lines, with no `\\r` frames.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
import os
|
|
10
|
+
import shutil
|
|
11
|
+
import sys
|
|
12
|
+
import time
|
|
13
|
+
|
|
14
|
+
import click
|
|
15
|
+
|
|
16
|
+
# The bar gets the room the numbers leave, between these widths, or is left out.
|
|
17
|
+
_BAR_MAX_WIDTH = 30
|
|
18
|
+
_BAR_MIN_WIDTH = 8
|
|
19
|
+
# Room kept for the rate ("999.9 KB/s") and ETA ("0:00:00"), so the bar keeps one width all along.
|
|
20
|
+
_RATE_WIDTH = 10
|
|
21
|
+
_ETA_WIDTH = 7
|
|
22
|
+
_SPINNER = "|/-\\"
|
|
23
|
+
# Redraw at most this often (seconds); downloads report every 64 KiB chunk.
|
|
24
|
+
_REDRAW_INTERVAL = 0.1
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def enabled(no_progress: bool = False) -> bool:
|
|
28
|
+
"""Whether to draw progress: not with --no-progress, TERM=dumb, or when stdout isn't a terminal."""
|
|
29
|
+
return not no_progress and os.environ.get("TERM") != "dumb" and _stdout_is_terminal()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _stdout_is_terminal() -> bool:
|
|
33
|
+
return sys.stdout.isatty()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class DownloadProgress:
|
|
37
|
+
"""A one-line progress display, redrawn in place, for one download.
|
|
38
|
+
|
|
39
|
+
Pass it as `materialize_asset(on_progress=...)`. Call `clear()` once the download
|
|
40
|
+
ends or fails, so the next line prints where the progress line was.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(
|
|
44
|
+
self,
|
|
45
|
+
label: str,
|
|
46
|
+
*,
|
|
47
|
+
write: Callable[[str], None] | None = None,
|
|
48
|
+
clock: Callable[[], float] = time.monotonic,
|
|
49
|
+
columns: Callable[[], int] | None = None,
|
|
50
|
+
) -> None:
|
|
51
|
+
self.label = label
|
|
52
|
+
self._write = write or (lambda text: click.echo(text, nl=False))
|
|
53
|
+
self._clock = clock
|
|
54
|
+
self._columns = columns or (lambda: shutil.get_terminal_size().columns)
|
|
55
|
+
self._started: float | None = None
|
|
56
|
+
self._last_draw: float | None = None
|
|
57
|
+
self._drawn_width = 0
|
|
58
|
+
self._frame = 0
|
|
59
|
+
|
|
60
|
+
def __call__(self, done: int, total: int | None) -> None:
|
|
61
|
+
now = self._clock()
|
|
62
|
+
if self._started is None:
|
|
63
|
+
self._started = now
|
|
64
|
+
finished = total is not None and done >= total
|
|
65
|
+
if self._last_draw is not None and now - self._last_draw < _REDRAW_INTERVAL and not finished:
|
|
66
|
+
return
|
|
67
|
+
self._last_draw = now
|
|
68
|
+
self._draw(self.render(done, total, now - self._started))
|
|
69
|
+
|
|
70
|
+
def render(self, done: int, total: int | None, elapsed: float) -> str:
|
|
71
|
+
rate = done / elapsed if elapsed > 0 else 0.0
|
|
72
|
+
speed = f"{format_bytes(rate)}/s" if rate else ""
|
|
73
|
+
if total is None:
|
|
74
|
+
self._frame += 1
|
|
75
|
+
return _join(self.label, _SPINNER[self._frame % len(_SPINNER)], format_bytes(done), speed)
|
|
76
|
+
fraction = min(done / total, 1.0) if total else 1.0
|
|
77
|
+
eta = _format_eta((total - done) / rate) if rate and done < total else ""
|
|
78
|
+
numbers = _join(_format_ratio(done, total), f"{int(fraction * 100):3d}%", speed, eta)
|
|
79
|
+
widest = _join(_format_ratio(total, total), "100%", "x" * _RATE_WIDTH, "x" * _ETA_WIDTH)
|
|
80
|
+
# Leave the last column free: some terminals wrap a line that fills the row.
|
|
81
|
+
width = min(self._columns() - 1 - len(_join(self.label, "[]", widest)), _BAR_MAX_WIDTH)
|
|
82
|
+
if width < _BAR_MIN_WIDTH:
|
|
83
|
+
return _join(self.label, numbers)
|
|
84
|
+
filled = int(fraction * width)
|
|
85
|
+
bar = "=" * filled + (">" if filled < width else "") + " " * (width - filled - 1)
|
|
86
|
+
return _join(self.label, f"[{bar}]", numbers)
|
|
87
|
+
|
|
88
|
+
def clear(self) -> None:
|
|
89
|
+
if self._drawn_width:
|
|
90
|
+
self._write("\r" + " " * self._drawn_width + "\r")
|
|
91
|
+
self._drawn_width = 0
|
|
92
|
+
|
|
93
|
+
def _draw(self, line: str) -> None:
|
|
94
|
+
# A line wider than the terminal wraps, and `\r` then only rewinds its last row.
|
|
95
|
+
line = line[: max(self._columns() - 1, 0)]
|
|
96
|
+
self._write("\r" + line.ljust(self._drawn_width))
|
|
97
|
+
self._drawn_width = len(line)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _join(*parts: str) -> str:
|
|
101
|
+
return " ".join(part for part in parts if part)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
_UNITS = ("B", "KB", "MB", "GB", "TB")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _unit(size: float) -> int:
|
|
108
|
+
index = 0
|
|
109
|
+
while size >= 1000 and index < len(_UNITS) - 1:
|
|
110
|
+
size /= 1000
|
|
111
|
+
index += 1
|
|
112
|
+
return index
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def format_bytes(size: float) -> str:
|
|
116
|
+
"""1234567 -> '1.2 MB' (decimal units, like download managers)."""
|
|
117
|
+
index = _unit(size)
|
|
118
|
+
if index == 0:
|
|
119
|
+
return f"{int(size)} B"
|
|
120
|
+
return f"{size / 1000**index:.1f} {_UNITS[index]}"
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _format_ratio(done: int, total: int) -> str:
|
|
124
|
+
"""Both sides in the total's unit: '45.3/120.0 MB'."""
|
|
125
|
+
index = _unit(total)
|
|
126
|
+
if index == 0:
|
|
127
|
+
return f"{done}/{total} B"
|
|
128
|
+
scale = 1000**index
|
|
129
|
+
return f"{done / scale:.1f}/{total / scale:.1f} {_UNITS[index]}"
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _format_eta(seconds: float) -> str:
|
|
133
|
+
seconds = int(seconds)
|
|
134
|
+
return f"{seconds // 3600}:{seconds // 60 % 60:02d}:{seconds % 60:02d}"
|
|
@@ -8,7 +8,7 @@ import pytest
|
|
|
8
8
|
import responses
|
|
9
9
|
from responses import matchers
|
|
10
10
|
|
|
11
|
-
from itqan_cli import browse
|
|
11
|
+
from itqan_cli import browse, main
|
|
12
12
|
from itqan_cli.client import CatalogLanguage, CatalogPackage, RegistryClient
|
|
13
13
|
from itqan_cli.exceptions import ManifestError, RegistryApiError
|
|
14
14
|
from itqan_cli.init_template import render_fallback, render_from_catalog
|
|
@@ -302,6 +302,64 @@ def test_browse_command_where_assets_picked_should_create_manifest_with_them(tmp
|
|
|
302
302
|
assert "Run `itqan install` when you're ready" in result.output
|
|
303
303
|
|
|
304
304
|
|
|
305
|
+
def _pick_everything_and_answer(monkeypatch, answer: bool) -> tuple[list[str], list[dict]]:
|
|
306
|
+
"""Pick every listed asset, answer the install question; returns the questions and install calls."""
|
|
307
|
+
asked: list[str] = []
|
|
308
|
+
installs: list[dict] = []
|
|
309
|
+
monkeypatch.setattr(browse, browse.pick_packages.__name__, lambda packages, targets, has_api_key: packages)
|
|
310
|
+
monkeypatch.setattr(browse, browse.pick_languages.__name__, lambda package, targets: list(package.languages))
|
|
311
|
+
monkeypatch.setattr(
|
|
312
|
+
"questionary.confirm",
|
|
313
|
+
lambda question, **kwargs: asked.append(question) or type("Q", (), {"ask": lambda self: answer})(),
|
|
314
|
+
)
|
|
315
|
+
monkeypatch.setattr(main.install_command, "callback", lambda **kwargs: installs.append(kwargs))
|
|
316
|
+
return asked, installs
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
@responses.activate
|
|
320
|
+
@pytest.mark.parametrize(
|
|
321
|
+
("pubspec", "command", "flutter"),
|
|
322
|
+
[
|
|
323
|
+
("name: app\nflutter:\n uses-material-design: true\n", "itqan install --flutter", True),
|
|
324
|
+
("name: pure_dart\n", "itqan install", None),
|
|
325
|
+
(None, "itqan install", None),
|
|
326
|
+
],
|
|
327
|
+
ids=["flutter project", "dart package", "no pubspec"],
|
|
328
|
+
)
|
|
329
|
+
def test_browse_command_where_user_installs_should_offer_flutter_only_in_a_flutter_project(
|
|
330
|
+
tmp_path: Path, monkeypatch, pubspec: str | None, command: str, flutter: bool | None
|
|
331
|
+
):
|
|
332
|
+
# Arrange
|
|
333
|
+
_mock_catalog([SINGLE])
|
|
334
|
+
if pubspec is not None:
|
|
335
|
+
(tmp_path / "pubspec.yaml").write_text(pubspec)
|
|
336
|
+
asked, installs = _pick_everything_and_answer(monkeypatch, True)
|
|
337
|
+
|
|
338
|
+
# Act
|
|
339
|
+
result = _browse(tmp_path, "--interactive")
|
|
340
|
+
|
|
341
|
+
# Assert
|
|
342
|
+
assert result.exit_code == 0, result.output
|
|
343
|
+
assert asked == [f"Run `{command}` now?"]
|
|
344
|
+
assert [call["flutter"] for call in installs] == [flutter]
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
@responses.activate
|
|
348
|
+
def test_browse_command_where_flutter_user_declines_install_should_suggest_install_flutter(tmp_path: Path, monkeypatch):
|
|
349
|
+
# Arrange
|
|
350
|
+
_mock_catalog([SINGLE])
|
|
351
|
+
(tmp_path / "pubspec.yaml").write_text("name: app\nflutter:\n uses-material-design: true\n")
|
|
352
|
+
_, installs = _pick_everything_and_answer(monkeypatch, False)
|
|
353
|
+
|
|
354
|
+
# Act
|
|
355
|
+
result = _browse(tmp_path, "--interactive")
|
|
356
|
+
|
|
357
|
+
# Assert
|
|
358
|
+
assert result.exit_code == 0, result.output
|
|
359
|
+
assert installs == []
|
|
360
|
+
assert "Run `itqan install --flutter` when you're ready" in result.output
|
|
361
|
+
|
|
362
|
+
|
|
305
363
|
@responses.activate
|
|
306
364
|
def test_browse_command_where_picker_cancelled_should_not_write_manifest(tmp_path: Path, monkeypatch):
|
|
307
365
|
# Arrange
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"""Tests for AssetDownloader idempotency and atomic materialization."""
|
|
2
2
|
|
|
3
|
+
import gzip
|
|
3
4
|
from pathlib import Path
|
|
4
5
|
|
|
5
6
|
import pytest
|
|
@@ -152,3 +153,97 @@ def test_materialize_asset_where_entry_is_named_like_the_marker_folder_should_ra
|
|
|
152
153
|
|
|
153
154
|
with pytest.raises(DownloadError, match="reserved"):
|
|
154
155
|
AssetDownloader(assets_dir=tmp_path).materialize_asset(asset)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _progress_asset() -> ResolvedAssetPayload:
|
|
159
|
+
return ResolvedAssetPayload(
|
|
160
|
+
slug="quran-hafs",
|
|
161
|
+
asset_version_id=1,
|
|
162
|
+
resolved_version="1.2.0",
|
|
163
|
+
asset_name="Quran Hafs",
|
|
164
|
+
download_url="https://cdn.itqan.dev/quran.zip",
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
BODY = b"x" * (65536 * 2 + 10) # two full chunks and a short one
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@responses.activate
|
|
172
|
+
def test_materialize_asset_where_content_length_given_should_report_progress_per_chunk(tmp_path: Path):
|
|
173
|
+
# Arrange
|
|
174
|
+
responses.add(
|
|
175
|
+
responses.GET, "https://cdn.itqan.dev/quran.zip", body=BODY, headers={"Content-Length": str(len(BODY))}
|
|
176
|
+
)
|
|
177
|
+
calls: list[tuple[int, int | None]] = []
|
|
178
|
+
|
|
179
|
+
# Act
|
|
180
|
+
AssetDownloader(assets_dir=tmp_path).materialize_asset(_progress_asset(), on_progress=lambda *a: calls.append(a))
|
|
181
|
+
|
|
182
|
+
# Assert
|
|
183
|
+
total = len(BODY)
|
|
184
|
+
assert calls == [(0, total), (65536, total), (131072, total), (total, total)]
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
@responses.activate
|
|
188
|
+
def test_materialize_asset_where_no_content_length_should_report_progress_with_unknown_total(tmp_path: Path):
|
|
189
|
+
# Arrange
|
|
190
|
+
responses.add(responses.GET, "https://cdn.itqan.dev/quran.zip", body=BODY)
|
|
191
|
+
calls: list[tuple[int, int | None]] = []
|
|
192
|
+
|
|
193
|
+
# Act
|
|
194
|
+
AssetDownloader(assets_dir=tmp_path).materialize_asset(_progress_asset(), on_progress=lambda *a: calls.append(a))
|
|
195
|
+
|
|
196
|
+
# Assert
|
|
197
|
+
assert calls == [(0, None), (65536, None), (131072, None), (len(BODY), None)]
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@responses.activate
|
|
201
|
+
def test_materialize_asset_where_response_is_compressed_should_report_unknown_total(tmp_path: Path):
|
|
202
|
+
# Arrange: Content-Length counts compressed bytes, but the file is written decompressed.
|
|
203
|
+
compressed = gzip.compress(BODY)
|
|
204
|
+
responses.add(
|
|
205
|
+
responses.GET,
|
|
206
|
+
"https://cdn.itqan.dev/quran.zip",
|
|
207
|
+
body=compressed,
|
|
208
|
+
headers={"Content-Encoding": "gzip", "Content-Length": str(len(compressed))},
|
|
209
|
+
)
|
|
210
|
+
calls: list[tuple[int, int | None]] = []
|
|
211
|
+
|
|
212
|
+
# Act
|
|
213
|
+
result = AssetDownloader(assets_dir=tmp_path).materialize_asset(
|
|
214
|
+
_progress_asset(), on_progress=lambda *a: calls.append(a)
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
# Assert
|
|
218
|
+
assert {total for _, total in calls} == {None}
|
|
219
|
+
assert calls[-1][0] == result.size_bytes == len(BODY)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@responses.activate
|
|
223
|
+
def test_materialize_asset_where_asset_is_cached_should_not_report_progress(tmp_path: Path):
|
|
224
|
+
# Arrange
|
|
225
|
+
responses.add(responses.GET, "https://cdn.itqan.dev/quran.zip", body=BODY)
|
|
226
|
+
downloader = AssetDownloader(assets_dir=tmp_path)
|
|
227
|
+
downloader.materialize_asset(_progress_asset())
|
|
228
|
+
calls: list[tuple[int, int | None]] = []
|
|
229
|
+
|
|
230
|
+
# Act
|
|
231
|
+
result = downloader.materialize_asset(_progress_asset(), on_progress=lambda *a: calls.append(a))
|
|
232
|
+
|
|
233
|
+
# Assert
|
|
234
|
+
assert result.downloaded is False
|
|
235
|
+
assert calls == []
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
@responses.activate
|
|
239
|
+
def test_materialize_asset_where_server_errors_should_not_report_progress(tmp_path: Path):
|
|
240
|
+
# Arrange
|
|
241
|
+
responses.add(responses.GET, "https://cdn.itqan.dev/quran.zip", status=500)
|
|
242
|
+
calls: list[tuple[int, int | None]] = []
|
|
243
|
+
|
|
244
|
+
# Act / Assert
|
|
245
|
+
with pytest.raises(DownloadError):
|
|
246
|
+
AssetDownloader(assets_dir=tmp_path).materialize_asset(
|
|
247
|
+
_progress_asset(), on_progress=lambda *a: calls.append(a)
|
|
248
|
+
)
|
|
249
|
+
assert calls == []
|
|
@@ -4,10 +4,12 @@ from pathlib import Path
|
|
|
4
4
|
import re
|
|
5
5
|
|
|
6
6
|
from click.testing import CliRunner
|
|
7
|
+
import pytest
|
|
7
8
|
import requests
|
|
8
9
|
import responses
|
|
9
10
|
from responses import matchers
|
|
10
11
|
|
|
12
|
+
from itqan_cli import browse, main
|
|
11
13
|
from itqan_cli.main import cli
|
|
12
14
|
from itqan_cli.manifest import parse_manifest_content
|
|
13
15
|
|
|
@@ -251,6 +253,79 @@ def test_init_command_where_no_asset_has_a_second_language_should_still_show_a_l
|
|
|
251
253
|
assert (entry.language, entry.version) == ("ar", "^1.0.0")
|
|
252
254
|
|
|
253
255
|
|
|
256
|
+
def _answer_confirm(monkeypatch, answer: bool | None) -> list[str]:
|
|
257
|
+
"""Answer every questionary yes/no prompt with `answer`; returns the questions asked."""
|
|
258
|
+
asked: list[str] = []
|
|
259
|
+
|
|
260
|
+
def confirm(question, **kwargs):
|
|
261
|
+
asked.append(question)
|
|
262
|
+
return type("Q", (), {"ask": lambda self: answer})()
|
|
263
|
+
|
|
264
|
+
monkeypatch.setattr("questionary.confirm", confirm)
|
|
265
|
+
return asked
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
@responses.activate
|
|
269
|
+
def test_init_command_where_in_a_terminal_and_user_says_yes_should_run_browse(tmp_path: Path, monkeypatch):
|
|
270
|
+
# Arrange
|
|
271
|
+
_mock_catalog([SINGLE])
|
|
272
|
+
_mock_catalog([SINGLE], query={"page_size": "50"}) # browse lists the whole catalog
|
|
273
|
+
monkeypatch.setattr(main, main._interactive_terminal.__name__, lambda: True)
|
|
274
|
+
asked = _answer_confirm(monkeypatch, True)
|
|
275
|
+
shown: list[list[str]] = []
|
|
276
|
+
monkeypatch.setattr(
|
|
277
|
+
browse,
|
|
278
|
+
browse.pick_packages.__name__,
|
|
279
|
+
lambda packages, targets, has_api_key: shown.append([p.slug for p in packages]),
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
# Act
|
|
283
|
+
result = _init(tmp_path)
|
|
284
|
+
|
|
285
|
+
# Assert
|
|
286
|
+
assert result.exit_code == 0, result.output
|
|
287
|
+
assert asked == ["Run `itqan browse` now to pick assets to add?"]
|
|
288
|
+
assert shown == [["mushaf-madinah"]]
|
|
289
|
+
assert (tmp_path / "itqan-assets.yaml").is_file()
|
|
290
|
+
assert "Next, run `itqan browse`" not in result.output
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
@responses.activate
|
|
294
|
+
@pytest.mark.parametrize("answer", [False, None], ids=["no", "ctrl-c"])
|
|
295
|
+
def test_init_command_where_in_a_terminal_and_user_declines_should_print_next_steps(
|
|
296
|
+
tmp_path: Path, monkeypatch, answer: bool | None
|
|
297
|
+
):
|
|
298
|
+
# Arrange
|
|
299
|
+
_mock_catalog([SINGLE])
|
|
300
|
+
monkeypatch.setattr(main, main._interactive_terminal.__name__, lambda: True)
|
|
301
|
+
asked = _answer_confirm(monkeypatch, answer)
|
|
302
|
+
|
|
303
|
+
# Act
|
|
304
|
+
result = _init(tmp_path)
|
|
305
|
+
|
|
306
|
+
# Assert
|
|
307
|
+
assert result.exit_code == 0, result.output
|
|
308
|
+
assert len(asked) == 1
|
|
309
|
+
assert "Next, run `itqan browse`" in result.output
|
|
310
|
+
assert len(responses.calls) == 1 # browse never listed the catalog
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
@responses.activate
|
|
314
|
+
def test_init_command_where_not_in_a_terminal_should_not_ask_to_browse(tmp_path: Path, monkeypatch):
|
|
315
|
+
# Arrange
|
|
316
|
+
_mock_catalog([SINGLE])
|
|
317
|
+
monkeypatch.setattr(main, main._interactive_terminal.__name__, lambda: False)
|
|
318
|
+
asked = _answer_confirm(monkeypatch, True)
|
|
319
|
+
|
|
320
|
+
# Act
|
|
321
|
+
result = _init(tmp_path)
|
|
322
|
+
|
|
323
|
+
# Assert
|
|
324
|
+
assert result.exit_code == 0, result.output
|
|
325
|
+
assert asked == []
|
|
326
|
+
assert "Next, run `itqan browse`" in result.output
|
|
327
|
+
|
|
328
|
+
|
|
254
329
|
def test_cli_help_where_listing_commands_should_not_truncate_their_descriptions():
|
|
255
330
|
# Act
|
|
256
331
|
result = CliRunner().invoke(cli, ["--help"], terminal_width=60)
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""`itqan install` draws download progress only in a terminal."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from click.testing import CliRunner
|
|
6
|
+
import pytest
|
|
7
|
+
import responses
|
|
8
|
+
|
|
9
|
+
from itqan_cli import progress
|
|
10
|
+
from itqan_cli.downloader import AssetDownloader
|
|
11
|
+
from itqan_cli.exceptions import DownloadError
|
|
12
|
+
from itqan_cli.main import cli
|
|
13
|
+
|
|
14
|
+
REGISTRY = "https://api.itqan.dev/api"
|
|
15
|
+
URL = "https://cdn.itqan.dev/assets/quran.pdf"
|
|
16
|
+
BODY = b"%PDF-1.4 dummy pdf bytes"
|
|
17
|
+
SUMMARY = " * quran-uthmani-hafs [2.4.1]: downloaded -> "
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@pytest.fixture
|
|
21
|
+
def project(tmp_path: Path) -> Path:
|
|
22
|
+
(tmp_path / "itqan-assets.yaml").write_text(
|
|
23
|
+
'schema_version: 1\n\nassets:\n quran-uthmani-hafs:\n version: "^2.1.0"\n'
|
|
24
|
+
)
|
|
25
|
+
responses.add(
|
|
26
|
+
responses.POST,
|
|
27
|
+
f"{REGISTRY}/packages/resolve/manifest/",
|
|
28
|
+
json={
|
|
29
|
+
"results": [
|
|
30
|
+
{
|
|
31
|
+
"slug": "quran-uthmani-hafs",
|
|
32
|
+
"asset_version_id": 10,
|
|
33
|
+
"resolved_version": "2.4.1",
|
|
34
|
+
"asset_name": "Quran Hafs",
|
|
35
|
+
"download_url": URL,
|
|
36
|
+
}
|
|
37
|
+
]
|
|
38
|
+
},
|
|
39
|
+
)
|
|
40
|
+
responses.add(responses.GET, URL, body=BODY, headers={"Content-Length": str(len(BODY))})
|
|
41
|
+
return tmp_path
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@pytest.fixture
|
|
45
|
+
def terminal(monkeypatch):
|
|
46
|
+
monkeypatch.setenv("TERM", "xterm-256color")
|
|
47
|
+
monkeypatch.setenv("COLUMNS", "120")
|
|
48
|
+
monkeypatch.setattr(progress, progress._stdout_is_terminal.__name__, lambda: True)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _install(project: Path, *extra: str):
|
|
52
|
+
args = ["-m", str(project / "itqan-assets.yaml"), "-l", str(project / "itqan-assets.lock")]
|
|
53
|
+
return CliRunner().invoke(cli, ["install", *args, "--registry-url", REGISTRY, *extra])
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@responses.activate
|
|
57
|
+
def test_install_command_where_not_a_terminal_should_print_plain_lines(project: Path):
|
|
58
|
+
# Act
|
|
59
|
+
result = _install(project)
|
|
60
|
+
|
|
61
|
+
# Assert
|
|
62
|
+
assert result.exit_code == 0, result.output
|
|
63
|
+
assert "\r" not in result.output
|
|
64
|
+
assert SUMMARY in result.output
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@responses.activate
|
|
68
|
+
def test_install_command_where_in_a_terminal_should_draw_progress_then_the_summary_line(project: Path, terminal):
|
|
69
|
+
# Act
|
|
70
|
+
result = _install(project)
|
|
71
|
+
|
|
72
|
+
# Assert
|
|
73
|
+
assert result.exit_code == 0, result.output
|
|
74
|
+
drawn = result.output.index("\r(1/1) quran-uthmani-hafs [2.4.1] [")
|
|
75
|
+
cleared = result.output.index("\r" + " " * 10)
|
|
76
|
+
assert drawn < cleared < result.output.index(SUMMARY)
|
|
77
|
+
assert f"{len(BODY)}/{len(BODY)} B 100%" in result.output
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@responses.activate
|
|
81
|
+
def test_install_command_where_no_progress_given_should_not_draw_progress(project: Path, terminal):
|
|
82
|
+
# Act
|
|
83
|
+
result = _install(project, "--no-progress")
|
|
84
|
+
|
|
85
|
+
# Assert
|
|
86
|
+
assert result.exit_code == 0, result.output
|
|
87
|
+
assert "\r" not in result.output
|
|
88
|
+
assert SUMMARY in result.output
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@responses.activate
|
|
92
|
+
def test_install_command_where_asset_is_cached_should_not_draw_progress(project: Path, terminal):
|
|
93
|
+
# Arrange
|
|
94
|
+
_install(project)
|
|
95
|
+
|
|
96
|
+
# Act
|
|
97
|
+
result = _install(project)
|
|
98
|
+
|
|
99
|
+
# Assert
|
|
100
|
+
assert result.exit_code == 0, result.output
|
|
101
|
+
assert "\r" not in result.output
|
|
102
|
+
assert "cached (up-to-date)" in result.output
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@responses.activate
|
|
106
|
+
def test_install_command_where_download_fails_midway_should_clear_progress_before_the_error(
|
|
107
|
+
project: Path, terminal, monkeypatch
|
|
108
|
+
):
|
|
109
|
+
# Arrange
|
|
110
|
+
def fail_midway(self, asset, *, force=False, on_progress=None):
|
|
111
|
+
on_progress(10, 100)
|
|
112
|
+
raise DownloadError("connection reset")
|
|
113
|
+
|
|
114
|
+
monkeypatch.setattr(AssetDownloader, AssetDownloader.materialize_asset.__name__, fail_midway)
|
|
115
|
+
|
|
116
|
+
# Act
|
|
117
|
+
result = _install(project)
|
|
118
|
+
|
|
119
|
+
# Assert
|
|
120
|
+
assert result.exit_code != 0
|
|
121
|
+
assert not (project / "itqan-assets.lock").exists()
|
|
122
|
+
cleared = result.output.rindex("\r")
|
|
123
|
+
assert result.output[cleared - 1] == " " # the bar was blanked out
|
|
124
|
+
assert result.output.index("Error: connection reset") > cleared
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""The progress line `itqan install` draws while downloading."""
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from itqan_cli import progress
|
|
6
|
+
from itqan_cli.progress import DownloadProgress, format_bytes
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class _Clock:
|
|
10
|
+
def __init__(self) -> None:
|
|
11
|
+
self.now = 0.0
|
|
12
|
+
|
|
13
|
+
def __call__(self) -> float:
|
|
14
|
+
return self.now
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _bar(columns: int = 200) -> tuple[DownloadProgress, list[str], _Clock]:
|
|
18
|
+
written: list[str] = []
|
|
19
|
+
clock = _Clock()
|
|
20
|
+
bar = DownloadProgress("(2/5) quran-hafs [1.2.0]", write=written.append, clock=clock, columns=lambda: columns)
|
|
21
|
+
return bar, written, clock
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_render_where_total_known_should_show_bytes_percent_rate_and_eta():
|
|
25
|
+
# Arrange
|
|
26
|
+
bar, _, _ = _bar()
|
|
27
|
+
|
|
28
|
+
# Act
|
|
29
|
+
line = bar.render(45_300_000, 120_000_000, elapsed=9.0)
|
|
30
|
+
|
|
31
|
+
# Assert
|
|
32
|
+
assert line == f"(2/5) quran-hafs [1.2.0] [{'=' * 11}>{' ' * 18}] 45.3/120.0 MB 37% 5.0 MB/s 0:00:14"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def test_render_where_terminal_is_80_columns_should_shrink_the_bar_and_keep_the_numbers():
|
|
36
|
+
# Arrange
|
|
37
|
+
bar, _, _ = _bar(columns=80)
|
|
38
|
+
|
|
39
|
+
# Act
|
|
40
|
+
line = bar.render(45_300_000, 120_000_000, elapsed=9.0)
|
|
41
|
+
|
|
42
|
+
# Assert
|
|
43
|
+
assert line == "(2/5) quran-hafs [1.2.0] [===> ] 45.3/120.0 MB 37% 5.0 MB/s 0:00:14"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_render_should_keep_the_bar_one_width_from_start_to_finish():
|
|
47
|
+
# Arrange
|
|
48
|
+
bar, _, _ = _bar(columns=80)
|
|
49
|
+
|
|
50
|
+
# Act
|
|
51
|
+
lines = [
|
|
52
|
+
bar.render(0, 120_000_000, elapsed=0.0), # no rate or ETA yet
|
|
53
|
+
bar.render(45_300_000, 120_000_000, elapsed=9.0),
|
|
54
|
+
bar.render(120_000_000, 120_000_000, elapsed=24.0), # no ETA
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
# Assert
|
|
58
|
+
assert {line.index("] ", len(bar.label) + 2) for line in lines} == {35}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_render_where_no_room_for_a_bar_should_leave_it_out():
|
|
62
|
+
# Arrange
|
|
63
|
+
bar, _, _ = _bar(columns=60)
|
|
64
|
+
bar.label = "(12/20) a-very-long-entry-name-for-an-asset [10.20.30]"
|
|
65
|
+
|
|
66
|
+
# Act
|
|
67
|
+
line = bar.render(45_300_000, 120_000_000, elapsed=9.0)
|
|
68
|
+
|
|
69
|
+
# Assert
|
|
70
|
+
assert line == f"{bar.label} 45.3/120.0 MB 37% 5.0 MB/s 0:00:14"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def test_render_where_total_unknown_should_show_spinner_and_byte_count():
|
|
74
|
+
# Arrange
|
|
75
|
+
bar, _, _ = _bar()
|
|
76
|
+
|
|
77
|
+
# Act
|
|
78
|
+
line = bar.render(2_500_000, None, elapsed=1.0)
|
|
79
|
+
|
|
80
|
+
# Assert
|
|
81
|
+
assert line == "(2/5) quran-hafs [1.2.0] / 2.5 MB 2.5 MB/s"
|
|
82
|
+
assert "%" not in line
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_render_where_download_finished_should_show_a_full_bar_without_eta():
|
|
86
|
+
# Arrange
|
|
87
|
+
bar, _, _ = _bar()
|
|
88
|
+
|
|
89
|
+
# Act
|
|
90
|
+
line = bar.render(500, 500, elapsed=1.0)
|
|
91
|
+
|
|
92
|
+
# Assert
|
|
93
|
+
assert f"[{'=' * 30}] 500/500 B 100% 500 B/s" in line
|
|
94
|
+
assert line.endswith("B/s")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def test_render_where_server_sends_more_than_its_content_length_should_cap_at_100_percent():
|
|
98
|
+
# Arrange
|
|
99
|
+
bar, _, _ = _bar()
|
|
100
|
+
|
|
101
|
+
# Act
|
|
102
|
+
line = bar.render(600, 500, elapsed=1.0)
|
|
103
|
+
|
|
104
|
+
# Assert
|
|
105
|
+
assert "100%" in line
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def test_call_where_chunks_arrive_quickly_should_redraw_at_most_every_tenth_of_a_second():
|
|
109
|
+
# Arrange
|
|
110
|
+
bar, written, clock = _bar()
|
|
111
|
+
|
|
112
|
+
# Act
|
|
113
|
+
bar(0, 1000)
|
|
114
|
+
clock.now = 0.05
|
|
115
|
+
bar(100, 1000) # too soon: skipped
|
|
116
|
+
clock.now = 0.2
|
|
117
|
+
bar(200, 1000)
|
|
118
|
+
clock.now = 0.21
|
|
119
|
+
bar(1000, 1000) # the last chunk always draws
|
|
120
|
+
|
|
121
|
+
# Assert
|
|
122
|
+
assert len(written) == 3
|
|
123
|
+
assert all(frame.startswith("\r") for frame in written)
|
|
124
|
+
assert " 20%" in written[1]
|
|
125
|
+
assert "100%" in written[2]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def test_call_where_line_wider_than_terminal_should_cut_it_to_fit():
|
|
129
|
+
# Arrange
|
|
130
|
+
bar, written, _ = _bar(columns=30)
|
|
131
|
+
|
|
132
|
+
# Act
|
|
133
|
+
bar(0, 1000)
|
|
134
|
+
|
|
135
|
+
# Assert
|
|
136
|
+
assert len(written[0]) == 1 + 29
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def test_clear_should_blank_the_drawn_line_and_return_to_its_start():
|
|
140
|
+
# Arrange
|
|
141
|
+
bar, written, clock = _bar()
|
|
142
|
+
bar(0, 1000)
|
|
143
|
+
width = len(written[0]) - 1
|
|
144
|
+
|
|
145
|
+
# Act
|
|
146
|
+
bar.clear()
|
|
147
|
+
|
|
148
|
+
# Assert
|
|
149
|
+
assert written[-1] == "\r" + " " * width + "\r"
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def test_clear_where_nothing_was_drawn_should_write_nothing():
|
|
153
|
+
# Arrange
|
|
154
|
+
bar, written, _ = _bar()
|
|
155
|
+
|
|
156
|
+
# Act
|
|
157
|
+
bar.clear()
|
|
158
|
+
|
|
159
|
+
# Assert
|
|
160
|
+
assert written == []
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@pytest.mark.parametrize(
|
|
164
|
+
("size", "expected"),
|
|
165
|
+
[(0, "0 B"), (999, "999 B"), (1000, "1.0 KB"), (1_234_567, "1.2 MB"), (5_000_000_000, "5.0 GB")],
|
|
166
|
+
)
|
|
167
|
+
def test_format_bytes(size: int, expected: str):
|
|
168
|
+
assert format_bytes(size) == expected
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@pytest.mark.parametrize(
|
|
172
|
+
("no_progress", "term", "terminal", "expected"),
|
|
173
|
+
[
|
|
174
|
+
(False, "xterm-256color", True, True),
|
|
175
|
+
(False, "xterm-256color", False, False),
|
|
176
|
+
(True, "xterm-256color", True, False),
|
|
177
|
+
(False, "dumb", True, False),
|
|
178
|
+
],
|
|
179
|
+
ids=["terminal", "piped", "no-progress flag", "dumb terminal"],
|
|
180
|
+
)
|
|
181
|
+
def test_enabled(monkeypatch, no_progress: bool, term: str, terminal: bool, expected: bool):
|
|
182
|
+
# Arrange
|
|
183
|
+
monkeypatch.setenv("TERM", term)
|
|
184
|
+
monkeypatch.setattr(progress, progress._stdout_is_terminal.__name__, lambda: terminal)
|
|
185
|
+
|
|
186
|
+
# Act / Assert
|
|
187
|
+
assert progress.enabled(no_progress) is expected
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|