itqan-cli 0.4.0__tar.gz → 0.5.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.
Files changed (61) hide show
  1. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/CHANGELOG.md +9 -0
  2. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/PKG-INFO +6 -2
  3. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/README.md +5 -1
  4. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/pyproject.toml +1 -1
  5. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/src/itqan_cli/client.py +2 -9
  6. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/src/itqan_cli/downloader.py +4 -1
  7. itqan_cli-0.5.0/src/itqan_cli/usage.py +97 -0
  8. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/conftest.py +3 -0
  9. itqan_cli-0.5.0/tests/test_usage.py +287 -0
  10. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/.gitignore +0 -0
  11. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/LICENSE +0 -0
  12. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/RELEASING.md +0 -0
  13. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/dart/.gitignore +0 -0
  14. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/dart/README.md +0 -0
  15. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/dart/analysis_options.yaml +0 -0
  16. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/dart/bin/itqan.dart +0 -0
  17. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/dart/lib/itqan_cli.dart +0 -0
  18. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/dart/lib/src/launcher.dart +0 -0
  19. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/dart/lib/src/version.dart +0 -0
  20. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/dart/pubspec.yaml +0 -0
  21. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/dart/test/launcher_test.dart +0 -0
  22. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/npm/README.md +0 -0
  23. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/npm/bin/itqan.js +0 -0
  24. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/scripts/dart_package.py +0 -0
  25. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/scripts/homebrew_formula.py +0 -0
  26. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/scripts/npm_packages.py +0 -0
  27. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/src/itqan_cli/__init__.py +0 -0
  28. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/src/itqan_cli/__main__.py +0 -0
  29. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/src/itqan_cli/add.py +0 -0
  30. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/src/itqan_cli/browse.py +0 -0
  31. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/src/itqan_cli/credentials.py +0 -0
  32. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/src/itqan_cli/exceptions.py +0 -0
  33. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/src/itqan_cli/flutter.py +0 -0
  34. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/src/itqan_cli/init_template.py +0 -0
  35. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/src/itqan_cli/lockfile.py +0 -0
  36. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/src/itqan_cli/main.py +0 -0
  37. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/src/itqan_cli/manifest.py +0 -0
  38. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/src/itqan_cli/progress.py +0 -0
  39. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/src/itqan_cli/semver.py +0 -0
  40. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/src/itqan_cli/updates.py +0 -0
  41. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/__init__.py +0 -0
  42. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_access.py +0 -0
  43. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_add.py +0 -0
  44. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_assets_dir.py +0 -0
  45. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_browse.py +0 -0
  46. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_cli_integration.py +0 -0
  47. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_client.py +0 -0
  48. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_dart_package.py +0 -0
  49. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_downloader.py +0 -0
  50. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_entry_points.py +0 -0
  51. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_flutter.py +0 -0
  52. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_homebrew_formula.py +0 -0
  53. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_init.py +0 -0
  54. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_install_progress.py +0 -0
  55. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_languages.py +0 -0
  56. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_lockfile.py +0 -0
  57. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_login.py +0 -0
  58. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_manifest.py +0 -0
  59. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_npm_packages.py +0 -0
  60. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_progress.py +0 -0
  61. {itqan_cli-0.4.0 → itqan_cli-0.5.0}/tests/test_updates.py +0 -0
@@ -1,3 +1,12 @@
1
+ ## v0.5.0 (2026-10-21)
2
+
3
+ ### Feat
4
+
5
+ - every request, including asset downloads, sends `User-Agent: itqan-cli/<version>`, a random
6
+ install ID (`X-Itqan-Install-Id`, kept in `<config dir>/install-id`) and the command's name
7
+ (`X-Itqan-Command`), so the registry can count CLI installs and usage. `DO_NOT_TRACK=1` or
8
+ `ITQAN_NO_TELEMETRY=1` leaves out the ID and command and creates no `install-id` file.
9
+
1
10
  ## v0.4.0 (2026-10-18)
2
11
 
3
12
  ### Feat
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: itqan-cli
3
- Version: 0.4.0
3
+ Version: 0.5.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
@@ -447,13 +447,17 @@ Add `--help` to any command for all its options. `install` and `browse` read the
447
447
  | `--api-key` | `ITQAN_API_KEY` | The key saved by `itqan login`, if any. |
448
448
  | `--registry-url` | `ITQAN_REGISTRY_URL` | `https://api.cms.itqan.dev`, the public registry. |
449
449
  | | `ITQAN_NO_UPDATE_NOTICE` | Set to `1` to stop `itqan install` saying that newer versions exist. |
450
- | | `ITQAN_CONFIG_DIR` | Where `itqan login` saves keys: `~/.config/itqan` (`%APPDATA%\itqan` on Windows). |
450
+ | | `DO_NOT_TRACK`, `ITQAN_NO_TELEMETRY` | Set to `1` to send no install ID or command name with requests (see below). |
451
+ | | `ITQAN_CONFIG_DIR` | Where `itqan login` saves keys and the install ID: `~/.config/itqan` (`%APPDATA%\itqan` on Windows). |
451
452
  | | `ITQAN_CACHE_DIR` | Dart package only. Where the downloaded program is kept: `~/Library/Caches/itqan` (macOS), `~/.cache/itqan` (Linux), `%LOCALAPPDATA%\itqan` (Windows). |
452
453
  | | `ITQAN_CLI_DOWNLOAD_URL` | Dart package only. A folder (`https://` or `file://`) with a release's programs and `SHA256SUMS`, such as a mirror, used instead of the GitHub Release. |
453
454
 
454
455
  A key passed with `--api-key` or `ITQAN_API_KEY` is used instead of the saved one. The saved key
455
456
  file is readable only by you.
456
457
 
458
+ **Usage counts.** Every request sends the CLI version (`User-Agent`), a random install ID kept in the config folder's `install-id` file, and the running command's name, so Itqan can count installs; nothing else about you or your project is sent.
459
+ Set `DO_NOT_TRACK=1` or `ITQAN_NO_TELEMETRY=1` to send only the version: no install ID or command, and no `install-id` file is created.
460
+
457
461
  ## Troubleshooting
458
462
 
459
463
  **"command not found: itqan".** The folder `itqan` was installed into isn't on your `PATH`. For
@@ -416,13 +416,17 @@ Add `--help` to any command for all its options. `install` and `browse` read the
416
416
  | `--api-key` | `ITQAN_API_KEY` | The key saved by `itqan login`, if any. |
417
417
  | `--registry-url` | `ITQAN_REGISTRY_URL` | `https://api.cms.itqan.dev`, the public registry. |
418
418
  | | `ITQAN_NO_UPDATE_NOTICE` | Set to `1` to stop `itqan install` saying that newer versions exist. |
419
- | | `ITQAN_CONFIG_DIR` | Where `itqan login` saves keys: `~/.config/itqan` (`%APPDATA%\itqan` on Windows). |
419
+ | | `DO_NOT_TRACK`, `ITQAN_NO_TELEMETRY` | Set to `1` to send no install ID or command name with requests (see below). |
420
+ | | `ITQAN_CONFIG_DIR` | Where `itqan login` saves keys and the install ID: `~/.config/itqan` (`%APPDATA%\itqan` on Windows). |
420
421
  | | `ITQAN_CACHE_DIR` | Dart package only. Where the downloaded program is kept: `~/Library/Caches/itqan` (macOS), `~/.cache/itqan` (Linux), `%LOCALAPPDATA%\itqan` (Windows). |
421
422
  | | `ITQAN_CLI_DOWNLOAD_URL` | Dart package only. A folder (`https://` or `file://`) with a release's programs and `SHA256SUMS`, such as a mirror, used instead of the GitHub Release. |
422
423
 
423
424
  A key passed with `--api-key` or `ITQAN_API_KEY` is used instead of the saved one. The saved key
424
425
  file is readable only by you.
425
426
 
427
+ **Usage counts.** Every request sends the CLI version (`User-Agent`), a random install ID kept in the config folder's `install-id` file, and the running command's name, so Itqan can count installs; nothing else about you or your project is sent.
428
+ Set `DO_NOT_TRACK=1` or `ITQAN_NO_TELEMETRY=1` to send only the version: no install ID or command, and no `install-id` file is created.
429
+
426
430
  ## Troubleshooting
427
431
 
428
432
  **"command not found: itqan".** The folder `itqan` was installed into isn't on your `PATH`. For
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "itqan-cli"
3
- version = "0.4.0"
3
+ version = "0.5.0"
4
4
  description = "Itqan Quranic Asset Manager: install and pin Itqan Quranic assets in your project."
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -3,11 +3,11 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from dataclasses import dataclass
6
- from importlib.metadata import PackageNotFoundError, version
7
6
 
8
7
  import requests
9
8
 
10
9
  from itqan_cli.exceptions import RegistryApiError
10
+ from itqan_cli.usage import usage_headers
11
11
 
12
12
 
13
13
  @dataclass(frozen=True, slots=True)
@@ -71,13 +71,6 @@ class Account:
71
71
  DEFAULT_REGISTRY_URL = "https://api.cms.itqan.dev"
72
72
 
73
73
 
74
- def _cli_version() -> str:
75
- try:
76
- return version("itqan-cli")
77
- except PackageNotFoundError: # running from a source checkout that isn't installed
78
- return "unknown"
79
-
80
-
81
74
  def _error_detail(response: requests.Response) -> str:
82
75
  """`: <reason>` from an error body like a 400 validation error, or ""."""
83
76
  try:
@@ -119,7 +112,7 @@ class RegistryClient:
119
112
  headers = {
120
113
  "Accept": "application/json",
121
114
  "Content-Type": "application/json",
122
- "User-Agent": f"itqan-cli/{_cli_version()}",
115
+ **usage_headers(),
123
116
  }
124
117
  if self.api_key:
125
118
  headers["X-API-Key"] = self.api_key
@@ -13,6 +13,7 @@ import requests
13
13
 
14
14
  from itqan_cli.client import ResolvedAssetPayload
15
15
  from itqan_cli.exceptions import DownloadError
16
+ from itqan_cli.usage import usage_headers
16
17
 
17
18
  # Version markers live in <assets_dir>/.itqan/<entry name>, outside the asset folders, so
18
19
  # bundlers that ship a whole folder (Flutter) don't ship them. The folder name is reserved.
@@ -200,7 +201,9 @@ class AssetDownloader:
200
201
 
201
202
  try:
202
203
  with open(temp_fd, "wb") as f_out:
203
- with self.session.get(asset.download_url, stream=True, timeout=self.timeout) as resp:
204
+ with self.session.get(
205
+ asset.download_url, stream=True, timeout=self.timeout, headers=usage_headers()
206
+ ) as resp:
204
207
  if resp.status_code != 200:
205
208
  raise DownloadError(
206
209
  f"Failed to download '{asset.slug}' from {asset.download_url}: HTTP {resp.status_code}"
@@ -0,0 +1,97 @@
1
+ """Headers that let the registry count CLI usage, sent with every request.
2
+
3
+ - ``User-Agent: itqan-cli/<version>``: always.
4
+ - ``X-Itqan-Install-Id: <uuid4>``: a random ID made on first use and kept in
5
+ ``<config dir>/install-id``, so the registry can count installs of the CLI
6
+ without knowing who runs it. Left out when it can't be stored.
7
+ - ``X-Itqan-Command: <command>``: the command that made the request, as
8
+ ``itqan --help`` lists it (``sync`` is sent as ``install``). The registry
9
+ doesn't count asset installs for ``outdated``, the one command that only
10
+ checks versions.
11
+
12
+ ``DO_NOT_TRACK`` or ``ITQAN_NO_TELEMETRY`` set to anything but ``0`` or
13
+ ``false`` leaves out the last two, and no install-id file is made.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from importlib.metadata import PackageNotFoundError, version
19
+ import os
20
+ from pathlib import Path
21
+ import tempfile
22
+ import uuid
23
+
24
+ import click
25
+
26
+ from itqan_cli.credentials import config_dir
27
+
28
+ _OPT_OUT_VARS = ("DO_NOT_TRACK", "ITQAN_NO_TELEMETRY")
29
+
30
+
31
+ def cli_version() -> str:
32
+ try:
33
+ return version("itqan-cli")
34
+ except PackageNotFoundError: # running from a source checkout that isn't installed
35
+ return "unknown"
36
+
37
+
38
+ def user_agent() -> str:
39
+ return f"itqan-cli/{cli_version()}"
40
+
41
+
42
+ def telemetry_disabled() -> bool:
43
+ """True when an opt-out variable is set to anything but empty, ``0`` or ``false``."""
44
+ return any(os.environ.get(var, "").strip().lower() not in ("", "0", "false") for var in _OPT_OUT_VARS)
45
+
46
+
47
+ def install_id_path() -> Path:
48
+ return config_dir() / "install-id"
49
+
50
+
51
+ def install_id() -> str | None:
52
+ """This installation's ID, made and stored on first use. A missing or corrupt file
53
+ gets a new ID; None when it can't be stored, so the CLI carries on without one."""
54
+ try:
55
+ path = install_id_path()
56
+ except RuntimeError: # no home directory to put the config dir in
57
+ return None
58
+ try:
59
+ return str(uuid.UUID(path.read_text(encoding="utf-8").strip()))
60
+ except (OSError, ValueError): # missing, unreadable, not text, or not a UUID
61
+ pass
62
+ new_id = str(uuid.uuid4())
63
+ try:
64
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
65
+ fd, tmp = tempfile.mkstemp(prefix=".install-id_", dir=path.parent)
66
+ try:
67
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
68
+ f.write(new_id + "\n")
69
+ os.replace(tmp, path)
70
+ except BaseException:
71
+ Path(tmp).unlink(missing_ok=True)
72
+ raise
73
+ except OSError:
74
+ return None
75
+ return new_id
76
+
77
+
78
+ def current_command() -> str | None:
79
+ """The `itqan` subcommand running now, or None outside one."""
80
+ ctx = click.get_current_context(silent=True)
81
+ if ctx is None or ctx.parent is None:
82
+ return None
83
+ while ctx.parent.parent is not None:
84
+ ctx = ctx.parent
85
+ return ctx.command.name
86
+
87
+
88
+ def usage_headers() -> dict[str, str]:
89
+ """The headers to send with a request: see the module docstring."""
90
+ headers = {"User-Agent": user_agent()}
91
+ if telemetry_disabled():
92
+ return headers
93
+ if install := install_id():
94
+ headers["X-Itqan-Install-Id"] = install
95
+ if command := current_command():
96
+ headers["X-Itqan-Command"] = command
97
+ return headers
@@ -8,3 +8,6 @@ def isolated_config_dir(tmp_path_factory, monkeypatch):
8
8
  monkeypatch.setenv("ITQAN_CONFIG_DIR", str(tmp_path_factory.mktemp("itqan-config")))
9
9
  monkeypatch.delenv("ITQAN_API_KEY", raising=False)
10
10
  monkeypatch.delenv("ITQAN_REGISTRY_URL", raising=False)
11
+ # The opt-out variables, so the usage-header tests see the default.
12
+ monkeypatch.delenv("DO_NOT_TRACK", raising=False)
13
+ monkeypatch.delenv("ITQAN_NO_TELEMETRY", raising=False)
@@ -0,0 +1,287 @@
1
+ """Tests for the usage-attribution headers sent with every request."""
2
+
3
+ from importlib.metadata import version
4
+ import os
5
+ from pathlib import Path
6
+ import uuid
7
+
8
+ from click.testing import CliRunner
9
+ import pytest
10
+ import responses
11
+
12
+ from itqan_cli import usage
13
+ from itqan_cli.credentials import config_dir
14
+ from itqan_cli.lockfile import AssetLockfile, LockfileEntry, serialize_lockfile
15
+ from itqan_cli.main import cli
16
+
17
+ USER_AGENT = f"itqan-cli/{version('itqan-cli')}"
18
+
19
+
20
+ def _id_file() -> Path:
21
+ return config_dir() / "install-id"
22
+
23
+
24
+ def test_install_id_where_first_run_should_create_a_uuid4_file():
25
+ # Act
26
+ install_id = usage.install_id()
27
+
28
+ # Assert
29
+ assert install_id is not None
30
+ assert uuid.UUID(install_id).version == 4
31
+ assert _id_file().read_text(encoding="utf-8").strip() == install_id
32
+
33
+
34
+ def test_install_id_where_file_exists_should_reuse_it():
35
+ # Arrange
36
+ existing = str(uuid.uuid4())
37
+ _id_file().parent.mkdir(parents=True, exist_ok=True)
38
+ _id_file().write_text(existing + "\n", encoding="utf-8")
39
+
40
+ # Act / Assert
41
+ assert usage.install_id() == existing
42
+ assert usage.install_id() == existing
43
+
44
+
45
+ @pytest.mark.parametrize("content", [b"not-a-uuid", b"", b"\xff\xfe\x00garbage"])
46
+ def test_install_id_where_file_is_corrupt_should_regenerate_it(content: bytes):
47
+ # Arrange
48
+ _id_file().parent.mkdir(parents=True, exist_ok=True)
49
+ _id_file().write_bytes(content)
50
+
51
+ # Act
52
+ install_id = usage.install_id()
53
+
54
+ # Assert
55
+ assert install_id is not None
56
+ assert uuid.UUID(install_id).version == 4
57
+ assert _id_file().read_text(encoding="utf-8").strip() == install_id
58
+
59
+
60
+ @pytest.mark.skipif(os.name != "posix" or os.geteuid() == 0, reason="needs POSIX permissions, not root")
61
+ def test_install_id_where_file_is_unreadable_should_regenerate_it():
62
+ # Arrange
63
+ _id_file().parent.mkdir(parents=True, exist_ok=True)
64
+ _id_file().write_text(str(uuid.uuid4()), encoding="utf-8")
65
+ _id_file().chmod(0)
66
+
67
+ # Act
68
+ install_id = usage.install_id()
69
+
70
+ # Assert
71
+ assert install_id is not None
72
+ assert _id_file().read_text(encoding="utf-8").strip() == install_id
73
+
74
+
75
+ def test_install_id_where_path_is_a_directory_should_return_none():
76
+ # Arrange: can't be read, and can't be replaced by a file either.
77
+ _id_file().mkdir(parents=True)
78
+
79
+ # Act / Assert
80
+ assert usage.install_id() is None
81
+
82
+
83
+ def test_install_id_where_config_dir_cannot_be_written_should_return_none(monkeypatch, tmp_path: Path):
84
+ # Arrange: the config dir's parent is a regular file, so mkdir fails.
85
+ blocker = tmp_path / "blocker"
86
+ blocker.write_text("x", encoding="utf-8")
87
+ monkeypatch.setenv("ITQAN_CONFIG_DIR", str(blocker / "itqan"))
88
+
89
+ # Act / Assert
90
+ assert usage.install_id() is None
91
+
92
+
93
+ def test_install_id_where_write_fails_should_leave_no_temp_files(monkeypatch):
94
+ # Arrange
95
+ def fail(*args, **kwargs):
96
+ raise OSError("disk full")
97
+
98
+ monkeypatch.setattr(usage.os, "replace", fail)
99
+
100
+ # Act
101
+ assert usage.install_id() is None
102
+
103
+ # Assert
104
+ assert list(config_dir().iterdir()) == []
105
+
106
+
107
+ @pytest.mark.parametrize("var", ["DO_NOT_TRACK", "ITQAN_NO_TELEMETRY"])
108
+ @pytest.mark.parametrize("value", ["1", "true", "yes", "TRUE"])
109
+ def test_telemetry_disabled_where_opt_out_set_should_be_true(monkeypatch, var: str, value: str):
110
+ monkeypatch.setenv(var, value)
111
+
112
+ assert usage.telemetry_disabled() is True
113
+
114
+
115
+ @pytest.mark.parametrize("value", ["", "0", "false", "False", " 0 "])
116
+ def test_telemetry_disabled_where_opt_out_unset_or_falsy_should_be_false(monkeypatch, value: str):
117
+ monkeypatch.setenv("DO_NOT_TRACK", value)
118
+ monkeypatch.setenv("ITQAN_NO_TELEMETRY", value)
119
+
120
+ assert usage.telemetry_disabled() is False
121
+
122
+
123
+ def test_usage_headers_where_outside_a_command_should_send_user_agent_and_install_id_only():
124
+ # Act
125
+ headers = usage.usage_headers()
126
+
127
+ # Assert
128
+ assert headers["User-Agent"] == USER_AGENT
129
+ assert headers["X-Itqan-Install-Id"] == usage.install_id()
130
+ assert "X-Itqan-Command" not in headers
131
+
132
+
133
+ @pytest.mark.parametrize("var", ["DO_NOT_TRACK", "ITQAN_NO_TELEMETRY"])
134
+ def test_usage_headers_where_opted_out_should_send_only_user_agent_and_create_no_file(monkeypatch, var: str):
135
+ # Arrange
136
+ monkeypatch.setenv(var, "1")
137
+
138
+ # Act
139
+ headers = usage.usage_headers()
140
+
141
+ # Assert
142
+ assert headers == {"User-Agent": USER_AGENT}
143
+ assert not _id_file().exists()
144
+
145
+
146
+ def test_usage_headers_where_install_id_cannot_be_stored_should_still_send_user_agent(monkeypatch, tmp_path: Path):
147
+ # Arrange
148
+ blocker = tmp_path / "blocker"
149
+ blocker.write_text("x", encoding="utf-8")
150
+ monkeypatch.setenv("ITQAN_CONFIG_DIR", str(blocker / "itqan"))
151
+
152
+ # Act
153
+ headers = usage.usage_headers()
154
+
155
+ # Assert
156
+ assert headers["User-Agent"] == USER_AGENT
157
+ assert "X-Itqan-Install-Id" not in headers
158
+
159
+
160
+ def test_install_id_file_should_not_be_world_writable():
161
+ usage.install_id()
162
+
163
+ if os.name == "posix":
164
+ assert _id_file().stat().st_mode & 0o022 == 0
165
+
166
+
167
+ # --- The headers on the requests commands make ---
168
+
169
+ REGISTRY = "https://api.itqan.dev/api"
170
+ DOWNLOAD = "https://cdn.itqan.dev/assets/tafsir.csv"
171
+
172
+
173
+ def _project(tmp_path: Path, *, locked: bool) -> Path:
174
+ (tmp_path / "itqan-assets.yaml").write_text('schema_version: 1\n\nassets:\n hafs-tafsir:\n version: "^1.0.0"\n')
175
+ if locked:
176
+ lockfile = AssetLockfile(
177
+ lockfile_version=1,
178
+ manifest_schema_version=1,
179
+ assets={"hafs-tafsir": LockfileEntry(slug="hafs-tafsir", constraint="^1.0.0", version="1.0.0")},
180
+ )
181
+ (tmp_path / "itqan-assets.lock").write_bytes(serialize_lockfile(lockfile))
182
+ return tmp_path
183
+
184
+
185
+ def _mock_registry() -> None:
186
+ result = {
187
+ "slug": "hafs-tafsir",
188
+ "asset_version_id": 7,
189
+ "resolved_version": "1.0.0",
190
+ "asset_name": "Hafs Tafsir",
191
+ "download_url": DOWNLOAD,
192
+ }
193
+ responses.add(responses.POST, f"{REGISTRY}/packages/resolve/manifest/", json={"results": [result]})
194
+ responses.add(responses.GET, DOWNLOAD, body=b"surah,ayah,text\n")
195
+
196
+
197
+ def _run(project: Path, command: str):
198
+ return CliRunner().invoke(
199
+ cli,
200
+ [
201
+ command,
202
+ "-m",
203
+ str(project / "itqan-assets.yaml"),
204
+ "-l",
205
+ str(project / "itqan-assets.lock"),
206
+ "--registry-url",
207
+ REGISTRY,
208
+ ],
209
+ )
210
+
211
+
212
+ @responses.activate
213
+ @pytest.mark.parametrize(("command", "sent"), [("install", "install"), ("sync", "install")])
214
+ def test_install_command_should_send_usage_headers_on_api_calls_and_downloads(tmp_path: Path, command: str, sent: str):
215
+ # Arrange
216
+ project = _project(tmp_path, locked=False)
217
+ _mock_registry()
218
+
219
+ # Act
220
+ result = _run(project, command)
221
+
222
+ # Assert
223
+ assert result.exit_code == 0, result.output
224
+ install = usage.install_id()
225
+ assert [call.request.url for call in responses.calls] == [f"{REGISTRY}/packages/resolve/manifest/", DOWNLOAD]
226
+ for call in responses.calls:
227
+ assert call.request.headers["User-Agent"] == USER_AGENT
228
+ assert call.request.headers["X-Itqan-Install-Id"] == install
229
+ assert call.request.headers["X-Itqan-Command"] == sent
230
+
231
+
232
+ @responses.activate
233
+ def test_outdated_command_should_send_outdated_as_command(tmp_path: Path):
234
+ # Arrange
235
+ project = _project(tmp_path, locked=True)
236
+ _mock_registry()
237
+
238
+ # Act
239
+ result = _run(project, "outdated")
240
+
241
+ # Assert
242
+ assert result.exit_code == 0, result.output
243
+ assert len(responses.calls) == 1
244
+ headers = responses.calls[0].request.headers
245
+ assert headers["X-Itqan-Command"] == "outdated"
246
+ assert headers["X-Itqan-Install-Id"] == usage.install_id()
247
+
248
+
249
+ @responses.activate
250
+ @pytest.mark.parametrize("var", ["DO_NOT_TRACK", "ITQAN_NO_TELEMETRY"])
251
+ def test_install_command_where_opted_out_should_send_only_user_agent(monkeypatch, tmp_path: Path, var: str):
252
+ # Arrange
253
+ monkeypatch.setenv(var, "1")
254
+ project = _project(tmp_path, locked=False)
255
+ _mock_registry()
256
+
257
+ # Act
258
+ result = _run(project, "install")
259
+
260
+ # Assert
261
+ assert result.exit_code == 0, result.output
262
+ assert len(responses.calls) == 2
263
+ for call in responses.calls:
264
+ assert call.request.headers["User-Agent"] == USER_AGENT
265
+ assert "X-Itqan-Install-Id" not in call.request.headers
266
+ assert "X-Itqan-Command" not in call.request.headers
267
+ assert not _id_file().exists()
268
+
269
+
270
+ @responses.activate
271
+ def test_install_command_where_install_id_cannot_be_stored_should_still_install(monkeypatch, tmp_path: Path):
272
+ # Arrange
273
+ blocker = tmp_path / "blocker"
274
+ blocker.write_text("x", encoding="utf-8")
275
+ monkeypatch.setenv("ITQAN_CONFIG_DIR", str(blocker / "itqan"))
276
+ project = _project(tmp_path, locked=False)
277
+ _mock_registry()
278
+
279
+ # Act
280
+ result = _run(project, "install")
281
+
282
+ # Assert
283
+ assert result.exit_code == 0, result.output
284
+ assert len(responses.calls) == 2
285
+ for call in responses.calls:
286
+ assert "X-Itqan-Install-Id" not in call.request.headers
287
+ assert call.request.headers["X-Itqan-Command"] == "install"
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